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.)48.5 KB · 827 lines · loads cdn.jsdelivr.net/npm/three@0.159.0/build/three.min.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="#f7f5fc">
<title>Cell Atlas · Inside an animal cell</title>
<style>
:root{color-scheme:light;--ink:#211a36;--muted:#655d76;--purple:#6643cc;--line:#e8e2f0;--color:#b599fa}
*{box-sizing:border-box}
body{margin:0;color:var(--ink);background:radial-gradient(ellipse at 92% 0%,#eee7fa,transparent 36rem),#f7f5fc;font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}
button,input{font:inherit}
button{cursor:pointer;-webkit-tap-highlight-color:transparent}
button:focus-visible,input:focus-visible{outline:3px solid #9677f3;outline-offset:3px}
svg{display:block;flex:none}
.mast{height:65px;border-bottom:1px solid var(--line);background:#faf9fdc9}
.mast-inner{max-width:1332px;margin:auto;height:100%;padding:0 32px;display:flex;align-items:center;justify-content:space-between}
.brand,.mast-note{display:flex;align-items:center;gap:9px}
.brand{font-size:17px;font-weight:780;letter-spacing:-.04em}
.brand-mark{width:34px;height:34px;display:grid;place-items:center;color:#fff;background:linear-gradient(145deg,#8965ee,#6039c7);border-radius:11px;box-shadow:0 3px 9px #6543cb35}
.mast-note{font-size:13px;font-weight:650;color:#635978}
.mast-note svg{color:#8863e1}
main{max-width:1332px;margin:auto;padding:32px 32px 27px}
.intro{margin-bottom:25px}
.eyebrow{margin:0 0 8px;color:#6948c5;font-weight:780;font-size:11px;letter-spacing:.15em;text-transform:uppercase}
h1{margin:0;font-size:clamp(33px,5vw,54px);line-height:1.04;letter-spacing:-.064em;font-weight:790}
.intro p:last-child{margin:11px 0 0;color:var(--muted);font-size:15px;line-height:1.47}
.layout{display:grid;grid-template-columns:minmax(0,1fr) 320px;gap:18px;align-items:start}
.model,.parts{min-width:0;background:#fff;border:1px solid var(--line);border-radius:21px;box-shadow:0 8px 28px #3320530a}
.model{overflow:hidden}
.stage{position:relative;height:clamp(435px,58vh,558px);overflow:hidden;isolation:isolate;background:radial-gradient(ellipse at 48% 46%,#382263 0%,#26194a 35%,#190f31 69%,#120b23 100%);color:white}
.stage:before,.stage:after{content:"";position:absolute;inset:0;pointer-events:none;z-index:-1}
.stage:before{background-image:radial-gradient(circle,#ad9cdb4b .65px,transparent 1.4px),radial-gradient(circle,#c5b6f738 .9px,transparent 1.6px);background-size:29px 29px,73px 73px;background-position:13px 6px,38px 19px;mask-image:radial-gradient(ellipse,#0002 8%,#000 85%)}
.stage:after{background:linear-gradient(#9887d310 1px,transparent 1px),linear-gradient(90deg,#9887d310 1px,transparent 1px);background-size:48px 48px;mask-image:radial-gradient(ellipse,#000 0%,transparent 85%)}
.canvas,.canvas canvas{position:absolute;inset:0;width:100%;height:100%;display:block;touch-action:none}
.canvas{cursor:grab}.canvas:active{cursor:grabbing}
.toolbar,.stage-footer{position:absolute;z-index:3;display:flex;justify-content:space-between;gap:8px;pointer-events:none}
.toolbar{inset:17px 17px auto;align-items:flex-start}
.stage-footer{inset:auto 17px 16px;align-items:flex-end}
.state{display:flex;align-items:center;gap:8px;background:#1b1335c7;border:1px solid #b797f747;border-radius:30px;padding:8px 11px;font-size:11px;font-weight:650;color:#e8dcf9;white-space:nowrap;margin-top:3px}
.state i{width:7px;height:7px;background:#c09dff;border-radius:50%;box-shadow:0 0 10px #b998ffd0}
.state[data-state="ready"] i{background:#74e9c7;box-shadow:0 0 10px #72e9c790}
.state[data-state="paused"] i{background:#ffd098;box-shadow:none}
.cut,.reset{pointer-events:auto;border:1px solid #b797f763;background:#2a1c49eb;color:white}
.cut{display:flex;align-items:center;gap:8px;min-height:44px;padding:0 10px 0 12px;border-radius:11px;font-size:12px;font-weight:680;white-space:nowrap}
.cut:hover,.reset:hover,.cut[aria-checked="true"]{border-color:#c6a7ff}
.cut[aria-checked="true"]{background:#462c73}
.toggle{position:relative;width:29px;height:17px;border-radius:20px;background:#6b5b85;transition:background .22s}
.toggle:after{content:"";position:absolute;left:3px;top:3px;width:11px;height:11px;background:#fff;border-radius:50%;transition:transform .22s}
.cut[aria-checked="true"] .toggle{background:#a77ef8}
.cut[aria-checked="true"] .toggle:after{transform:translateX(12px)}
.reset{min-width:44px;height:44px;display:grid;place-items:center;border-radius:10px;color:#efdcff}
.gestures{display:flex;align-items:center;gap:12px;min-height:34px;padding:0 10px;border-radius:8px;background:#170f2acb;color:#d5c9ee;font-size:11px;font-weight:580}
.gestures span{display:flex;align-items:center;gap:5px;white-space:nowrap}
.gestures svg{color:#ac95d7}
.touch{display:none!important}
@media(pointer:coarse){.touch{display:flex!important}.mouse{display:none!important}}
.annotation{position:absolute;z-index:2;inset:0;pointer-events:none}
.annotation[hidden]{display:none}
.label-line,.label-dot,.label-name{position:absolute}
.label-line{height:1px;background:#dec8ffbc;transform-origin:0 0}
.label-dot{width:9px;height:9px;border:2px solid #fff;border-radius:50%;background:var(--color);box-shadow:0 0 0 3px #27153d8c,0 0 12px var(--color);transform:translate(-50%,-50%)}
.label-name{display:flex;align-items:center;gap:7px;width:max-content;max-width:min(200px,48%);padding:7px 10px;border:1px solid #c3a1ec82;border-radius:7px;color:#f7eeff;background:#221437ef;box-shadow:0 4px 16px #10091e80;font-size:11px;font-weight:690;line-height:1.25}
.label-name:before{content:"";flex:none;width:6px;height:6px;background:var(--color);border-radius:50%}
.timeline{padding:13px 17px 12px;display:grid;grid-template-columns:44px minmax(0,1fr) auto;grid-template-rows:auto auto;column-gap:13px;align-items:center}
.play{grid-column:1;grid-row:1/3;width:44px;height:44px;display:grid;place-items:center;border:0;border-radius:13px;color:white;background:#6844d2;box-shadow:0 3px 9px #6844d244}
.play:hover{background:#5533b9}
.timeline-meta{grid-column:2;grid-row:1;display:flex;align-items:center;justify-content:space-between;gap:6px}
.timeline-meta strong{font-size:13px;letter-spacing:-.01em}
.timeline-index{color:#6d5b94;font-size:11px;font-weight:650;white-space:nowrap;font-variant-numeric:tabular-nums}
.scrub{grid-column:2;grid-row:2;position:relative;height:31px;display:flex;align-items:center}
.track{position:absolute;left:8px;right:8px;height:5px;border-radius:10px;background:linear-gradient(90deg,#7955df var(--progress,0%),#e9e1f6 var(--progress,0%));display:flex;justify-content:space-between;align-items:center;pointer-events:none}
.track i{width:3px;height:3px;border-radius:50%;background:#b29dd4}
#slider{z-index:1;display:block;appearance:none;-webkit-appearance:none;width:100%;height:31px;margin:0;background:transparent;cursor:pointer;touch-action:pan-y}
#slider::-webkit-slider-runnable-track{height:16px;background:transparent}
#slider::-webkit-slider-thumb{appearance:none;-webkit-appearance:none;width:16px;height:16px;border-radius:50%;background:#7751da;border:2px solid #fff;box-shadow:0 0 0 1px #7650d8,0 2px 5px #5b36b24d}
#slider::-moz-range-track{height:16px;background:transparent}
#slider::-moz-range-thumb{box-sizing:border-box;width:16px;height:16px;border-radius:50%;background:#7751da;border:2px solid #fff;box-shadow:0 0 0 1px #7650d8}
.rebuild{grid-column:3;grid-row:1/3;min-height:44px;padding:0 12px;display:flex;align-items:center;justify-content:center;gap:7px;border:1px solid #e3d9f5;border-radius:11px;background:#faf7ff;color:#5f3cbd;font-size:12px;font-weight:720;white-space:nowrap}
.rebuild:hover{background:#f0e8fd}
.parts{padding:17px 16px 14px}
.parts-head{display:flex;justify-content:space-between;align-items:center;margin:0 0 12px;gap:8px}
.parts-head h2{margin:0;font-size:20px;font-weight:770;letter-spacing:-.045em}
.count{padding:4px 8px;border-radius:7px;background:#f0eafa;color:#6849aa;font-size:11px;font-weight:750;white-space:nowrap;font-variant-numeric:tabular-nums}
.detail{position:relative;min-height:130px;padding:13px;background:linear-gradient(129deg,#f2ebfd,#fcf9ff);border:1px solid #eae0f9;border-radius:13px;overflow:hidden}
.detail:after{content:"";position:absolute;top:-46px;right:-22px;width:122px;height:122px;border-radius:50%;border:1px solid #b899e93e;box-shadow:0 0 0 10px #b899e917,0 0 0 22px #b899e912;pointer-events:none}
.detail-kicker{position:relative;z-index:1;display:flex;align-items:center;gap:7px;margin:0 0 7px;color:#6948b2;font-size:9px;font-weight:800;letter-spacing:.12em;text-transform:uppercase}
.detail-kicker i{width:7px;height:7px;border-radius:50%;background:var(--color);box-shadow:0 0 0 2px white}
.detail h3{position:relative;z-index:1;margin:0 0 5px;font-weight:770;font-size:20px;letter-spacing:-.041em;line-height:1.15}
.description{margin:0;color:#554a68;font-size:12px;line-height:1.43;max-width:35ch}
.parts-list{list-style:none;margin:9px 0 0;padding:0;display:grid;gap:1px}
.part-row{display:grid;grid-template-columns:10px minmax(0,1fr) 18px;gap:9px;align-items:center;width:100%;padding:0 8px;min-height:33px;border:1px solid transparent;border-radius:8px;color:#3e3452;background:transparent;text-align:left;font-size:12px;font-weight:620;line-height:1.22}
.part-row:hover{background:#f7f3ff}
.part-row[aria-current="true"]{background:#f3edff;border-color:#eadffa;color:#5835a5;font-weight:750}
.part-row[data-built="false"]{color:#625970}
.part-dot{width:9px;height:9px;border-radius:50%;background:var(--color);box-shadow:inset 0 0 0 1px #29184530}
.part-row[data-built="false"] .part-dot{background:none;box-shadow:inset 0 0 0 1.6px var(--color)}
.number{text-align:right;color:#77688f;font-size:10px;font-weight:650;font-variant-numeric:tabular-nums}
@media(max-width:1000px){.layout{grid-template-columns:minmax(0,1fr) 285px;gap:14px}.mast-inner,main{padding-left:23px;padding-right:23px}.gestures{gap:8px}}
@media(max-width:760px){
  .mast{height:55px}.mast-inner,main{padding-left:14px;padding-right:14px}main{padding-top:22px}.intro{margin-bottom:18px}.intro p:last-child{font-size:14px;margin-top:8px}.mast-note{font-size:11px}
  .layout{display:flex;flex-direction:column;gap:13px}.model,.parts{width:100%;border-radius:17px}.stage{height:clamp(292px,52vh,455px)}.toolbar{inset:10px 10px auto}.stage-footer{inset:auto 10px 10px}
  .timeline{padding:10px;column-gap:9px}.rebuild{padding:0 9px}.parts{padding:14px}.detail{min-height:97px}.parts-list{grid-template-columns:repeat(2,minmax(0,1fr));column-gap:4px}
  .part-row{min-height:45px;padding:0 6px;gap:6px;font-size:11px;grid-template-columns:8px minmax(0,1fr) 14px}
}
@media(max-width:365px){.mast-note svg,.pick-hint{display:none!important}.state{font-size:10px}.cut{gap:5px}.timeline{column-gap:7px}.timeline-meta strong{font-size:12px}}
@media(pointer:coarse) and (min-width:761px){.part-row{min-height:44px}}
@media(prefers-reduced-motion:reduce){*,*:before,*:after{transition:none!important}}
</style>
</head>
<body>
<header class="mast"><div class="mast-inner">
  <div class="brand"><span class="brand-mark"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.45" aria-hidden="true"><path d="M21 11.7c.1 4.6-4.2 8.3-9 8.5-5 .2-8.9-3.1-9-7.7C2.9 7.9 6.8 4 11.8 3.8 16.7 3.5 21 7.2 21 11.7Z"/><circle cx="10.9" cy="11.6" r="3.2"/><path d="m16 9 .6-1.1m-1.1 7.2 1.3.6M6.8 14l.6 1.5" stroke-linecap="round"/></svg></span>Cell Atlas</div>
  <div class="mast-note"><svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linejoin="round" aria-hidden="true"><path d="M12 3 21 8v8l-9 5-9-5V8l9-5Z"/><path d="m3 8 9 5 9-5m-9 5v8"/></svg>Interactive 3D model</div>
</div></header>
<main>
  <div class="intro"><p class="eyebrow">Cell biology</p><h1>Inside an animal cell</h1><p>Watch it come together, then explore what each part does.</p></div>
  <div class="layout">
    <section class="model" aria-label="Interactive animal cell">
      <div class="stage">
        <div class="canvas" id="canvas"></div>
        <div class="toolbar">
          <div class="state" id="state" data-state="building"><i></i><span id="stateText">Building cell</span></div>
          <button class="cut" id="cut" type="button" role="switch" aria-checked="false"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" aria-hidden="true"><circle cx="12" cy="12" r="8.5"/><path d="m5.8 18.2 12.4-12.4m-7 12 6.6-6.6m-2.6 7.1 3.1-3.1"/></svg>Cut open<span class="toggle" aria-hidden="true"></span></button>
        </div>
        <div class="annotation" id="annotation" aria-hidden="true"><div class="label-line" id="labelLine"></div><div class="label-dot" id="labelDot"></div><div class="label-name" id="labelName"></div></div>
        <div class="stage-footer">
          <div class="gestures" aria-hidden="true"><span><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><ellipse cx="12" cy="12" rx="10" ry="5" transform="rotate(-30 12 12)"/><path d="M14 4h5v5m-9 11H5v-5"/></svg>Drag to orbit</span><span class="mouse">Scroll to zoom</span><span class="touch">Pinch to zoom</span><span class="pick-hint"><span class="mouse">Click a part</span><span class="touch">Tap a part</span></span></div>
          <button class="reset" id="reset" type="button" aria-label="Reset view" title="Reset view"><svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linejoin="round" stroke-linecap="round" aria-hidden="true"><path d="M8 4H4v4m12-4h4v4m0 8v4h-4m-8 0H4v-4"/><circle cx="12" cy="12" r="3"/></svg></button>
        </div>
      </div>
      <div class="timeline">
        <button class="play" id="play" type="button" aria-label="Pause build"></button>
        <div class="timeline-meta"><strong>Build timeline</strong><span class="timeline-index" id="timelineIndex">0 / 11 parts</span></div>
        <div class="scrub"><div class="track" id="track" aria-hidden="true"></div><input id="slider" type="range" min="0" max="11" step="1" value="0" aria-label="Cell build progress"></div>
        <button class="rebuild" id="rebuild" type="button"><svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4.5 11a7.6 7.6 0 1 1 1.8 6M4 5.6v5.9h5.9"/></svg>Rebuild</button>
      </div>
    </section>
    <aside class="parts" aria-labelledby="partsTitle">
      <div class="parts-head"><h2 id="partsTitle">Cell parts</h2><span class="count" id="count">0 of 11</span></div>
      <div class="detail" id="detail"><p class="detail-kicker"><i></i><span id="kicker">Starting layer</span></p><h3 id="partTitle">Cell membrane</h3><p class="description" id="description">The membrane surrounds the cell and controls what goes in and out.</p></div>
      <ol class="parts-list" id="partsList"></ol>
    </aside>
  </div>
</main>
<script src="https://cdn.jsdelivr.net/npm/three@0.159.0/build/three.min.js"></script>
<script>
(() => {
  "use strict";
  const parts = [
    ["Cell membrane","#ba9afc",[-2.48,.82,.6],"The membrane surrounds the cell and controls what goes in and out."],
    ["Nucleus","#aa85ee",[-.96,.51,.52],"The nucleus holds DNA, the instructions that help run the cell."],
    ["Nucleolus","#f1a0e5",[-.65,.30,.46],"The nucleolus makes the pieces that become ribosomes."],
    ["Rough endoplasmic reticulum","#6fbaff",[.56,.75,.1],"This folded network uses attached ribosomes to make and move proteins."],
    ["Smooth endoplasmic reticulum","#57dab4",[1.35,1.23,.06],"This network makes fats the cell needs and helps break down some harmful chemicals."],
    ["Ribosomes","#f2bc60",[.31,1.49,-.1],"Ribosomes build proteins by joining small building blocks called amino acids."],
    ["Golgi apparatus","#f38cbd",[.90,-1.00,.34],"The Golgi apparatus sorts and packs proteins and fats so they can go where they are needed."],
    ["Mitochondria","#ffa371",[-1.63,-1.18,.12],"Mitochondria turn energy from food into a form the cell can use."],
    ["Lysosomes","#bedf6c",[1.66,-1.48,.13],"Lysosomes break down worn-out cell parts and recycle the pieces."],
    ["Vesicles","#72cee7",[1.74,-.61,.24],"Vesicles are tiny sacs that carry or store materials."],
    ["Centrioles","#efbd76",[-.34,-1.59,.11],"Centrioles help organize fibers that move chromosomes when a cell divides."],
    ["Cytoskeleton","#a09cf3",[2.30,.73,-.23],"The cytoskeleton is a web of fibers that gives the cell shape and helps move things inside it."]
  ].map(([name,color,anchor,text])=>({name,color,anchor,text}));
  const get = id => document.getElementById(id);
  const host = get("canvas"), slider = get("slider"), track = get("track"), play = get("play"), cutButton = get("cut");
  const annotation = get("annotation"), label = get("labelName"), dot = get("labelDot"), labelLine = get("labelLine");
  const reduced = matchMedia("(prefers-reduced-motion: reduce)").matches;
  const tau = Math.PI*2, total = parts.length-1, interval = 760;
  const clamp = (n,lo,hi) => Math.max(lo,Math.min(hi,n));
  const defaultView = {yaw:-.12,pitch:.14,dist:10.55,x:0,y:0,z:0};
  const eye = {...defaultView}, goal = {...defaultView};
  const frames = parts.map(()=>({born:0,size:1,x:0,y:0,z:0}));
  const rows = [];
  let step = 0, selected = 0, cut = false, playing = true;
  let demo = location.hash === "#demo", cue = -1, demoStart = performance.now();
  let nextPart = demoStart+1120, previous = demoStart, width = 1, height = 1;

  parts.forEach((part,id) => {
    track.append(document.createElement("i"));
    if (!id) return;
    const item = document.createElement("li");
    const button = document.createElement("button");
    button.type = "button";
    button.className = "part-row";
    button.style.setProperty("--color",part.color);
    const swatch = document.createElement("span");
    swatch.className = "part-dot";
    swatch.setAttribute("aria-hidden","true");
    const name = document.createElement("span");
    name.textContent = part.name;
    const number = document.createElement("span");
    number.className = "number";
    number.textContent = String(id).padStart(2,"0");
    number.setAttribute("aria-hidden","true");
    button.append(swatch,name,number);
    item.append(button);
    get("partsList").append(item);
    rows[id] = button;
    button.addEventListener("click",()=>select(id));
  });

  function updateInterface() {
    const part = parts[selected];
    slider.value = step;
    slider.setAttribute("aria-valuetext",step ? step+" of "+total+" parts, "+parts[step].name : "Cell membrane only");
    track.style.setProperty("--progress",100*step/total+"%");
    get("timelineIndex").textContent = step+" / "+total+" parts";
    get("count").textContent = step+" of "+total;
    get("stateText").textContent = demo ? "Demo playing" : step===total ? "Ready to explore" : playing ? "Building cell" : "Build paused";
    get("state").dataset.state = step===total ? "ready" : playing ? "building" : "paused";
    play.innerHTML = '<svg width="19" height="19" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">'+(playing ? '<rect x="6.5" y="5" width="3.5" height="14" rx="1"/><rect x="14" y="5" width="3.5" height="14" rx="1"/>' : '<path d="M8 5.8c0-.8.9-1.25 1.55-.81l9.1 6.2a.98.98 0 0 1 0 1.62l-9.1 6.2c-.65.44-1.55-.02-1.55-.81Z"/>')+'</svg>';
    const playLabel = playing ? "Pause build" : step===total ? "Replay build" : "Resume build";
    play.setAttribute("aria-label",playLabel);
    play.title = playLabel;
    cutButton.setAttribute("aria-checked",String(cut));
    get("detail").style.setProperty("--color",part.color);
    get("kicker").textContent = selected ? "Part "+String(selected).padStart(2,"0")+" of "+total : "Starting layer";
    get("partTitle").textContent = part.name;
    get("description").textContent = part.text;
    annotation.style.setProperty("--color",part.color);
    label.textContent = part.name;
    rows.forEach((button,id)=>{
      button.dataset.built = String(id<=step);
      button.setAttribute("aria-current",String(id===selected));
    });
  }

  function buildTo(value,instant=false) {
    const old = step, now = performance.now();
    step = clamp(value,0,total);
    selected = step;
    for (let i=old+1;i<=step;i++) frames[i].born = instant ? now-1000 : now;
    if (step===total) playing = false;
    updateInterface();
  }
  function turnTo(yaw) {
    goal.yaw = eye.yaw+Math.atan2(Math.sin(yaw-eye.yaw),Math.cos(yaw-eye.yaw));
  }
  function resetView() {
    Object.assign(goal,defaultView);
    turnTo(cut ? .56 : defaultView.yaw);
  }
  function select(id) {
    playing = false;
    if (id>step) buildTo(id,true);
    selected = id;
    const [x,y,z] = parts[id].anchor;
    goal.x=x*.80; goal.y=y*.80; goal.z=(cut ? Math.min(0,z) : z)*.57;
    goal.dist = id===11 ? 8.0 : id===5 ? 5.9 : 6.8;
    if (!cut) {turnTo(-.12+clamp(x*.12,-.32,.32)); goal.pitch=.16;}
    updateInterface();
  }
  function setCut(value) {
    cut = value;
    if (cut) {turnTo(.57);goal.pitch=.21;goal.z=Math.min(0,goal.z);}
    updateInterface();
  }
  function rebuild() {
    cut=false; playing=true; nextPart=performance.now()+1050;
    resetView(); buildTo(0);
  }
  get("reset").addEventListener("click",resetView);
  get("rebuild").addEventListener("click",rebuild);
  cutButton.addEventListener("click",()=>setCut(!cut));
  slider.addEventListener("input",()=>{playing=false;resetView();buildTo(Number(slider.value),true);});
  play.addEventListener("click",()=>{
    if (step===total) {rebuild();return;}
    playing=!playing;
    nextPart=performance.now()+480;
    updateInterface();
  });

  function seeded(seed) {
    return () => {
      seed=(Math.imul(seed,1664525)+1013904223)>>>0;
      return seed/4294967296;
    };
  }
  const samples = (count,fn) => Array.from({length:count},(_,i)=>fn(i/(count-1),i));
  function surface(x,y,z) {
    const r=1+.044*Math.sin(5*x+2*z)*Math.cos(4*y-z)+.032*Math.sin(7*y+2*x)+.023*Math.sin(8*z-4*x+3*y);
    return [3.01*x*r+.15*y*y,2.46*y*r-.13*x,2.09*z*r];
  }
  function roughPoint(k,t,b=0) {
    const a=-.99+2.53*t+k*.046, thick=.022+.115*Math.sin(Math.PI*t)**.46;
    const r=1.04+k*.176+.045*Math.sin(t*7+k)+Math.cos(b)*thick;
    return [-.51+Math.cos(a)*r,.13+.90*Math.sin(a)*r,-.30+k*.083+.115*Math.sin(t*5+k*.38)+Math.sin(b)*thick*.44];
  }
  function golgiPoint(k,t,b=0) {
    const u=t*2-1, thick=.042+.24*Math.sin(Math.PI*t)**.48;
    return [.88+u*(.67-k*.043),-1.32+k*.153+.21*u*u-.10*u+Math.sin(b)*thick*.23+.028*Math.sin(5*u+k*.59),-.13+k*.055+Math.cos(b)*thick+.037*Math.sin(t*12+k*.36)];
  }
  const smoothPaths = [
    [[.69,1.23,-.18],[.84,1.51,-.18],[1.05,1.48,-.10],[1.20,1.32,-.04],[1.46,1.40,-.02],[1.64,1.32,.03],[1.72,1.09,-.01],[1.90,1.03,-.10]],
    [[.82,1.55,-.16],[.92,1.76,-.18],[1.21,1.70,-.17],[1.37,1.52,-.08],[1.63,1.61,-.09],[1.73,1.48,-.19]],
    [[1.04,1.48,-.10],[1.01,1.28,-.03],[1.12,1.02,.06],[1.39,.99,.09],[1.49,1.16,.08],[1.38,1.37,-.04]],
    [[1.11,1.03,.06],[.84,.92,.01],[.71,.76,-.09],[.87,.62,-.15],[1.09,.73,-.12],[1.19,.86,-.09],[1.37,.86,-.09],[1.51,.72,-.10]],
    [[1.24,1.69,-.16],[1.31,1.81,-.31],[1.50,1.79,-.40],[1.68,1.57,-.41],[1.82,1.54,-.37],[1.98,1.42,-.24]],
    [[1.48,1.18,.08],[1.70,1.02,.06],[1.84,.86,.05],[1.67,.69,.03],[1.49,.73,-.09]],
    [[.73,1.23,-.18],[.58,1.13,-.33],[.66,.97,-.40],[.86,.95,-.41],[1.02,1.06,-.43]]
  ];
  const mitochondria = [
    {p:[-1.67,-1.19,.025],a:-.41,s:1},{p:[-1.83,1.26,-.13],a:.59,s:.89},{p:[2.09,.33,-.15],a:-1.28,s:.88},
    {p:[.56,1.91,-.80],a:-.12,s:.68},{p:[.28,-1.86,-.80],a:.39,s:.70}
  ];
  const lysosomes = [[1.66,-1.48,-.04,.27],[-2.13,-.48,-.35,.22],[.01,1.38,-.03,.20],[-.87,-1.77,-.32,.17]];
  const vesicles = [[1.74,-.61,.16,.19],[1.96,-.81,.25,.12],[1.65,-.93,.66,.13],[1.98,-1.03,-.22,.16],[.84,-1.63,-.04,.13],[-1.38,.97,.14,.12],[-1.89,.36,.37,.16],[1.81,1.31,-.33,.12],[.43,.43,.84,.10],[-.56,1.80,-.58,.13]];
  const centrioles = [[-.49,-1.55,-.05,-.57],[-.11,-1.59,-.13,1.09]];
  const random = seeded(437);
  const skinSpecks = samples(185,()=>{
    const a=random()*tau,z=random()*2-1,r=Math.sqrt(1-z*z);
    return [...surface(r*Math.cos(a),r*Math.sin(a),z).map(n=>n*.994),.009+random()*.014];
  });
  const ribosomes = [];
  for (let i=0;i<94;i++) {
    const a=random()*tau,r=.46+.51*Math.sqrt(random());
    const x=2.63*r*Math.cos(a),y=2.03*r*Math.sin(a),z=(random()-.51)*1.62;
    if (Math.hypot(x+.64,y-.23,z+.18)>1.07) ribosomes.push([x,y,z,.021+random()*.019]);
  }
  for (let k=0;k<4;k++) for (let j=0;j<13;j++) ribosomes.push([...roughPoint(k,.06+.88*j/12,1.30),.024+random()*.013]);
  ribosomes.push([.31,1.49,-.10,.041]);
  const fibers = Array.from({length:22},(_,i)=>{
    const a=i*tau/22+(random()-.5)*.34,turn=(random()-.5)*1.9;
    return samples(9,t=>{
      const a1=a+turn*(1-t),r=.22+.72*t;
      return [-.24*(1-t)+Math.cos(a1)*r*2.84,-.97*(1-t)+Math.sin(a1)*r*2.22,-.64+Math.sin(i*.91)*.55+.33*Math.sin(t*3+i)];
    });
  });
  fibers.push(samples(16,t=>[2.43*Math.cos(-.46+t*1.03),2.03*Math.sin(-.46+t*1.03),-.26+.09*Math.sin(t*8)]));
  const fold = samples(48,t=>[(t-.5)*1.01,.048*Math.sin((t-.5)*5)+.155*Math.sin(t*tau*4.1)*Math.sin(t*Math.PI)**.5,.091+Math.sin(t*Math.PI)*.052]);

  function webGL(T) {
    const scene = new T.Scene();
    const camera = new T.PerspectiveCamera(36,1,.08,80);
    const renderer = new T.WebGLRenderer({alpha:true,antialias:true,powerPreference:"high-performance"});
    renderer.setClearColor(0x000000,0);
    renderer.setPixelRatio(Math.min(devicePixelRatio||1,1.75));
    renderer.outputColorSpace=T.SRGBColorSpace;
    renderer.toneMapping=T.ACESFilmicToneMapping;
    renderer.toneMappingExposure=1.11;
    const plane = new T.Plane(new T.Vector3(0,0,-1),0);
    const clipped = [plane], clear = [];
    const vector = p=>new T.Vector3(p[0],p[1],p[2]);
    const sphere = new T.SphereGeometry(1,32,23), bead = new T.IcosahedronGeometry(1,1);
    const temp = new T.Object3D();
    const ray = new T.Raycaster(), ndc = new T.Vector2();
    const groups = parts.map(()=>{
      const group = new T.Group(); scene.add(group); return group;
    });
    scene.add(new T.HemisphereLight(0xe8dcff,0x512b69,1.63));
    for (const [color,power,p] of [[0xffe6fc,2.40,[-4,6,7]],[0x8fa5ff,1.55,[4,2,-5]],[0xf68fb4,.70,[1,-5,3]]]) {
      const light=new T.DirectionalLight(color,power);
      light.position.set(...p);
      scene.add(light);
    }
    const matte=(color,emissive=color,emissiveIntensity=.12,extras={})=>new T.MeshStandardMaterial({color,emissive,emissiveIntensity,roughness:.53,metalness:.09,...extras});
    const glassMaterials = [];
    function glass(base,edge,core,rim,power,side=T.FrontSide) {
      const material=new T.ShaderMaterial({
        side,transparent:true,depthWrite:false,clipping:true,
        uniforms:{baseTint:{value:new T.Color(base)},rimTint:{value:new T.Color(edge)},core:{value:core},rim:{value:rim},power:{value:power},clock:{value:0}},
        vertexShader:[
          "varying vec3 nrm, towardEye, local;",
          "#include <clipping_planes_pars_vertex>",
          "void main(){ vec4 mvPosition = modelViewMatrix * vec4(position,1.0);",
          "nrm=normalize(normalMatrix*normal); towardEye=-mvPosition.xyz; local=position;",
          "gl_Position=projectionMatrix*mvPosition;",
          "#include <clipping_planes_vertex>",
          "}"
        ].join("\n"),
        fragmentShader:[
          "uniform vec3 baseTint,rimTint; uniform float core,rim,power,clock;",
          "varying vec3 nrm,towardEye,local;",
          "#include <clipping_planes_pars_fragment>",
          "void main(){",
          "#include <clipping_planes_fragment>",
          "vec3 normal=normalize(nrm);",
          "float facing=abs(dot(normal,normalize(towardEye)));",
          "float fresnel=pow(1.0-clamp(facing,0.0,1.0),power);",
          "float ripple=sin(local.y*14.0+local.z*6.0+sin(local.x*6.0)+clock*.52);",
          "float grain=sin(local.x*161.0+sin(local.y*142.0)+local.z*129.0)*sin(local.y*132.0+local.z*173.0);",
          "float shade=.56+.25*normal.y+.073*ripple;",
          "vec3 tint=mix(baseTint,rimTint,clamp(fresnel*1.11+shade*.24,0.0,1.0))*(.87+shade*.44);",
          "gl_FragColor=vec4(tint,clamp(core*(.85+shade*.38)+rim*fresnel+.018*grain,0.0,.94));",
          "#include <colorspace_fragment>",
          "}"
        ].join("\n")
      });
      glassMaterials.push(material);
      return material;
    }
    function mesh(group,geometry,material,p=[0,0,0],s=[1,1,1],id=0,order=0) {
      const object=new T.Mesh(geometry,material);
      object.position.set(...p); object.scale.set(...s);
      object.userData.part=id; object.renderOrder=order;
      group.add(object);
      return object;
    }
    function dots(group,positions,material,id=0) {
      const batch=new T.InstancedMesh(bead,material,positions.length);
      positions.forEach(([x,y,z,r],i)=>{
        temp.position.set(x,y,z);temp.scale.setScalar(r);temp.rotation.set(i*.24,i*.47,i*.19);temp.updateMatrix();
        batch.setMatrixAt(i,temp.matrix);
      });
      batch.userData.part=id;
      group.add(batch);
    }
    function tube(group,points,r,material,id=0,segments=36,closed=false) {
      const curve=new T.CatmullRomCurve3(points.map(vector),closed);
      return mesh(group,new T.TubeGeometry(curve,segments,r,7,closed),material,[0,0,0],[1,1,1],id);
    }
    function shaped(sample,detail) {
      const geo=new T.SphereGeometry(1,detail,Math.floor(detail*.7));
      const p=geo.attributes.position;
      for (let i=0;i<p.count;i++) p.setXYZ(i,...sample(p.getX(i),p.getY(i),p.getZ(i)));
      geo.computeVertexNormals();
      return geo;
    }
    function ribbon(group,fn,material,id) {
      const vertices=[],indices=[],sections=52,sides=12;
      for (let i=0;i<=sections;i++) for (let j=0;j<sides;j++) vertices.push(...fn(i/sections,j*tau/sides));
      for (let i=0;i<sections;i++) for (let j=0;j<sides;j++) {
        const a=i*sides+j,b=i*sides+(j+1)%sides;
        indices.push(a,b,a+sides,b,b+sides,a+sides);
      }
      const geo=new T.BufferGeometry();
      geo.setAttribute("position",new T.Float32BufferAttribute(vertices,3));
      geo.setIndex(indices);geo.computeVertexNormals();
      return mesh(group,geo,material,[0,0,0],[1,1,1],id);
    }

    const shell=shaped(surface,100);
    mesh(groups[0],shell,glass("#4d2986","#9469ef",.113,.65,1.55,T.BackSide),[0,0,0],[1,1,1],0,1);
    mesh(groups[0],shell,glass("#6941a4","#a67aff",0,.29,5.1,T.BackSide),[0,0,0],[1.019,1.019,1.019],0,2);
    mesh(groups[0],shell,glass("#683aa5","#cfadff",.078,.83,1.95),[0,0,0],[1,1,1],0,7);
    dots(groups[0],skinSpecks,new T.MeshBasicMaterial({color:0xd1a8ff,transparent:true,opacity:.33,depthWrite:false}));

    const section=new T.Group();
    groups[0].add(section);
    const edge=Array.from({length:106},(_,i)=>{
      const a=i*tau/106,[x,y]=surface(Math.cos(a),Math.sin(a),0);
      return [x,y,-.019];
    });
    const cutEdge=tube(section,edge,.027,new T.MeshBasicMaterial({color:0xe5b8ff,transparent:true,opacity:.89,depthWrite:false}),0,136,true);
    cutEdge.renderOrder=8;
    const shape=new T.Shape(edge.map(([x,y])=>new T.Vector2(x,y)));
    mesh(section,new T.ShapeGeometry(shape),new T.MeshBasicMaterial({color:0xaa7ced,transparent:true,opacity:.09,side:T.DoubleSide,depthWrite:false}),[0,0,-.022],[1,1,1],0,6);

    const nucleus=shaped((x,y,z)=>{
      const r=1+.022*Math.sin(5*x+6*y)*Math.cos(9*z-2*x);
      return [x*r,y*r,z*r];
    },63);
    const np=[-.65,.22,-.19], ns=[1.05,.98,.89];
    mesh(groups[1],nucleus,glass("#583291","#9667df",.22,.55,1.7,T.BackSide),np,ns,0,3);
    mesh(groups[1],nucleus,glass("#7b45b0","#dfb6ff",.16,.86,1.62),np,ns,1,5);
    const chromatin=matte("#a15bcd","#a75fdf",.23,{transparent:true,opacity:.43,depthWrite:false});
    for (let k=0;k<6;k++) {
      const p=samples(15,(t,i)=>{
        const a=i*.31+k*1.23,r=.26+.25*Math.sin(i*.35+k);
        return [-.65+Math.cos(a)*r,.22+Math.sin(a)*r*.88,-.28+Math.cos(i*.49+k)*.28];
      });
      tube(groups[1],p,.013,chromatin,1);
    }
    const pores=seeded(990);
    dots(groups[1],samples(91,()=>{
      const y=pores()*1.98-.99,a=pores()*tau,r=Math.sqrt(1-y*y);
      return [np[0]+ns[0]*r*Math.cos(a),np[1]+ns[1]*y,np[2]+ns[2]*r*Math.sin(a),.010+pores()*.011];
    }),new T.MeshBasicMaterial({color:0xd2aaf9,transparent:true,opacity:.44,depthWrite:false}),1);

    const nucleolus=shaped((x,y,z)=>{
      const r=1+.067*Math.sin(10*x+3*y)*Math.cos(8*z-3*y)+.024*Math.sin(16*y);
      return [x*r,y*r,z*r];
    },42);
    mesh(groups[2],nucleolus,matte("#d962ba","#b33991",.22,{roughness:.66}),[-.65,.29,.18],[.381,.35,.38],2);
    dots(groups[2],samples(55,()=>{
      const y=pores()*2-1,a=pores()*tau,r=Math.sqrt(1-y*y);
      return [-.65+.372*r*Math.cos(a),.29+.343*y,.18+.371*r*Math.sin(a),.016+pores()*.024];
    }),matte("#ef96d3","#d252ab",.18),2);

    const blueEdge=matte("#8bc9ff","#4d85ef",.24);
    ["#3f68bd","#4b83d1","#5597df","#527bcc"].forEach((color,k)=>{
      ribbon(groups[3],(t,b)=>roughPoint(k,t,b),matte(color,"#456fd4",.22,{side:T.DoubleSide}),3);
      tube(groups[3],samples(23,t=>roughPoint(k,t,.22)),.014,blueEdge,3,42);
    });
    const teal=matte("#4cbbab","#3db290",.25), mint=matte("#73dbc0","#4dca9c",.21);
    smoothPaths.forEach((p,i)=>{
      const bright=i%3===0,r=bright?.076:.058,material=bright?mint:teal;
      tube(groups[4],p,r,material,4);
      mesh(groups[4],sphere,material,p[0],[r,r,r],4);
      mesh(groups[4],sphere,material,p[p.length-1],[r,r,r],4);
    });
    dots(groups[5],ribosomes,matte("#f2bc68","#e5993f",.30),5);
    const pinkEdge=matte("#ed9cc9","#d360a0",.23);
    ["#ac407f","#c25892","#d267a3","#e180b4","#ed91bd"].forEach((color,k)=>{
      ribbon(groups[6],(t,b)=>golgiPoint(k,t,b),matte(color,"#a4397d",.21,{side:T.DoubleSide}),6);
      tube(groups[6],samples(23,t=>golgiPoint(k,t,.12)),.014,pinkEdge,6);
    });
    const mitoGeo=shaped((x,y,z)=>{
      const r=.98+.099*Math.cos(x*4+1);
      return [x*.62,y*.285*r+.065*Math.sin(x*Math.PI),z*.245*r];
    },51);
    const mitoBack=glass("#923449","#ff875e",.52,.58,1.57,T.BackSide);
    const mitoSkin=glass("#d7554e","#ffb986",.24,.86,1.58);
    const mitoBase=matte("#9d3d51","#933044",.22);
    const mitoFold=matte("#ffc281","#eb783b",.33);
    mitochondria.forEach(({p,a,s},i)=>{
      const g=new T.Group();g.position.set(...p);g.rotation.set(i*.11,i%2?.21:-.15,a);g.scale.setScalar(s);groups[7].add(g);
      mesh(g,mitoGeo,mitoBack,[0,0,0],[1,1,1],7,3);
      mesh(g,mitoGeo,mitoBase,[0,0,-.052],[.87,.76,.50],7);
      mesh(g,mitoGeo,mitoSkin,[0,0,0],[1,1,1],7,4);
      tube(g,fold,.032,mitoFold,7,82);
      tube(g,fold.map(([x,y,z])=>[x,y,z-.20]),.024,mitoFold,7,75);
    });
    const lyso=matte("#a0b959","#6b821c",.22,{roughness:.67});
    const lysoDots=matte("#d5e888","#9ba83d",.19);
    const lysoSkin=glass("#8eb044","#e9f8aa",.05,.63,1.92);
    lysosomes.forEach(([x,y,z,r])=>{
      mesh(groups[8],sphere,lyso,[x,y,z],[r*.90,r*.90,r*.87],8);
      mesh(groups[8],sphere,lysoSkin,[x,y,z],[r,r,r],8,4);
      dots(groups[8],samples(24,()=>{
        const ny=pores()*2-1,a=pores()*tau,sr=r*.88*Math.sqrt(1-ny*ny);
        return [x+sr*Math.cos(a),y+r*ny*.85,z+sr*Math.sin(a),r*(.06+.07*pores())];
      }),lysoDots,8);
    });
    const bubble=glass("#338fa8","#9aebff",.21,.85,1.62);
    const cargo=matte("#79d3de","#4cbacb",.28,{transparent:true,opacity:.49,depthWrite:false});
    vesicles.forEach(([x,y,z,r],i)=>{
      mesh(groups[9],sphere,bubble,[x,y,z],[r,r,r],9,4);
      mesh(groups[9],sphere,cargo,[x+.23*r,y+.20*r,z+.015],[.42*r,(i%2?.55:.38)*r,.43*r],9,3);
    });
    const barrelRod=new T.CylinderGeometry(1,1,1,10), barrelRing=new T.TorusGeometry(.125,.022,8,26);
    const barrelFill=matte("#8d4652","#703248",.20), orange=matte("#d9914e","#c16825",.24), honey=matte("#ffd18b","#e78b3a",.23);
    centrioles.forEach(([x,y,z,a],i)=>{
      const g=new T.Group();g.position.set(x,y,z);g.rotation.set(i?-.5:.52,.13,a);groups[10].add(g);
      mesh(g,barrelRod,barrelFill,[0,0,0],[.101,.42,.101],10);
      for (let j=0;j<9;j++) {const b=j*tau/9;mesh(g,barrelRod,orange,[.111*Math.cos(b),0,.111*Math.sin(b)],[.031,.45,.031],10);}
      for (const h of [-.225,.225]) mesh(g,barrelRing,honey,[0,h,0],[1,1,1],10).rotation.x=Math.PI/2;
    });
    const fiberMaterials=["#8c78e7","#6898cc","#bb7bdc"].map(color=>new T.MeshBasicMaterial({color,transparent:true,opacity:.48,depthWrite:false}));
    fibers.forEach((points,i)=>tube(groups[11],points,.013+(i%4)*.003,fiberMaterials[i%3],11,35));
    host.append(renderer.domElement);

    function render(time) {
      const h=eye.dist*Math.cos(eye.pitch);
      camera.position.set(eye.x+h*Math.sin(eye.yaw),eye.y+eye.dist*Math.sin(eye.pitch),eye.z+h*Math.cos(eye.yaw));
      camera.lookAt(eye.x,eye.y,eye.z);camera.updateMatrixWorld();
      renderer.clippingPlanes=cut ? clipped : clear;
      section.visible=cut;
      glassMaterials.forEach(m=>{m.uniforms.clock.value=time;});
      for (let i=1;i<=total;i++) {
        const g=groups[i],f=frames[i],a=parts[i].anchor;
        g.visible=i<=step;if (!g.visible) continue;
        g.scale.setScalar(f.size);
        g.position.set(f.x+a[0]*(1-f.size),f.y+a[1]*(1-f.size),f.z+a[2]*(1-f.size));
      }
      renderer.render(scene,camera);
    }
    function project(p) {
      const q=vector(p).project(camera);
      return {x:(q.x+1)*width/2,y:(1-q.y)*height/2,visible:q.z>-1&&q.z<1};
    }
    function pick(x,y) {
      ndc.set(2*x/width-1,1-2*y/height);ray.setFromCamera(ndc,camera);
      const hits=ray.intersectObjects(groups.slice(1,step+1),true).filter(hit=>hit.object.userData.part && (!cut||hit.point.z<=.008));
      if (hits.length) {
        const first=hits[0];
        if (first.object.userData.part===1 && hits.some(h=>h.object.userData.part===2 && h.distance<first.distance+1.5)) return 2;
        return first.object.userData.part;
      }
      let nearest=null, distance=13;
      for (let i=1;i<=step;i++) {
        const p=project(moving(i,parts[i].anchor,true)),d=Math.hypot(p.x-x,p.y-y);
        if (p.visible&&d<distance) {nearest=i;distance=d;}
      }
      return nearest;
    }
    return {render,project,pick,resize(w,h){
      camera.aspect=w/h;
      camera.fov=2*Math.atan(Math.tan(Math.PI/10)*Math.max(1,1.20/camera.aspect))*180/Math.PI;
      camera.updateProjectionMatrix();
      renderer.setSize(w,h,false);
    }};
  }

  function moving(id,p,clip=false) {
    const a=parts[id].anchor,f=frames[id];
    const z=a[2]+(p[2]-a[2])*f.size+f.z;
    return [a[0]+(p[0]-a[0])*f.size+f.x,a[1]+(p[1]-a[1])*f.size+f.y,clip&&cut?Math.min(0,z):z];
  }

  // Perspective canvas rendering for browsers with WebGL or the library unavailable.
  function canvasScene() {
    const canvas=document.createElement("canvas"),ctx=canvas.getContext("2d");
    const pixel=Math.min(devicePixelRatio||1,1.6);
    host.append(canvas);
    let focal=1,ca=1,sa=0,cp=1,sp=0,targets=[];
    function project(p) {
      const x=p[0]-eye.x,y=p[1]-eye.y,z=p[2]-eye.z;
      const rx=ca*x-sa*z,rz=sa*x+ca*z,ry=cp*y-sp*rz;
      const d=eye.dist-(sp*y+cp*rz),s=focal/Math.max(.08,d);
      return {x:width/2+rx*s,y:height/2-ry*s,d,s,visible:d>0};
    }
    function trace(points,close=false) {
      ctx.beginPath();
      points.forEach((p,i)=>{if (i) ctx.lineTo(p.x,p.y);else ctx.moveTo(p.x,p.y);});
      if (close) ctx.closePath();
    }
    function strand(path,color,thickness,id,alpha=1) {
      ctx.strokeStyle=color;ctx.lineCap=ctx.lineJoin="round";ctx.globalAlpha=alpha;
      for (let i=1;i<path.length;i++) {
        let a=path[i-1],b=path[i];
        if (cut && a[2]>0 && b[2]>0) continue;
        if (cut && (a[2]>0 || b[2]>0)) {
          const t=a[2]/(a[2]-b[2]),edge=a.map((n,j)=>n+(b[j]-n)*t);
          if (a[2]>0) a=edge;else b=edge;
        }
        const p=project(a),q=project(b);
        ctx.lineWidth=Math.max(.65,thickness*(p.s+q.s)/2);
        trace([p,q]);ctx.stroke();
        if (id) targets.push({...p,id,rx:Math.max(6,ctx.lineWidth*.9),ry:Math.max(6,ctx.lineWidth*.9),angle:0});
      }
      ctx.globalAlpha=1;
    }
    function orb(id,at,rx,ry,color,angle=0,alpha=1) {
      if (cut && at[2]>Math.min(rx,ry)*.90) return;
      const p=project(at),w=rx*p.s*frames[id].size,h=ry*p.s*frames[id].size;
      if (!p.visible || w<.25 || h<.25) return;
      angle=-angle+eye.yaw*.21;
      ctx.save();ctx.translate(p.x,p.y);ctx.rotate(angle);ctx.scale(w,h);ctx.globalAlpha=alpha;
      const g=ctx.createRadialGradient(-.28,-.37,0,0,0,1);
      g.addColorStop(0,"#fff0fb");g.addColorStop(.26,color);g.addColorStop(.67,color);g.addColorStop(1,"#392252");
      ctx.fillStyle=g;ctx.beginPath();ctx.arc(0,0,1,0,tau);ctx.fill();
      ctx.strokeStyle=color;ctx.lineWidth=1/Math.max(w,h);ctx.stroke();ctx.restore();
      targets.push({...p,id,rx:w,ry:h,angle});
    }
    function render() {
      ca=Math.cos(eye.yaw);sa=Math.sin(eye.yaw);cp=Math.cos(eye.pitch);sp=Math.sin(eye.pitch);
      ctx.setTransform(pixel,0,0,pixel,0,0);ctx.clearRect(0,0,width,height);
      targets=[];
      const rim=samples(111,t=>{
        const x=Math.cos(t*tau),y=Math.sin(t*tau);
        return project(cut ? surface(x,y,0) : surface(ca*x-sa*sp*y,cp*y,-sa*x-ca*sp*y));
      });
      const mid=project([0,0,0]);
      const background=ctx.createRadialGradient(mid.x,mid.y,0,mid.x,mid.y,mid.s*3.12);
      background.addColorStop(0,"#8c57d113");background.addColorStop(.64,"#9560db20");
      background.addColorStop(.91,"#a870ec57");background.addColorStop(1,"#c8a1ffa5");
      trace(rim,true);ctx.fillStyle=background;ctx.fill();
      ctx.shadowColor="#af78fa";ctx.shadowBlur=15;ctx.lineWidth=cut?2:3;ctx.strokeStyle="#c5a2ffde";ctx.stroke();ctx.shadowBlur=0;
      skinSpecks.forEach((at,i)=>{
        if (cut && at[2]>0) return;
        const p=project(at);
        ctx.fillStyle=i%3?"#d9bef74b":"#f2d6ff82";
        ctx.beginPath();ctx.arc(p.x,p.y,.48+i%4*.22,0,tau);ctx.fill();
      });
      if (step>=11) fibers.forEach((p,i)=>strand(p.map(q=>moving(11,q)),["#a089f1","#79a0d8","#cc9aec"][i%3],.025,11,.53));
      if (step>=1) orb(1,moving(1,[-.65,.22,-.19]),1.05,.98,parts[1].color,0,.66);
      if (step>=2) orb(2,moving(2,[-.65,.29,.18]),.38,.35,parts[2].color);
      if (step>=3) for(let k=0;k<4;k++) strand(samples(43,t=>moving(3,roughPoint(k,t,.65))),k%2?"#84c6ff":"#5e80de",.125,3);
      if (step>=4) smoothPaths.forEach((p,i)=>strand(p.map(q=>moving(4,q)),i%2?"#60dfb9":"#99f2d3",.105,4));
      if (step>=5) ribosomes.forEach(([x,y,z,r])=>orb(5,moving(5,[x,y,z]),r,r,parts[5].color));
      if (step>=6) for(let k=0;k<5;k++) strand(samples(32,t=>moving(6,golgiPoint(k,t,cut?2.8:1.35))),k%2?"#eca0ca":"#d876ac",.136,6);
      if (step>=7) mitochondria.forEach(({p,a,s})=>{
        const at=moving(7,p);
        orb(7,at,.62*s,.285*s,parts[7].color,a);
        const path=fold.map(([x,y,z])=>moving(7,[p[0]+s*(x*Math.cos(a)-y*Math.sin(a)),p[1]+s*(x*Math.sin(a)+y*Math.cos(a)),cut?Math.min(-.02,p[2]):p[2]+z]));
        strand(path,"#984b60",.054*s,7);strand(path,"#ffe1a8",.023*s,0,.95);
      });
      if (step>=8) lysosomes.forEach(([x,y,z,r])=>orb(8,moving(8,[x,y,z]),r,r,parts[8].color));
      if (step>=9) vesicles.forEach(([x,y,z,r])=>orb(9,moving(9,[x,y,z]),r,r,parts[9].color,0,.72));
      if (step>=10) centrioles.forEach(([x,y,z,a])=>{
        orb(10,moving(10,[x,y,z]),.23,.112,parts[10].color,a);
        for (let j=0;j<5;j++) {
          const q=(j-2)*.037;
          strand([-1,1].map(sign=>moving(10,[x+sign*.18*Math.cos(a)-q*Math.sin(a),y+sign*.18*Math.sin(a)+q*Math.cos(a),z])),"#9c654b",.014,0);
        }
      });
    }
    function pick(x,y) {
      const hits=targets.filter(p=>{
        const dx=x-p.x,dy=y-p.y,c=Math.cos(p.angle),s=Math.sin(p.angle);
        return Math.hypot((c*dx+s*dy)/Math.max(5,p.rx),(-s*dx+c*dy)/Math.max(5,p.ry))<1.07;
      });
      hits.sort((a,b)=>a.d-b.d);
      return hits[0]?.id ?? null;
    }
    return {render,project,pick,resize(w,h){
      canvas.width=Math.round(w*pixel);canvas.height=Math.round(h*pixel);
      focal=Math.min(h,w/1.20)/(2*Math.tan(Math.PI/10));
    }};
  }

  let engine;
  try {
    engine=window.THREE ? webGL(window.THREE) : canvasScene();
  } catch {
    engine=canvasScene();
  }
  function resize() {
    width=Math.max(1,host.clientWidth);height=Math.max(1,host.clientHeight);
    engine.resize(width,height);
  }
  if ("ResizeObserver" in window) new ResizeObserver(resize).observe(host);
  window.addEventListener("resize",resize);
  resize();

  function positionLabel() {
    let at=moving(selected,parts[selected].anchor,true);
    if (!selected && !cut) {
      const x=-.84,z=.41,c=Math.cos(eye.yaw),s=Math.sin(eye.yaw);
      at=surface(c*x+s*z,.35,c*z-s*x);
    }
    const p=engine.project(at);
    annotation.hidden=!p.visible||p.x<9||p.x>width-9||p.y<38||p.y>height-40;
    if (annotation.hidden) return;
    const w=label.offsetWidth,h=label.offsetHeight;
    const right=width-p.x>w+50;
    const left=clamp(p.x+(right?41:-w-41),8,width-w-8);
    const top=clamp(p.y-30-h*.5,57,height-h-50);
    const dx=(right?left:left+w)-p.x,dy=top+h/2-p.y;
    label.style.left=left+"px";label.style.top=top+"px";
    dot.style.left=labelLine.style.left=p.x+"px";
    dot.style.top=labelLine.style.top=p.y+"px";
    labelLine.style.width=Math.hypot(dx,dy)+"px";
    labelLine.style.transform="rotate("+Math.atan2(dy,dx)+"rad)";
  }

  const pointers=new Map();
  let gesture=null,lastGap=0;
  function gap() {
    const [a,b]=pointers.values();
    return a&&b?Math.hypot(a.x-b.x,a.y-b.y):0;
  }
  function stopDemo(event) {
    if (!demo || !event.isTrusted) return;
    demo=false;
    if (playing) nextPart=performance.now()+interval;
    updateInterface();
  }
  document.addEventListener("pointerdown",stopDemo,true);
  document.addEventListener("keydown",stopDemo,true);
  host.addEventListener("pointerdown",event=>{
    if (event.pointerType==="mouse"&&event.button!==0) return;
    const x=event.clientX,y=event.clientY;
    pointers.set(event.pointerId,{x,y});host.setPointerCapture(event.pointerId);
    if (pointers.size===1) gesture={x,y,moved:false};
    else {gesture.moved=true;lastGap=gap();}
  });
  host.addEventListener("pointermove",event=>{
    const old=pointers.get(event.pointerId);
    if (!old||!gesture) return;
    const x=event.clientX,y=event.clientY;
    pointers.set(event.pointerId,{x,y});
    if (pointers.size>1) {
      const distance=gap();
      if (lastGap>0&&distance>0) goal.dist=clamp(goal.dist*lastGap/distance,4.3,19);
      lastGap=distance;
    } else if (gesture.moved||Math.hypot(x-gesture.x,y-gesture.y)>5) {
      gesture.moved=true;
      goal.yaw-=(x-old.x)*.008;
      goal.pitch=clamp(goal.pitch+(y-old.y)*.008,-1.35,1.35);
    }
  });
  function release(event) {
    if (!pointers.has(event.pointerId)) return;
    const tap=event.type==="pointerup"&&pointers.size===1&&gesture&&!gesture.moved;
    pointers.delete(event.pointerId);lastGap=gap();
    if (!pointers.size) gesture=null;
    if (!tap) return;
    const box=host.getBoundingClientRect(),id=engine.pick(event.clientX-box.left,event.clientY-box.top);
    if (id!=null) select(id);
  }
  host.addEventListener("pointerup",release);
  host.addEventListener("pointercancel",release);
  host.addEventListener("lostpointercapture",release);
  host.addEventListener("wheel",event=>{
    event.preventDefault();stopDemo(event);
    const unit=event.deltaMode===1?16:event.deltaMode===2?height:1;
    goal.dist=clamp(goal.dist*Math.exp(event.deltaY*unit*.00125),4.3,19);
  },{passive:false});

  function runDemo(now) {
    if (now-demoStart>=20200) {demoStart=now;cue=-1;}
    const t=now-demoStart;
    if (t<8200) {
      if (cue!==0) {cue=0;cut=false;playing=true;resetView();buildTo(0);}
      const n=clamp(Math.floor((t-450)/660),0,total);
      if (n!==step) buildTo(n);
    } else if (t<11000) {
      if (cue!==1) {cue=1;buildTo(total);}
      turnTo(-.12+(t-8200)/2800*1.17);
      goal.pitch=.16+.17*Math.sin((t-8200)/2800*Math.PI);
    } else if (t<13600) {
      if (cue!==2) {cue=2;select(7);}
    } else if (t<16700) {
      if (cue!==3) {cue=3;resetView();setCut(true);}
      turnTo(.54+.36*Math.sin((t-13600)/3100*Math.PI));
    } else if (t<18600) {
      if (cue!==4) {cue=4;setCut(false);resetView();buildTo(3,true);}
      const n=Math.min(8,3+Math.floor((t-16700)/350));
      if(n!==step) buildTo(n,true);
    } else if (cue!==5) {cue=5;resetView();buildTo(total,true);}
  }
  function animate(now) {
    const dt=clamp(now-previous,0,46);previous=now;
    if (demo) runDemo(now);
    else if (playing&&step<total&&now>=nextPart) {nextPart=now+interval;buildTo(step+1);}
    const t=reduced?0:now/1000,ease=reduced?1:1-Math.exp(-dt*.010);
    Object.keys(eye).forEach(k=>{eye[k]+=(goal[k]-eye[k])*ease;});
    for (let i=1;i<=step;i++) {
      const f=frames[i],fraction=reduced?1:clamp((now-f.born)/490,0,1);
      const growth=.13+.87*(1-(1-fraction)**3);
      f.size=growth*(reduced?1:1+.019*Math.sin(t*1.8+i*2.12));
      f.x=reduced?0:.039*Math.sin(t*.77+i*1.63);
      f.y=reduced?0:.052*Math.sin(t*1.03+i*.91);
      f.z=reduced?0:.041*Math.cos(t*.68+i*1.35);
    }
    engine.render(t);
    positionLabel();
    requestAnimationFrame(animate);
  }
  updateInterface();
  requestAnimationFrame(animate);
})();
</script>
</body>
</html>