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.)68.1 KB · 1,583 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, viewport-fit=cover">
<meta name="theme-color" content="#0d141f">
<link rel="icon" href="data:,">
<title>Cell Lab · Inside an animal cell</title>
<style>
  :root {
    color-scheme: dark;
    --page: #0d141f;
    --panel: #131e2b;
    --border: #2a3949;
    --white: #eef5f6;
    --muted: #a3b5c5;
    --mint: #8ce9d5;
    font-family: "Segoe UI", system-ui, sans-serif;
  }
  *, *::before, *::after { box-sizing: border-box; }
  body {
    margin: 0;
    min-height: 100vh;
    color: var(--white);
    background: radial-gradient(ellipse at 37% -32%, #1e3745, transparent 59%), var(--page);
  }
  button, input { font: inherit; }
  button { -webkit-tap-highlight-color: transparent; color: inherit; cursor: pointer; }
  button:focus-visible, input:focus-visible { outline: 2px solid var(--mint); outline-offset: 4px; }
  button:disabled { cursor: default; }
  svg { display: block; }
  [hidden] { display: none !important; }
  .wrap { width: min(1424px, calc(100% - 96px)); margin-inline: auto; }
  .masthead {
    position: relative;
    display: flex;
    justify-content: space-between;
    align-items: center;
    min-height: 73px;
    border-bottom: 1px solid #2c3e4d;
  }
  .brand { display: flex; align-items: center; gap: 11px; font-weight: 750; font-size: 19px; letter-spacing: -.035em; }
  .brand-mark {
    display: grid;
    place-items: center;
    width: 36px;
    height: 36px;
    border: 1px solid #417c79;
    border-radius: 11px;
    color: var(--mint);
    background: #19343d;
  }
  .help-toggle, .tool, .rebuild, .play {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    border: 1px solid var(--border);
    background: #192737;
    border-radius: 10px;
    min-height: 44px;
    font-size: 13px;
    font-weight: 650;
  }
  .help-toggle { padding: 0 13px; background: transparent; color: #c1ced9; }
  button:hover { border-color: #567280; }
  .help-popover {
    position: absolute;
    z-index: 20;
    top: calc(100% - 2px);
    right: 0;
    width: min(318px, 100%);
    padding: 18px 20px;
    background: #192737;
    border: 1px solid #455b68;
    border-radius: 13px;
    box-shadow: 0 12px 38px #040a12ac;
    font-size: 14px;
    line-height: 1.55;
  }
  .help-popover strong { font-size: 15px; }
  .help-popover p { margin: 6px 0 0; color: #c0d0dc; }
  .intro { padding: 24px 0 23px; }
  h1 {
    margin: 0;
    font-size: clamp(40px, 4.45vw, 71px);
    line-height: 1.03;
    font-weight: 700;
    letter-spacing: -.071em;
  }
  h1 em {
    color: var(--mint);
    font-family: Georgia, serif;
    font-weight: 400;
    letter-spacing: -.071em;
  }
  .intro p { margin: 12px 0 0; color: var(--muted); font-size: clamp(14px, 1.25vw, 17px); line-height: 1.48; }
  .exhibit {
    --model-height: clamp(500px, 59vh, 650px);
    display: grid;
    grid-template-columns: minmax(0, 1fr) clamp(282px, 24vw, 342px);
    grid-template-areas: "stage guide" "timeline timeline";
    gap: 13px;
    padding-bottom: 24px;
  }
  .stage, .guide, .timeline { border: 1px solid var(--border); border-radius: 19px; }
  .stage {
    grid-area: stage;
    height: var(--model-height);
    position: relative;
    overflow: hidden;
    isolation: isolate;
    background: radial-gradient(ellipse at 50% 44%, #20434c 0%, #142b39 40%, #0c1826 76%);
  }
  .stage::before {
    content: "";
    position: absolute;
    inset: 0;
    pointer-events: none;
    background-image: linear-gradient(#7eb5c018 1px, transparent 1px), linear-gradient(90deg, #7eb5c018 1px, transparent 1px);
    background-position: center;
    background-size: 38px 38px;
    mask-image: radial-gradient(ellipse at center, #000 15%, transparent 77%);
  }
  .orbit-ring {
    position: absolute;
    pointer-events: none;
    top: 55%;
    left: 50%;
    width: min(76%, 670px);
    height: 60%;
    border: 1px solid #7cb9bf20;
    border-radius: 50%;
    transform: translate(-50%,-50%) rotate(-10deg);
  }
  .orbit-ring::after {
    content: "";
    position: absolute;
    inset: 13px -18px;
    border: 1px dashed #88b7bf1d;
    border-radius: inherit;
  }
  .corners { position: absolute; inset: 68px 22px 65px; pointer-events: none; opacity: .6; }
  .corners i { position: absolute; width: 15px; height: 15px; border: 1px solid #60828c; }
  .corners i:nth-child(1) { top: 0; left: 0; border-right: 0; border-bottom: 0; }
  .corners i:nth-child(2) { top: 0; right: 0; border-left: 0; border-bottom: 0; }
  .corners i:nth-child(3) { bottom: 0; right: 0; border-left: 0; border-top: 0; }
  .corners i:nth-child(4) { bottom: 0; left: 0; border-right: 0; border-top: 0; }
  .surface, .surface canvas, .leader { position: absolute; inset: 0; width: 100%; height: 100%; }
  .surface { touch-action: none; cursor: grab; }
  .surface:active { cursor: grabbing; }
  .surface canvas, .leader { pointer-events: none; }
  .leader { overflow: visible; }
  .part-pin {
    position: absolute;
    z-index: 2;
    top: 0;
    left: 0;
    transform: translate(-50%,-100%);
    max-width: min(240px, 72%);
    border: 1px solid #597584;
    border-radius: 7px;
    padding: 6px 10px;
    color: #f3fbfc;
    background: #102331ee;
    box-shadow: 0 4px 18px #070e193f;
    font-size: 12px;
    font-weight: 650;
    text-align: center;
    white-space: nowrap;
    pointer-events: none;
  }
  .stage-top, .stage-bottom {
    position: absolute;
    z-index: 3;
    left: 16px;
    right: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 8px;
    pointer-events: none;
  }
  .stage-top { top: 15px; }
  .stage-bottom { bottom: 15px; align-items: end; }
  .stage-top button, .stage-bottom button { pointer-events: auto; }
  .state-label, .gesture {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    color: #c0d1dc;
    font-size: 12px;
    white-space: nowrap;
  }
  .state-label {
    padding: 8px 10px;
    background: #10202dd9;
    border: 1px solid #2f4856;
    border-radius: 7px;
    font-weight: 650;
  }
  .state-light { width: 7px; height: 7px; border-radius: 50%; background: var(--mint); box-shadow: 0 0 10px #8ce9d588; }
  .state-label[data-running="false"] .state-light { background: #909dbb; box-shadow: none; }
  .gesture { padding: 8px 0; color: #a7bacb; }
  .touch-gesture { display: none; }
  .stage-tools { display: flex; gap: 5px; }
  .tool { width: 44px; padding: 0; background: #112331ee; color: #d6e5ed; }
  .cut {
    width: auto;
    padding: 0 10px 0 12px;
    gap: 9px;
    white-space: nowrap;
  }
  .switch {
    display: block;
    position: relative;
    width: 29px;
    height: 17px;
    background: #344d5b;
    border: 1px solid #567180;
    border-radius: 30px;
    transition: background .2s, border-color .2s;
  }
  .switch::after {
    content: "";
    position: absolute;
    top: 2px;
    left: 2px;
    width: 11px;
    height: 11px;
    border-radius: 50%;
    background: #d0e1e7;
    transition: transform .2s;
  }
  .cut[aria-checked="true"] { color: var(--mint); border-color: #558b88; }
  .cut[aria-checked="true"] .switch { background: #8ce9d5; border-color: #8ce9d5; }
  .cut[aria-checked="true"] .switch::after { transform: translateX(12px); background: #133641; }
  .mobile-fact { display: none; }
  .guide {
    grid-area: guide;
    height: var(--model-height);
    background: var(--panel);
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
  .details { padding: 16px 19px 15px; border-bottom: 1px solid var(--border); }
  .detail-top { display: flex; align-items: center; gap: 10px; min-height: 39px; color: var(--part, var(--mint)); }
  .detail-symbol {
    width: 39px;
    height: 39px;
    display: grid;
    place-items: center;
    border-radius: 11px;
    border: 1px solid color-mix(in srgb, currentColor 38%, transparent);
    background: color-mix(in srgb, currentColor 10%, transparent);
  }
  .detail-category { font-size: 11px; font-weight: 750; letter-spacing: .108em; text-transform: uppercase; }
  .details h2 { font-size: clamp(22px, 2.05vw, 30px); line-height: 1.1; letter-spacing: -.037em; margin: 9px 0 6px; }
  .details p { margin: 0; color: #b9cbd7; font-size: 13.5px; line-height: 1.5; }
  .parts-heading { display: flex; justify-content: space-between; align-items: center; padding: 12px 19px 6px; }
  .parts-heading h3 { margin: 0; font-size: 13px; font-weight: 700; }
  .parts-heading span { color: #a6bdcb; font-size: 11px; font-variant-numeric: tabular-nums; }
  .part-list { margin: 0 7px 7px 0; padding: 0 6px 2px 10px; min-height: 0; list-style: none; overflow: auto; scrollbar-width: thin; scrollbar-color: #4a6573 transparent; }
  .part-list button {
    display: grid;
    grid-template-columns: 13px 1fr 13px;
    align-items: center;
    gap: 8px;
    width: 100%;
    min-height: 29px;
    padding: 3px 7px;
    text-align: left;
    font-size: 12.5px;
    background: transparent;
    border: 1px solid transparent;
    border-radius: 7px;
    color: #a7bbcb;
  }
  .part-list button:hover { background: #1b2a39; }
  .part-list button[data-built="true"] { color: #d5e2e9; }
  .part-list button[aria-current="true"] { color: #f1f9fa; background: #213540; border-color: #3b5964; font-weight: 650; }
  .part-dot { width: 8px; height: 8px; margin-left: 2px; border: 1px solid var(--part); border-radius: 50%; opacity: .75; }
  [data-built="true"] .part-dot { background: var(--part); opacity: 1; }
  .part-arrow { color: var(--part); opacity: 0; }
  [aria-current="true"] .part-arrow { opacity: 1; }
  .timeline {
    grid-area: timeline;
    background: #131f2c;
    padding: 9px 16px 12px;
  }
  .timeline-head { display: flex; justify-content: space-between; align-items: center; gap: 10px; }
  .timeline-name { display: flex; flex-wrap: wrap; align-items: baseline; gap: 5px 13px; }
  .timeline-name h2 { margin: 0; font-size: 15px; font-weight: 720; letter-spacing: -.01em; }
  .timeline-name output { font-size: 11px; color: var(--mint); font-weight: 650; font-variant-numeric: tabular-nums; }
  .rebuild { min-height: 40px; padding: 0 12px; }
  .rebuild[data-demo="true"] { color: var(--mint); border-color: var(--mint); }
  .transport { display: grid; grid-template-columns: 44px 1fr; align-items: center; gap: 13px; }
  .play { width: 44px; background: #18383e; border-color: #37666a; color: var(--mint); }
  .ruler { min-width: 0; }
  .slider-bed { position: relative; height: 27px; display: flex; align-items: center; }
  .marks { position: absolute; inset: 9px 9px auto; display: flex; justify-content: space-between; pointer-events: none; }
  .marks i { width: 1px; height: 9px; background: #67818f; opacity: .65; }
  .marks i[data-passed="true"] { background: var(--mint); opacity: .9; }
  #scrub {
    --pct: 0%;
    appearance: none;
    -webkit-appearance: none;
    position: relative;
    width: 100%;
    height: 32px;
    margin: 0;
    border-radius: 8px;
    background: transparent;
    cursor: pointer;
    touch-action: pan-y;
  }
  #scrub::-webkit-slider-runnable-track { height: 4px; border-radius: 8px; background: linear-gradient(to right, var(--mint) var(--pct), #3a5162 var(--pct)); }
  #scrub::-moz-range-track { height: 4px; border-radius: 8px; background: linear-gradient(to right, var(--mint) var(--pct), #3a5162 var(--pct)); }
  #scrub::-webkit-slider-thumb {
    appearance: none;
    -webkit-appearance: none;
    width: 16px;
    height: 16px;
    margin-top: -6px;
    border: 3px solid #e0fff5;
    border-radius: 50%;
    background: #56bfae;
    box-shadow: 0 0 0 3px #85e8d52b;
  }
  #scrub::-moz-range-thumb { width: 11px; height: 11px; border: 3px solid #e0fff5; border-radius: 50%; background: #56bfae; box-shadow: 0 0 0 3px #85e8d52b; }
  .ruler-ends { display: flex; justify-content: space-between; color: #a7bac9; font-size: 11px; padding: 0 2px; }
  @media (pointer: coarse) {
    .desktop-gesture { display: none; }
    .touch-gesture { display: inline; }
    .part-list button { min-height: 44px; }
    .rebuild, #scrub { min-height: 44px; }
    .slider-bed { height: 36px; }
    .marks { top: 13px; }
  }
  @media (max-width: 810px) {
    .wrap { width: calc(100% - 30px); }
    .masthead { min-height: 61px; }
    .intro { padding: 20px 0 16px; }
    h1 { font-size: clamp(32px, 8.25vw, 62px); }
    .intro p { margin-top: 8px; }
    .exhibit { grid-template-columns: minmax(0, 1fr); grid-template-areas: "stage" "timeline" "guide"; gap: 10px; }
    .stage { height: clamp(312px, 46svh, 500px); }
    .guide { height: auto; }
    .part-list { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 2px 6px; margin: 0 3px 8px 0; }
    .parts-heading { padding-top: 11px; }
    .part-list button { min-height: 42px; line-height: 1.2; }
    .details { padding: 14px 16px; }
    .details h2 { margin-top: 8px; }
    .stage-top, .stage-bottom { left: 10px; right: 10px; }
    .stage-top { top: 10px; }
    .stage-bottom { bottom: 10px; }
    .corners { inset: 66px 15px 59px; }
    .gesture { font-size: 11px; }
    .orbit-ring { width: 85%; }
    .stage[data-focused="true"] .mobile-fact {
      display: block;
      position: absolute;
      z-index: 3;
      left: 10px;
      bottom: 63px;
      max-width: min(325px, calc(100% - 20px));
      border: 1px solid #456373;
      border-radius: 9px;
      padding: 7px 10px;
      background: #10202ef0;
      color: #e4eff4;
      font-size: 12px;
      line-height: 1.35;
      pointer-events: none;
    }
    .timeline { padding-inline: 11px; }
  }
  @media (max-width: 385px) {
    .wrap { width: calc(100% - 20px); }
    .gesture svg { display: none; }
    .stage-tools { gap: 3px; }
    .tool:not(.cut) { width: 42px; }
    .state-label { font-size: 11px; }
  }
  @media (prefers-reduced-motion: reduce) {
    *, *::before, *::after { transition-duration: 0s !important; }
  }
</style>
</head>
<body>
<header class="masthead wrap">
  <div class="brand">
    <span class="brand-mark" aria-hidden="true">
      <svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round">
        <path d="M21.1 10.4c.8 3.8-2.1 7.3-6 8.9-3.8 1.6-9.5.9-11.7-2.8C1.1 12.7 3.8 7.6 8.1 5.4c4.5-2.3 12-1.1 13 5Z"/>
        <path d="M13.8 8.8c2.3 1.4 1.8 4.4-.5 5.5-2.5 1.1-5.4-.7-5-3 .4-2.5 3.3-3.8 5.5-2.5Z"/>
        <path d="M17.3 13.5h.1m-5.5-2h.1m-5.5 4.7h.1"/>
      </svg>
    </span>
    Cell Lab
  </div>
  <button class="help-toggle" type="button" id="help-toggle" aria-expanded="false" aria-controls="help">
    <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M9.5 9a2.5 2.5 0 1 1 3.8 2.1c-.9.5-1.3 1-1.3 2m0 3.2v.1"/></svg>
    Controls
  </button>
  <div class="help-popover" id="help" hidden>
    <strong>Explore the cell</strong>
    <p>Drag to turn the cell. Pinch, scroll, or use the zoom buttons to get closer. Tap a part or choose its name to fly to it.</p>
    <p>Use the timeline to move through the build, and switch on Cut open to see a cross-section.</p>
  </div>
</header>

<main class="wrap">
  <div class="intro">
    <h1>Inside an <em>animal cell</em></h1>
    <p>Watch a cell come together, then get close to the parts that keep it alive.</p>
  </div>

  <div class="exhibit">
    <section class="stage" id="stage" aria-label="Interactive animal cell">
      <div class="orbit-ring" aria-hidden="true"></div>
      <div class="corners" aria-hidden="true"><i></i><i></i><i></i><i></i></div>
      <div class="surface" id="surface" role="img" aria-label="Animal cell model. Use the Cell parts list to select a structure by name."></div>
      <svg class="leader" id="leader" aria-hidden="true">
        <path id="leader-line" fill="none" stroke="#b5f4e9" stroke-opacity=".7" stroke-width="1"/>
        <circle id="leader-ring" r="5" fill="#122432" fill-opacity=".75" stroke="#b5f4e9" stroke-width="1"/>
        <circle id="leader-dot" r="2" fill="#b5f4e9"/>
      </svg>
      <div class="part-pin" id="part-pin" aria-hidden="true">Cell membrane</div>
      <div class="stage-top">
        <div class="state-label" id="state-label"><span class="state-light" aria-hidden="true"></span><span id="state-text">Building cell</span></div>
        <button class="tool cut" type="button" id="cut" role="switch" aria-checked="false" aria-label="Cut open">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" aria-hidden="true"><path d="M11 4a8 8 0 0 0 0 16M14 4v3m0 3v4m0 3v3m3.5-14.2a8 8 0 0 1 0 12.4"/></svg>
          Cut open <span class="switch" aria-hidden="true"></span>
        </button>
      </div>
      <div class="mobile-fact" id="mobile-fact" aria-hidden="true"></div>
      <div class="stage-bottom">
        <div class="gesture">
          <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3v18M3 12h18M9 6l3-3 3 3M9 18l3 3 3-3M6 9l-3 3 3 3m12-6 3 3-3 3"/></svg>
          <span class="desktop-gesture">Drag to orbit · Scroll to zoom</span>
          <span class="touch-gesture">Drag to orbit · Pinch to zoom</span>
        </div>
        <div class="stage-tools">
          <button class="tool" id="zoom-out" type="button" aria-label="Zoom out" title="Zoom out"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><path d="M5 12h14"/></svg></button>
          <button class="tool" id="zoom-in" type="button" aria-label="Zoom in" title="Zoom in"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><path d="M5 12h14m-7-7v14"/></svg></button>
          <button class="tool" id="reset-view" 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.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M8 3H4a1 1 0 0 0-1 1v4m13-5h4a1 1 0 0 1 1 1v4M3 16v4a1 1 0 0 0 1 1h4m13-5v4a1 1 0 0 1-1 1h-4"/><circle cx="12" cy="12" r="3"/></svg></button>
        </div>
      </div>
    </section>

    <aside class="guide" aria-label="Cell parts guide">
      <div class="details" id="details" aria-live="polite">
        <div class="detail-top"><span class="detail-symbol" id="detail-symbol" aria-hidden="true"></span><span class="detail-category" id="detail-category">Cell boundary</span></div>
        <h2 id="part-title">Cell membrane</h2>
        <p id="part-fact">The membrane is a flexible skin that controls what goes in and out of the cell.</p>
      </div>
      <div class="parts-heading"><h3>Cell parts</h3><span id="part-count"></span></div>
      <ul class="part-list" id="part-list"></ul>
    </aside>

    <section class="timeline" aria-labelledby="timeline-heading">
      <div class="timeline-head">
        <div class="timeline-name"><h2 id="timeline-heading">Build timeline</h2><output id="step-readout" for="scrub">Step 1 of 12</output></div>
        <button class="rebuild" id="rebuild" type="button">
          <svg width="16" height="16" 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 11a8 8 0 1 1 2.2 6m-2.2-6V5m0 6h6"/></svg>
          Rebuild
        </button>
      </div>
      <div class="transport">
        <button class="play" id="play" type="button" aria-label="Pause build" title="Pause build"></button>
        <div class="ruler">
          <div class="slider-bed">
            <div class="marks" id="marks" aria-hidden="true"></div>
            <input type="range" id="scrub" min="0" max="11" value="0" step="1" aria-label="Build step">
          </div>
          <div class="ruler-ends" aria-hidden="true"><span>Membrane only</span><span>Complete cell</span></div>
        </div>
      </div>
    </section>
  </div>
</main>

<script>
(() => {
  "use strict";

  const parts = [
    { name: "Cell membrane", short: "Cell membrane", group: "Cell boundary", color: "#86e9d5", anchors: [[-2.97,1.10,.98]], fact: "The membrane is a flexible skin that controls what goes in and out of the cell.", icon: '<path d="M21 10.2c1.2 4-2.5 7.9-6.8 9C9 20.6 4 19 3 15c-1-4 2.6-8 7-9.8 4.5-1.7 9.8.8 11 5Z"/><path d="M18.5 10.8c.7 2.5-1.8 5.4-5.1 6.2C10 18 6.2 17 5.5 14.4s2-5.6 5.3-6.8c3.4-1.1 7 .7 7.7 3.2Z"/>' },
    { name: "Nucleus", short: "Nucleus", group: "Cell instructions", color: "#bdadff", anchors: [[-.93,.28,-.25]], fact: "The nucleus stores DNA, the instructions the cell uses to do its jobs.", icon: '<circle cx="12" cy="12" r="8.5"/><path d="M7 12c2-3.7 5.5-4.6 8.8-1.6m-6.3 4c1.4 1.4 3.1 1.6 5 .1"/>' },
    { name: "Nucleolus", short: "Nucleolus", group: "Ribosome maker", color: "#f39bd7", anchors: [[-.97,.45,.27]], fact: "The nucleolus makes the pieces that join together to form ribosomes.", icon: '<circle cx="12" cy="12" r="8.2" opacity=".5"/><circle cx="12" cy="12" r="4.3" fill="currentColor" fill-opacity=".34"/><path d="M11 10.4a2 2 0 0 1 2.1-.2"/>' },
    { name: "Rough endoplasmic reticulum", short: "Rough ER", group: "Protein workshop", color: "#a7afff", anchors: [[-2.22,-.47,.58]], fact: "This folded network helps its attached ribosomes make and prepare proteins.", icon: '<path d="M19 5c-4 3-9 1-13 4m13 2c-4 3-9 1-13 4m12 2c-3 2-7 1-10 3M8 5h.1M4 12h.1m16 3h.1m-8-4h.1m-7 7h.1"/>' },
    { name: "Smooth endoplasmic reticulum", short: "Smooth ER", group: "Lipid workshop", color: "#7dd9fa", anchors: [[-.39,1.62,-.19]], fact: "This network makes fats the cell needs and helps break down harmful chemicals.", icon: '<path d="M4 16c3-1 2-7 6-7 3 0 1 7 5 7 2 0 2-5 5-6M6 20c4-2 3-7 6-7m-1-3c.5-4 4-6 8-6"/>' },
    { name: "Ribosomes", short: "Ribosomes", group: "Protein builders", color: "#f8b7c7", anchors: [[-2.46,-.56,.75], [.30,.85,.96], [-.3,-1.35,.90], [1.46,-.50,-.36]], fact: "Ribosomes read instructions and link small building blocks together to make proteins.", icon: '<circle cx="7" cy="8" r="2"/><circle cx="15" cy="6" r="1.6"/><circle cx="17" cy="13" r="2.3"/><circle cx="8" cy="17" r="2"/><circle cx="15" cy="19" r="1"/>' },
    { name: "Golgi apparatus", short: "Golgi apparatus", group: "Packing and shipping", color: "#ffb481", anchors: [[1.60,.14,-.08]], fact: "The Golgi apparatus sorts, changes, and packs proteins for delivery.", icon: '<path d="M4 7c5 4 11 4 16 0M5 11c4 4 10 4 14 0M7 15c3 3 7 3 10 0m-7 4c1 .7 3 .7 4 0"/>' },
    { name: "Mitochondria", short: "Mitochondria", group: "Energy supply", color: "#ff967e", anchors: [[1.53,1.38,-.14], [-1.88,-1.62,.22], [1.56,-1.44,.03]], fact: "Mitochondria turn energy from food into a form the cell can use.", icon: '<path d="M21 10c.4 4-5.3 7.9-10.2 8C6 18.2 3 16 3 12.8c0-3.3 3.1-4.4 7-4.4 4 0 7.1-2.8 9.7-.8.8.6 1.2 1.4 1.3 2.4Z"/><path d="m6.8 13 2-2 2 3 2-3 2 2 2.1-2.3"/>' },
    { name: "Lysosomes", short: "Lysosomes", group: "Cell recycling", color: "#ffdb80", anchors: [[2.53,-.57,-.26], [-.67,-1.74,-.30], [-2.71,.40,-.28]], fact: "Lysosomes break down waste and recycle worn-out cell parts.", icon: '<circle cx="12" cy="12" r="8"/><path d="M8 10h.1m6-2h.1m2 6h.1m-6.8 1.6h.1m2.8-3.8h.1"/>' },
    { name: "Vesicles", short: "Vesicles", group: "Tiny cargo carriers", color: "#75ead1", anchors: [[2.54,.49,.53], [2.32,1.05,.14], [2.91,.00,-.49], [.55,-.48,1.29], [1.96,-.21,.88], [-2.13,1.40,-.46], [-.21,-1.91,.54], [2.13,-1.13,-.35], [.67,1.08,-.65]], fact: "Vesicles are tiny bubbles that carry materials around the cell.", icon: '<circle cx="9" cy="13" r="5.3"/><circle cx="17.2" cy="7.6" r="3.2"/><circle cx="17.7" cy="16.6" r="2.5"/>' },
    { name: "Centrioles", short: "Centrioles", group: "Cell division", color: "#d2ee90", anchors: [[.42,-.96,-.02]], fact: "Centrioles help organize the fibers that move chromosomes when a cell divides.", icon: '<path d="m5.3 18 6.4-8.8m-3.5 10.4 6.5-8.9M4.6 16.4l6.1-8.8m5.5 10.2 3.2-7.3m-5 6 3.2-7.1"/><ellipse cx="12.7" cy="8.9" rx="2.8" ry="1.6" transform="rotate(33 12.7 8.9)"/>' },
    { name: "Cytoskeleton", short: "Cytoskeleton", group: "Support and movement", color: "#8fc8fc", anchors: [[.62,1.85,-.33], [-2.33,-1.25,-.60], [2.45,1.03,-.89]], fact: "The cytoskeleton is a web of fibers that gives the cell shape and helps things move.", icon: '<path d="M4 7c4 1 8 5 16 11M4 17c6-4 10-5 16-9M9 4c1 5 2 10 1 16m6-16c-2 5-2 12 1 16M4 12c5 1 12 2 16 .5"/>' }
  ];

  const byId = id => document.getElementById(id);
  const surface = byId("surface");
  const stage = byId("stage");
  const pin = byId("part-pin");
  const leader = byId("leader");
  const line = byId("leader-line");
  const ring = byId("leader-ring");
  const dot = byId("leader-dot");
  const scrub = byId("scrub");
  const playButton = byId("play");
  const rebuildButton = byId("rebuild");
  const cutButton = byId("cut");
  const help = byId("help");
  const helpToggle = byId("help-toggle");
  const list = byId("part-list");
  const marks = byId("marks");
  const last = parts.length - 1;
  const reduceMotion = matchMedia("(prefers-reduced-motion: reduce)").matches;
  const field = 34;
  const tangent = Math.tan(field * Math.PI / 360);
  const initialYaw = .22;
  const initialPitch = .14;
  const cutAt = .055;
  const pace = 1620;
  const clamp = (v, min, max) => Math.min(max, Math.max(min, v));
  const scalar = (a, b, weight) => a + (b - a) * weight;
  const distanceSquared = (a, b) => a.reduce((sum, n, i) => sum + (n - b[i]) ** 2, 0);
  const icon = (body, size = 22) => '<svg width="' + size + '" height="' + size + '" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' + body + '</svg>';
  const arrow = '<svg class="part-arrow" width="13" height="13" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3.5 8h8m-3-3 3 3-3 3"/></svg>';
  const start = performance.now();
  const model = {
    step: 0, selected: 0, cut: false, focused: false, anchor: null,
    playing: true, next: start + 1550, demo: location.hash === "#demo",
    reveal: parts.map((_, i) => Number(i === 0)), motion: [], pose: null
  };
  const goal = { yaw: initialYaw, pitch: initialPitch, zoom: 1, target: [0,0,0] };
  const view = { yaw: initialYaw, pitch: initialPitch, zoom: 1, target: [0,0,0] };

  const partButtons = parts.map((part, i) => {
    const row = document.createElement("li");
    const button = document.createElement("button");
    button.type = "button";
    button.style.setProperty("--part", part.color);
    button.setAttribute("aria-label", part.name);
    button.innerHTML = '<span class="part-dot" aria-hidden="true"></span><span>' + part.short + '</span>' + arrow;
    button.addEventListener("click", () => explore(i));
    row.append(button);
    list.append(row);
    marks.append(document.createElement("i"));
    return button;
  });

  let displayedPart = -1;
  function sync() {
    const part = parts[model.selected];
    if (displayedPart !== model.selected) {
      displayedPart = model.selected;
      byId("details").style.setProperty("--part", part.color);
      byId("detail-symbol").innerHTML = icon(part.icon);
      byId("detail-category").textContent = part.group;
      byId("part-title").textContent = part.name;
      byId("part-fact").textContent = part.fact;
      byId("mobile-fact").textContent = part.fact;
      pin.textContent = part.short;
      ring.setAttribute("stroke", part.color);
      line.setAttribute("stroke", part.color);
      dot.setAttribute("fill", part.color);
    }
    byId("part-count").textContent = (model.step + 1) + " of " + parts.length + " visible";
    byId("step-readout").textContent = "Step " + (model.step + 1) + " of " + parts.length;
    scrub.value = model.step;
    scrub.style.setProperty("--pct", (100 * model.step / last) + "%");
    scrub.setAttribute("aria-valuetext", "Step " + (model.step + 1) + " of " + parts.length + ", " + parts[model.step].name);
    partButtons.forEach((button, i) => {
      button.dataset.built = String(i <= model.step);
      if (i === model.selected) button.setAttribute("aria-current", "true");
      else button.removeAttribute("aria-current");
      marks.children[i].dataset.passed = String(i <= model.step);
    });
    cutButton.setAttribute("aria-checked", String(model.cut));
    stage.dataset.focused = String(model.focused);
    const ongoing = model.playing || model.demo;
    byId("state-label").dataset.running = String(ongoing || model.step === last);
    byId("state-text").textContent = model.demo ? "Demo playing" : model.step === last ? "Cell complete" : ongoing ? "Building cell" : "Build paused";
    const playLabel = ongoing ? "Pause build" : model.step === last ? "Replay build" : "Play build";
    playButton.setAttribute("aria-label", playLabel);
    playButton.title = playLabel;
    playButton.innerHTML = ongoing
      ? icon('<path fill="currentColor" stroke="none" d="M7 5h3.6v14H7zm6.4 0H17v14h-3.6z"/>', 19)
      : icon('<path fill="currentColor" stroke="none" d="M8 4.5v15l12-7.5z"/>', 19);
  }

  function selectBuildStep(i) {
    model.step = clamp(i, 0, last);
    model.selected = model.step;
    model.focused = false;
    model.anchor = null;
    for (let j = model.step + 1; j <= last; j += 1) model.reveal[j] = 0;
    sync();
  }

  function overview() {
    goal.yaw = initialYaw + Math.PI * 2 * Math.round((view.yaw - initialYaw) / (Math.PI * 2));
    goal.pitch = initialPitch;
    goal.zoom = 1;
    goal.target = [0,0,0];
  }

  function rebuild() {
    model.playing = true;
    model.cut = false;
    model.next = performance.now() + 1220;
    overview();
    selectBuildStep(0);
  }

  function targetFor(i, point) {
    const anchors = parts[i].anchors;
    const available = model.cut ? anchors.filter(p => p[2] <= cutAt) : anchors;
    const choices = available.length ? available : anchors;
    let anchor = choices[0];
    if (point) {
      for (const candidate of choices) {
        if (distanceSquared(candidate, point) < distanceSquared(anchor, point)) anchor = candidate;
      }
    }
    return model.cut && anchor[2] > cutAt ? [anchor[0],anchor[1],cutAt - .015] : anchor;
  }

  function explore(i, point, handsFree = false) {
    if (!handsFree) model.playing = false;
    if (i > model.step) model.step = i;
    model.selected = i;
    model.focused = true;
    model.anchor = targetFor(i, point);
    goal.target = model.anchor.slice();
    goal.zoom = i === 0 ? .82 : (i === 5 || i === 9 ? .50 : .57);
    if (!model.cut && i === 3) goal.yaw -= .14;
    sync();
  }

  function setCut(cut) {
    model.cut = cut;
    if (cut && Math.cos(goal.yaw) < .35) {
      goal.yaw = initialYaw + Math.PI * 2 * Math.round((view.yaw - initialYaw) / (Math.PI * 2));
    }
    if (model.focused) {
      model.anchor = targetFor(model.selected, model.anchor);
      goal.target = model.anchor.slice();
    }
    sync();
  }

  function dismissDemo() {
    if (!model.demo) return;
    model.demo = false;
    model.playing = false;
    rebuildButton.dataset.demo = "false";
    sync();
  }
  for (const type of ["pointerdown", "wheel", "keydown"]) {
    window.addEventListener(type, event => {
      if (event.isTrusted) dismissDemo();
    }, { capture: true, passive: true });
  }

  cutButton.addEventListener("click", () => setCut(!model.cut));
  rebuildButton.addEventListener("click", rebuild);
  byId("reset-view").addEventListener("click", () => {
    overview();
    model.focused = false;
    model.anchor = null;
    sync();
  });
  function zoom(factor) { goal.zoom = clamp(goal.zoom * factor, .31, 2.5); }
  byId("zoom-in").addEventListener("click", () => zoom(.83));
  byId("zoom-out").addEventListener("click", () => zoom(1.2));
  playButton.addEventListener("click", () => {
    if (model.playing) {
      model.playing = false;
      sync();
    } else if (model.step === last) {
      rebuild();
    } else {
      model.playing = true;
      model.next = performance.now() + 690;
      overview();
      selectBuildStep(model.step);
    }
  });
  scrub.addEventListener("input", () => {
    model.playing = false;
    overview();
    selectBuildStep(Number(scrub.value));
  });
  helpToggle.addEventListener("click", () => {
    help.hidden = !help.hidden;
    helpToggle.setAttribute("aria-expanded", String(!help.hidden));
  });
  document.addEventListener("pointerdown", event => {
    if (!help.hidden && !help.contains(event.target) && !helpToggle.contains(event.target)) helpToggle.click();
  });
  document.addEventListener("keydown", event => {
    if (event.key === "Escape" && !help.hidden) {
      helpToggle.click();
      helpToggle.focus();
    }
  });

  let width = 1;
  let height = 1;
  let resizeNeeded = true;
  let graphics;
  const pointers = new Map();
  let gestureMoved = false;
  surface.addEventListener("pointerdown", event => {
    if (event.pointerType === "mouse" && event.button !== 0) return;
    if (!pointers.size) gestureMoved = false;
    else gestureMoved = true;
    pointers.set(event.pointerId, { x: event.clientX, y: event.clientY, startX: event.clientX, startY: event.clientY });
    surface.setPointerCapture(event.pointerId);
  });
  surface.addEventListener("pointermove", event => {
    const pointer = pointers.get(event.pointerId);
    if (!pointer) return;
    const dx = event.clientX - pointer.x;
    const dy = event.clientY - pointer.y;
    if (pointers.size === 2) {
      const other = [...pointers.values()].find(item => item !== pointer);
      const before = Math.hypot(other.x - pointer.x, other.y - pointer.y);
      const after = Math.hypot(other.x - event.clientX, other.y - event.clientY);
      if (before > 6 && after > 6) zoom(before / after);
    } else if (pointers.size === 1) {
      if (Math.hypot(event.clientX - pointer.startX, event.clientY - pointer.startY) > 4) gestureMoved = true;
      if (gestureMoved) {
        goal.yaw -= dx * .008;
        goal.pitch = clamp(goal.pitch + dy * .008, -1.39, 1.39);
      }
    }
    pointer.x = event.clientX;
    pointer.y = event.clientY;
  });
  surface.addEventListener("pointerup", event => {
    if (!pointers.has(event.pointerId)) return;
    const tap = !gestureMoved && pointers.size === 1;
    pointers.delete(event.pointerId);
    if (tap && graphics && model.pose) {
      const bounds = surface.getBoundingClientRect();
      const hit = graphics.pick(event.clientX - bounds.left, event.clientY - bounds.top);
      if (hit) explore(hit.id, hit.point);
    }
  });
  for (const type of ["pointercancel", "lostpointercapture"]) {
    surface.addEventListener(type, event => pointers.delete(event.pointerId));
  }
  surface.addEventListener("wheel", event => {
    event.preventDefault();
    const units = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? height : 1;
    zoom(Math.exp(clamp(event.deltaY * units * .0014, -.35, .35)));
  }, { passive: false });

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

  function shellPoint(x, y, z) {
    const swell = 1 + .038 * Math.sin(x * 6 + y * 4 - z * 3) + .021 * Math.cos(y * 11 + z * 5) + .018 * Math.sin(z * 8 - x * 4);
    return [3.72 * swell * x, 2.58 * swell * y, 2.46 * swell * z];
  }

  function worldPoint(id, point) {
    if (id === 0 || !model.motion[id]) return point;
    const move = model.motion[id];
    return point.map((value, i) => value * move.scale + move.offset[i]);
  }

  function project(point) {
    const { back, right, up, distance } = model.pose;
    const delta = point.map((value, i) => value - view.target[i]);
    const depth = distance - delta.reduce((sum, value, i) => sum + value * back[i], 0);
    const scale = height / (2 * tangent * Math.max(.06, depth));
    return {
      x: width / 2 + scale * delta.reduce((sum, value, i) => sum + value * right[i], 0),
      y: height / 2 - scale * delta.reduce((sum, value, i) => sum + value * up[i], 0),
      depth, scale
    };
  }

  function nearbyPart(x, y) {
    let best = null;
    let score = Infinity;
    for (let id = 1; id <= model.step; id += 1) {
      for (const anchor of parts[id].anchors) {
        const point = worldPoint(id, anchor);
        if (model.cut && point[2] > cutAt + .09) continue;
        const screen = project(point);
        const d = Math.hypot(x - screen.x, y - screen.y);
        const limit = id === 1 ? 41 : id === 5 || id === 9 ? 18 : 26;
        const weighted = d + (id === 1 ? 7 : 0);
        if (screen.depth > .08 && d < limit && weighted < score) {
          score = weighted;
          best = { id, point };
        }
      }
    }
    return best;
  }

  function positionPin() {
    const id = model.selected;
    const anchor = model.anchor || targetFor(id);
    const labelPoint = worldPoint(id, anchor);
    const projected = project(labelPoint);
    const show = projected.depth > .12 && projected.x > 6 && projected.x < width - 6 && projected.y > 34 && projected.y < height - 26;
    pin.hidden = !show;
    leader.hidden = !show;
    if (!show) return;
    const half = Math.min(126, pin.offsetWidth / 2 + 9);
    const labelX = clamp(projected.x + (id === 0 ? -13 : 18), half, width - half);
    const labelY = clamp(projected.y - 31, 83, height - 75);
    pin.style.left = labelX + "px";
    pin.style.top = labelY + "px";
    const x = projected.x.toFixed(1);
    const y = projected.y.toFixed(1);
    line.setAttribute("d", "M" + x + " " + y + " L" + x + " " + (labelY + (projected.y > labelY ? 9 : -8)) + " L" + labelX + " " + labelY);
    for (const circle of [ring, dot]) {
      circle.setAttribute("cx", x);
      circle.setAttribute("cy", y);
    }
  }

  const animator = { cycle: -1, phase: -1 };
  function runDemo(now) {
    const seconds = (now - start) / 1000;
    const cycle = Math.floor(seconds / 20.7);
    const time = seconds % 20.7;
    if (cycle !== animator.cycle) {
      animator.cycle = cycle;
      animator.phase = -1;
    }
    const phase = time < 9.5 ? 0 : time < 11.5 ? 1 : time < 14.2 ? 2 : time < 16.6 ? 3 : time < 18.45 ? 4 : 5;
    if (phase !== animator.phase) {
      animator.phase = phase;
      rebuildButton.dataset.demo = String(phase === 5);
      if (phase === 0 || phase === 5) {
        model.cut = false;
        overview();
        selectBuildStep(0);
      } else if (phase === 1) {
        model.cut = false;
        selectBuildStep(last);
      } else if (phase === 2) {
        model.cut = false;
        model.step = last;
        explore(7, null, true);
      } else if (phase === 3) {
        overview();
        selectBuildStep(last);
        setCut(true);
      } else {
        model.cut = false;
        overview();
        selectBuildStep(last);
      }
    }
    if (phase === 0) {
      const step = clamp(Math.floor((time - .22) / .80), 0, last);
      if (step !== model.step) selectBuildStep(step);
      goal.yaw = initialYaw + .22 * Math.sin(time * .37);
    } else if (phase === 1) {
      goal.yaw = .16 - .57 * clamp((time - 9.5) / 2, 0, 1);
      goal.pitch = .26;
    } else if (phase === 3) {
      goal.yaw = .15 + .37 * (time - 14.2) / 2.4;
    } else if (phase === 4) {
      const step = Math.max(3, last - Math.floor((time - 16.6) * 5));
      if (step !== model.step) selectBuildStep(step);
    } else if (phase === 5 && time > 19.58 && model.step === 0) {
      selectBuildStep(1);
    }
  }

  function makeCanvasModel() {
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
    const random = randomGenerator(215);
    const flecks = Array.from({ length: 150 }, () => {
      const angle = random() * Math.PI * 2;
      const y = 2 * random() - 1;
      const radius = Math.sqrt(1 - y * y);
      return shellPoint(radius * Math.cos(angle), y, radius * Math.sin(angle));
    });
    const seeds = Array.from({ length: 48 }, () => {
      const angle = random() * Math.PI * 2;
      const radius = Math.sqrt(random());
      return [3.0 * radius * Math.cos(angle), 2.05 * radius * Math.sin(angle), (random() - .5) * 1.75];
    });
    const sizes = { 1: 1.18, 2: .43, 3: .78, 4: .68, 6: .79, 7: .76, 8: .26, 9: .145, 10: .42 };
    let pixels = 1;
    let cell = null;
    function oval(x, y, rx, ry, angle = 0) {
      ctx.beginPath();
      ctx.ellipse(x, y, Math.max(.01, rx), Math.max(.01, ry), angle, 0, Math.PI * 2);
    }
    function litOrb(r, color, transparent = false) {
      const fill = ctx.createRadialGradient(-r * .33, -r * .44, r * .04, 0, 0, r * 1.28);
      fill.addColorStop(0, transparent ? color + "b8" : "#fff4ec");
      fill.addColorStop(.39, transparent ? color + "45" : color);
      fill.addColorStop(.85, transparent ? color + "19" : "#3d243e");
      ctx.fillStyle = fill;
      oval(0, 0, r, r * .92, -.1);
      ctx.fill();
      ctx.strokeStyle = color + "bc";
      ctx.lineWidth = Math.max(.7, r * .019);
      ctx.stroke();
    }
    function paintPart(id, r, index) {
      const color = parts[id].color;
      ctx.lineCap = "round";
      ctx.lineJoin = "round";
      if (id === 1 || id === 2 || id === 8 || id === 9) {
        litOrb(r, color, id === 1 || id === 9);
        if (id === 1 || id === 8) {
          ctx.strokeStyle = color + "88";
          ctx.lineWidth = Math.max(1, r * .033);
          for (let j = 0; j < 5; j += 1) {
            ctx.beginPath();
            ctx.ellipse((j % 3 - 1) * r * .33, (j / 2 - 1) * r * .27, r * .29, r * .13, j - 1, .2, 3.7);
            ctx.stroke();
          }
        }
      } else if (id === 7) {
        ctx.rotate([-.48, .34, -.20][index]);
        const fill = ctx.createLinearGradient(0,-r*.5,0,r*.5);
        fill.addColorStop(0,"#ffd1b5");
        fill.addColorStop(.46,"#d96e63");
        fill.addColorStop(1,"#6e3b56");
        ctx.fillStyle = fill;
        ctx.beginPath();
        ctx.moveTo(-r,0);
        ctx.bezierCurveTo(-r,-r*.62,-r*.16,-r*.39,r*.12,-r*.42);
        ctx.bezierCurveTo(r*.85,-r*.69,r*1.14,-r*.29,r*.95,r*.09);
        ctx.bezierCurveTo(r*.78,r*.54,-r*.89,r*.58,-r,0);
        ctx.fill();
        ctx.strokeStyle = "#ffbfaa";
        ctx.lineWidth = Math.max(1.3,r*.065);
        ctx.beginPath();
        for (let j = 0; j < 9; j += 1) {
          const x = (-.73 + j * .18) * r;
          const y = (j % 2 ? -.23 : .17) * r;
          if (j) ctx.lineTo(x,y);
          else ctx.moveTo(x,y);
        }
        ctx.stroke();
      } else if (id === 3 || id === 6) {
        ctx.rotate(id === 3 ? .63 : -.11);
        for (let j = 0; j < 5; j += 1) {
          const y = (j - 2) * r * .24;
          const span = r * (1 - .07 * j);
          ctx.beginPath();
          ctx.moveTo(-span,y-r*.24);
          ctx.bezierCurveTo(-r*.47,y+r*.37,r*.48,y+r*.31,span,y-r*.24);
          ctx.strokeStyle = id === 3 ? "#4e4f92" : "#8a4744";
          ctx.lineWidth = r * .23;
          ctx.stroke();
          ctx.strokeStyle = color;
          ctx.lineWidth = r * .115;
          ctx.stroke();
        }
      } else if (id === 4) {
        for (let j = 0; j < 6; j += 1) {
          ctx.beginPath();
          ctx.moveTo(-r + j * r * .16, r * .57);
          ctx.bezierCurveTo(-r * .40, (-1+j*.24)*r, r*.02, (.4-j*.26)*r, r*(j*.22-.10), -r*.48);
          ctx.strokeStyle = j % 2 ? "#5dabc9" : color;
          ctx.lineWidth = Math.max(1.5,r*.12);
          ctx.stroke();
        }
      } else if (id === 10) {
        for (let j = 0; j < 2; j += 1) {
          ctx.save();
          ctx.translate(r * (j ? .32 : -.25),r * (j ? .12 : -.2));
          ctx.rotate(j ? .75 : -.66);
          ctx.strokeStyle = color;
          ctx.lineWidth = r * .1;
          for (let k = -2; k < 3; k += 1) {
            ctx.beginPath();
            ctx.moveTo(k * r * .11,-r*.6);
            ctx.lineTo(k * r * .11,r*.6);
            ctx.stroke();
          }
          ctx.restore();
        }
      }
    }
    return {
      canvas,
      resize(w, h) {
        pixels = Math.min(2, devicePixelRatio || 1);
        canvas.width = Math.max(1, Math.round(w * pixels));
        canvas.height = Math.max(1, Math.round(h * pixels));
      },
      draw() {
        if (!ctx) return;
        ctx.setTransform(pixels,0,0,pixels,0,0);
        ctx.clearRect(0,0,width,height);
        const center = project([0,0,0]);
        const rx = center.scale * Math.hypot(3.68 * Math.cos(view.yaw), 2.48 * Math.sin(view.yaw));
        const ry = center.scale * 2.59;
        cell = { center, rx, ry };
        ctx.save();
        oval(center.x,center.y,rx,ry,-.075);
        ctx.clip();
        const gel = ctx.createRadialGradient(center.x-rx*.26,center.y-ry*.36,0,center.x,center.y,rx);
        gel.addColorStop(0,"#70cfca29");
        gel.addColorStop(.56,"#31778f2e");
        gel.addColorStop(.91,"#75ebd351");
        gel.addColorStop(1,"#a3efe883");
        ctx.fillStyle = gel;
        ctx.fillRect(0,0,width,height);
        if (model.step === last) {
          for (let j = 0; j < 18; j += 1) {
            const end = project(worldPoint(last, shellPoint(Math.cos(j*.79)*.93, Math.sin(j*.79)*.93, -.32)));
            const base = project(worldPoint(last,[.42,-.96,-.20]));
            ctx.strokeStyle = j % 3 ? "#8fd4ff5e" : "#b4a5ff68";
            ctx.lineWidth = 1;
            ctx.beginPath();
            ctx.moveTo(base.x,base.y);
            ctx.quadraticCurveTo((base.x+end.x)*.5+Math.sin(j)*32,(base.y+end.y)*.53,end.x,end.y);
            ctx.stroke();
          }
        }
        const visible = [];
        for (let id = 1; id <= model.step; id += 1) {
          if (id === last) continue;
          const locations = id === 5 ? seeds.concat(parts[id].anchors) : parts[id].anchors;
          locations.forEach((anchor, index) => {
            const p = worldPoint(id,anchor);
            const r = id === 5 ? .045 : sizes[id] * (id === 8 || id === 9 ? 1 - (index % 4) * .115 : 1);
            if (model.cut && p[2] > cutAt + r*.60) return;
            visible.push({ id, index, r, screen: project(p) });
          });
        }
        visible.sort((a,b) => b.screen.depth - a.screen.depth);
        for (const item of visible) {
          const { id, index, r, screen } = item;
          if (screen.depth <= .1) continue;
          ctx.save();
          ctx.globalAlpha = model.reveal[id];
          ctx.translate(screen.x,screen.y);
          const size = screen.scale * r * model.motion[id].scale;
          if (id === 5) {
            ctx.fillStyle = parts[id].color;
            oval(0,0,size,size);
            ctx.fill();
          } else paintPart(id,size,index);
          ctx.restore();
        }
        for (const point of flecks) {
          if (model.cut && point[2] > cutAt) continue;
          const screen = project(point);
          if (screen.depth <= .1) continue;
          ctx.fillStyle = "#b4fff04a";
          oval(screen.x,screen.y,Math.min(1.35,screen.scale*.015),Math.min(1.35,screen.scale*.015));
          ctx.fill();
        }
        ctx.restore();
        oval(center.x,center.y,rx,ry,-.075);
        ctx.strokeStyle = model.cut ? "#a6f5dccf" : "#8bebe498";
        ctx.lineWidth = model.cut ? 2.4 : 1.6;
        ctx.stroke();
        if (model.cut) {
          oval(center.x,center.y,rx*.975,ry*.972,-.075);
          ctx.setLineDash([3,6]);
          ctx.strokeStyle = "#93f3db72";
          ctx.lineWidth = 1;
          ctx.stroke();
          ctx.setLineDash([]);
        }
      },
      pick(x, y) {
        const part = nearbyPart(x,y);
        if (part) return part;
        if (cell && ((x-cell.center.x)/cell.rx)**2 + ((y-cell.center.y)/cell.ry)**2 <= 1.05) {
          return { id: 0, point: parts[0].anchors[0] };
        }
        return null;
      }
    };
  }

  function makeThreeModel(T) {
    const renderer = new T.WebGLRenderer({ alpha: true, antialias: true, powerPreference: "low-power" });
    renderer.setClearColor(0x000000, 0);
    renderer.setPixelRatio(Math.min(1.75, devicePixelRatio || 1));
    renderer.outputColorSpace = T.SRGBColorSpace;
    renderer.toneMapping = T.ACESFilmicToneMapping;
    renderer.toneMappingExposure = 1.10;
    renderer.localClippingEnabled = true;
    const scene = new T.Scene();
    const camera = new T.PerspectiveCamera(field, 1, .08, 100);
    const ray = new T.Raycaster();
    const cutPlane = new T.Plane(new T.Vector3(0,0,-1), 30);
    const random = randomGenerator(3807);
    const vec = p => new T.Vector3(...p);
    const targets = [];
    const groups = parts.map(() => {
      const group = new T.Group();
      scene.add(group);
      return group;
    });
    scene.add(new T.HemisphereLight(0xe4faff,0x38406f,1.75));
    const light = (color, intensity, position) => {
      const lamp = new T.DirectionalLight(color,intensity);
      lamp.position.set(...position);
      scene.add(lamp);
    };
    light(0xfff0e5,2.55,[-4,6,8]);
    light(0x83dfff,1.85,[5,2,-4]);
    light(0xe6a1ff,.80,[-4,-3,1]);

    function material(color, options = {}) {
      return new T.MeshStandardMaterial({ color, roughness: .44, metalness: .04, clippingPlanes: [cutPlane], ...options });
    }

    function gelMaterial(a, b, strength, nucleus = false) {
      return new T.ShaderMaterial({
        transparent: true,
        depthWrite: false,
        side: T.FrontSide,
        toneMapped: false,
        uniforms: {
          tintA: { value: new T.Color(a) }, tintB: { value: new T.Color(b) },
          strength: { value: strength }, cut: { value: 30 }, time: { value: 0 }, core: { value: nucleus ? .22 : .035 }
        },
        vertexShader: "varying vec3 world; varying vec3 nrm; void main(){ vec4 p=modelMatrix*vec4(position,1.0); world=p.xyz; nrm=normalize(mat3(modelMatrix)*normal); gl_Position=projectionMatrix*viewMatrix*p; }",
        fragmentShader: [
          "uniform vec3 tintA; uniform vec3 tintB; uniform float strength, cut, time, core;",
          "varying vec3 world; varying vec3 nrm;",
          "void main(){ if(world.z>cut) discard;",
          "vec3 n=normalize(nrm); vec3 eye=normalize(cameraPosition-world);",
          "float fres=1.0-max(0.0,dot(n,eye));",
          "float ripple=sin(world.x*6.0+sin(world.y*6.6+world.z*2.9)+time*.32)*.5+.5;",
          "float speck=sin(world.x*37.0+world.y*34.0)*sin(world.z*35.0-world.y*27.0)*.5+.5;",
          "float shine=pow(max(0.0,dot(n,normalize(vec3(-.39,.75,.52)))),16.0);",
          "float edge=pow(fres,3.0);",
          "vec3 c=mix(tintB,tintA,clamp(.48+world.y*.14+ripple*.17,0.0,1.0));",
          "c=mix(c,vec3(.85,1.0,.98),clamp(shine*.43+edge*.34,0.0,.74));",
          "float alpha=strength*min(.90,core+pow(fres,1.8)*.69+shine*.19+ripple*.044+speck*.028);",
          "gl_FragColor=vec4(pow(max(c,vec3(0.0)),vec3(.4545)),alpha); }"
        ].join("\n")
      });
    }

    function bodyGeometry(rx, ry, rz, ripple, phase, segments = 40) {
      const geometry = new T.SphereGeometry(1, segments, Math.max(16, Math.floor(segments*.63)));
      const p = geometry.attributes.position;
      for (let j = 0; j < p.count; j += 1) {
        const x = p.getX(j), y = p.getY(j), z = p.getZ(j);
        const scale = 1 + ripple * (Math.sin(7*x + 3*z + phase) * Math.cos(6*y - phase) + .45 * Math.sin(9*z - 4*y));
        p.setXYZ(j,rx*x*scale,ry*y*scale,rz*z*scale);
      }
      geometry.computeVertexNormals();
      geometry.computeBoundingSphere();
      return geometry;
    }

    function put(parent, geometry, mat, position = [0,0,0], id = null) {
      const mesh = new T.Mesh(geometry, mat);
      mesh.position.set(...position);
      parent.add(mesh);
      if (id !== null) {
        mesh.userData.part = id;
        targets.push(mesh);
      }
      return mesh;
    }

    function makePath(points) {
      return new T.CatmullRomCurve3(points.map(vec), false, "centripetal");
    }

    function tube(parent, path, radius, mat, id = null, steps = 40, sides = 7) {
      return put(parent,new T.TubeGeometry(path,steps,radius,sides,path.closed),mat,[0,0,0],id);
    }

    function ribbon(parent, path, broad, thick, mat, id) {
      const positions = [];
      const faces = [];
      const segments = 40;
      const sides = 12;
      const up = new T.Vector3(0,0,1);
      for (let i = 0; i <= segments; i += 1) {
        const t = i / segments;
        const point = path.getPoint(t);
        const along = path.getTangent(t);
        const side = up.clone().cross(along).normalize();
        const normal = along.clone().cross(side).normalize();
        const taper = .105 + .895 * Math.pow(Math.sin(Math.PI*t),.39);
        for (let j = 0; j < sides; j += 1) {
          const a = (j/sides)*Math.PI*2;
          const edge = point.clone().addScaledVector(side,Math.cos(a)*broad*taper).addScaledVector(normal,Math.sin(a)*thick*taper);
          positions.push(edge.x,edge.y,edge.z);
          if (i === segments) continue;
          const v = i*sides+j;
          const w = i*sides+(j+1)%sides;
          faces.push(v,w,v+sides,w,w+sides,v+sides);
        }
      }
      const geometry = new T.BufferGeometry();
      geometry.setAttribute("position",new T.Float32BufferAttribute(positions,3));
      geometry.setIndex(faces);
      geometry.computeVertexNormals();
      return put(parent,geometry,mat,[0,0,0],id);
    }

    function points(parent, coordinates, color, size, opacity, cut = true) {
      const geometry = new T.BufferGeometry();
      geometry.setAttribute("position",new T.Float32BufferAttribute(coordinates.flat(),3));
      const mat = new T.PointsMaterial({ color, size, opacity, transparent: true, depthWrite: false, clippingPlanes: cut ? [cutPlane] : [] });
      const cloud = new T.Points(geometry,mat);
      parent.add(cloud);
      return cloud;
    }

    function sphereSample() {
      const a = random() * Math.PI * 2;
      const y = random() * 2 - 1;
      const r = Math.sqrt(1-y*y);
      return [r*Math.cos(a),y,r*Math.sin(a)];
    }

    const shellGeo = new T.SphereGeometry(1,96,56);
    const shellPositions = shellGeo.attributes.position;
    for (let i = 0; i < shellPositions.count; i += 1) {
      shellPositions.setXYZ(i,...shellPoint(shellPositions.getX(i),shellPositions.getY(i),shellPositions.getZ(i)));
    }
    shellGeo.computeVertexNormals();
    shellGeo.computeBoundingSphere();
    const cellGel = gelMaterial("#7defd6","#697ebf",.86);
    const shell = put(groups[0],shellGeo,cellGel);
    shell.renderOrder = 20;
    const shellDots = Array.from({ length: 820 }, () => {
      const p = shellPoint(...sphereSample());
      return p.map(x => x * 1.002);
    });
    points(groups[0],shellDots,0x98f4e2,.025,.39).renderOrder = 21;
    points(groups[0],shellDots.filter((_,i) => i%23 === 0),0xbde8ff,.049,.37).renderOrder = 21;

    const cutFace = new T.Group();
    scene.add(cutFace);
    const edgePositions = Array.from({length:96}, (_,i) => {
      const a = i/96*Math.PI*2;
      const p = shellPoint(Math.cos(a),Math.sin(a),0);
      return [p[0],p[1],cutAt];
    });
    const edge = new T.CatmullRomCurve3(edgePositions.map(vec),true);
    const rimMat = new T.MeshBasicMaterial({color:0x9df6de,transparent:true,opacity:.85,depthWrite:false});
    tube(cutFace,edge,.029,rimMat,null,124,8).renderOrder = 25;
    const capShape = new T.Shape(edgePositions.map(p => new T.Vector2(p[0]*.995,p[1]*.995)));
    const capMat = new T.MeshBasicMaterial({color:0x75dfa9,transparent:true,opacity:.065,side:T.DoubleSide,depthWrite:false});
    put(cutFace,new T.ShapeGeometry(capShape),capMat,[0,0,cutAt]).renderOrder = 23;
    points(cutFace,edgePositions.filter((_,i) => i%2 === 0).map(p => [p[0]*.966,p[1]*.966,p[2]+.007]),0xafefe4,.034,.78,false).renderOrder = 24;

    const nucleus = parts[1].anchors[0];
    const nucleusGel = gelMaterial("#c8adff","#695ac1",1.12,true);
    put(groups[1],bodyGeometry(1.28,1.09,1.06,.032,2,64),nucleusGel,nucleus,1).renderOrder = 12;
    const chromatin = material(0xb89af8,{transparent:true,opacity:.49,depthWrite:false,roughness:.66});
    for (let strand = 0; strand < 11; strand += 1) {
      const phase = strand*.87;
      const track = Array.from({ length: 13 }, (_,i) => {
        const u = i/12;
        const a = u*3.75 + phase;
        return [
          nucleus[0] + Math.cos(a)*(.56+.16*Math.sin(a*3+phase)),
          nucleus[1] + .62*Math.sin(a+phase*.3),
          nucleus[2] + .51*Math.sin(a*1.72+phase*.71)
        ];
      });
      tube(groups[1],makePath(track),.016+(strand%3)*.004,chromatin,null,30,5).renderOrder = 5;
    }
    const pores = Array.from({ length:210 }, () => {
      const [x,y,z] = sphereSample();
      return [nucleus[0]+x*1.28,nucleus[1]+y*1.09,nucleus[2]+z*1.06];
    });
    points(groups[1],pores,0xd3c7ff,.035,.49).renderOrder = 13;

    const nucleolus = parts[2].anchors[0];
    put(groups[2],bodyGeometry(.43,.38,.40,.076,1.2),material(0xd261aa,{emissive:0x502443,emissiveIntensity:.18}),nucleolus,2);
    points(groups[2],Array.from({length:120}, () => {
      const [x,y,z] = sphereSample();
      return [nucleolus[0]+x*.435,nucleolus[1]+y*.385,nucleolus[2]+z*.407];
    }),0xffc0eb,.023,.71).renderOrder = 11;

    const roughTracks = [];
    for (let layer = 0; layer < 5; layer += 1) {
      const path = makePath(Array.from({length:21},(_,i) => {
        const t = i/20;
        const angle = 2.56 + t * (2.28 - layer*.14);
        return [
          -.88 + (1.14 + layer*.225)*Math.cos(angle),
          .27 + (.96 + layer*.144)*Math.sin(angle),
          .56 - layer*.16 + .22*Math.sin(t*6.1 + layer*.54)
        ];
      }));
      roughTracks.push(path);
      ribbon(groups[3],path,.119,.075,material(layer%2 ? 0x6868b8 : 0x8589db),3);
    }

    const smoothPaths = [
      [[-1.53,1.23,-.55],[-1.40,1.71,-.45],[-.94,1.94,-.29],[-.55,1.90,-.32],[-.12,1.63,-.22],[.27,1.70,-.33],[.51,1.98,-.50]],
      [[-1.72,1.52,-.61],[-1.37,1.98,-.49],[-.87,2.07,-.33],[-.45,2.19,-.50],[-.09,1.95,-.39],[.08,1.74,-.30]],
      [[-1.12,1.10,-.79],[-.79,1.36,-.45],[-.41,1.56,-.25],[-.12,1.45,-.41],[.25,1.48,-.55],[.55,1.72,-.56]],
      [[-.63,1.38,-.33],[-.33,1.53,-.15],[-.42,1.80,-.30],[-.38,2.07,-.50],[.09,2.21,-.68],[.48,2.09,-.58]],
      [[.28,1.47,-.55],[.51,1.46,-.54],[.65,1.65,-.60],[.43,1.83,-.44],[.55,2.01,-.50]],
      [[-.71,1.94,-.34],[-.59,1.82,-.14],[-.32,1.70,-.04],[-.13,1.81,.05],[.19,1.88,-.19]],
      [[-1.62,1.64,-.55],[-1.59,1.39,-.30],[-1.37,1.36,-.20],[-1.15,1.58,-.30],[-.87,1.60,-.40]]
    ];
    const smoothMats = [material(0x3f9fc9), material(0x69cadc), material(0x529bc5)];
    smoothPaths.forEach((track,i) => tube(groups[4],makePath(track),.057+(i%3)*.009,smoothMats[i%3],4,45,8));

    const ribosomePositions = [];
    roughTracks.forEach((path, row) => {
      for (let j = 0; j < 21; j += 1) {
        const q = path.getPoint(.095+.81*(j/20));
        ribosomePositions.push([q.x+(random()-.5)*.17,q.y+(random()-.5)*.15,q.z+.065+random()*.042]);
      }
      if (row < 3) ribosomePositions.push(parts[5].anchors[row]);
    });
    for (let j = 0; j < 66; j += 1) {
      const [x,y,z] = sphereSample();
      const r = .47+random()*.41;
      const p = [x*3.55*r,y*2.38*r,z*2.30*r];
      if (distanceSquared(p,nucleus)>1.24) ribosomePositions.push(p);
    }
    const ribosomeGeometry = new T.IcosahedronGeometry(.050,1);
    const ribosomes = new T.InstancedMesh(ribosomeGeometry,material(0xffadc3,{roughness:.6,emissive:0x6b3247,emissiveIntensity:.22}),ribosomePositions.length);
    const dummy = new T.Object3D();
    ribosomePositions.forEach((p,i) => {
      dummy.position.set(...p);
      dummy.rotation.set(random()*2,random()*2,random()*2);
      dummy.scale.setScalar(.64+random()*.62);
      dummy.updateMatrix();
      ribosomes.setMatrixAt(i,dummy.matrix);
    });
    ribosomes.instanceMatrix.needsUpdate = true;
    ribosomes.userData.part = 5;
    groups[5].add(ribosomes);
    targets.push(ribosomes);

    for (let i = 0; i < 6; i += 1) {
      const path = makePath(Array.from({length:17},(_,j) => {
        const t = j/16;
        const s = (t-.5)*2;
        return [
          1.57 + s*(.90-i*.050) + i*.039,
          .65 - i*.187 + s*s*(.28-i*.015) + s*.11,
          -.18 - i*.06 + .22*(1-s*s) + .29*s
        ];
      }));
      const golgiColors = [0xf3a968,0xe98f62,0xf2a373,0xec926f,0xefab76,0xdd8262];
      ribbon(groups[6],path,.115,.209,material(golgiColors[i],{roughness:.38}),6);
    }

    const mitoCore = material(0xa24257,{roughness:.73});
    const mitoFolds = material(0xffad93,{emissive:0x994754,emissiveIntensity:.13,roughness:.44});
    const mitoRim = material(0xec7968,{roughness:.4});
    const mitoShell = material(0xe97f77,{transparent:true,opacity:.39,depthWrite:false,roughness:.24});
    parts[7].anchors.forEach((position,i) => {
      const bean = new T.Group();
      bean.position.set(...position);
      bean.rotation.set([.22,-.26,.55][i],[-.16,.22,.53][i],[-.44,.34,-.20][i]);
      bean.scale.setScalar([1,.87,.84][i]);
      groups[7].add(bean);
      put(bean,bodyGeometry(.76,.319,.243,.059,1.3),mitoShell,[0,0,.007],7).renderOrder = 9;
      put(bean,bodyGeometry(.695,.257,.147,.068,1.3),mitoCore,[0,0,-.037],7);
      const surround = Array.from({length:38},(_,j) => {
        const a = j/38*Math.PI*2;
        return [.712*Math.cos(a),.277*Math.sin(a)+.048*Math.cos(a*2),.077+.023*Math.sin(a)];
      });
      tube(bean,new T.CatmullRomCurve3(surround.map(vec),true),.024,mitoRim,7,64,7);
      const folds = Array.from({length:33},(_,j) => {
        const t = j/32;
        return [(.5-t)*1.18,.174*Math.sin(t*Math.PI*10)*(Math.sin(Math.PI*t)**.48)+.040*Math.cos(t*6.28),.163+.064*Math.sin(Math.PI*t)];
      });
      tube(bean,makePath(folds),.041,mitoFolds,7,85,8);
    });

    parts[8].anchors.forEach((p,i) => {
      const r = [.275,.226,.244][i];
      put(groups[8],bodyGeometry(r,r*.94,r*.98,.069,i),material(0xeabb5b,{emissive:0x986335,emissiveIntensity:.13}),p,8);
      const grains = Array.from({length:34},() => {
        const [x,y,z] = sphereSample();
        return [p[0]+x*r*1.005,p[1]+y*r*.95,p[2]+z*r*.99];
      });
      points(groups[8],grains,0xffe6a4,.029,.70);
    });

    const vesicleSkin = material(0x6bdfc9,{transparent:true,opacity:.62,depthWrite:false,roughness:.24});
    const vesicleCore = material(0x419a91,{emissive:0x266f71,emissiveIntensity:.32});
    parts[9].anchors.forEach((p,i) => {
      const r = [.16,.117,.133,.112,.103,.166,.106,.128,.10][i];
      put(groups[9],bodyGeometry(r,r*.96,r,.043,i,24),vesicleSkin,p,9).renderOrder = 7;
      put(groups[9],bodyGeometry(r*.55,r*.54,r*.55,.02,i,19),vesicleCore,p,9);
    });

    const centrioleRod = new T.CylinderGeometry(.020,.020,.47,7);
    const centrioleMat = material(0xb0cc67,{roughness:.57});
    const centrioleEdge = material(0xcfe78c);
    for (let barrel = 0; barrel < 2; barrel += 1) {
      const unit = new T.Group();
      unit.position.set(barrel ? .65 : .36,barrel ? -.96 : -1.03,barrel ? -.07 : .033);
      unit.rotation.set(barrel ? .89 : .67,barrel ? .22 : -.21,barrel ? 1.04 : -.43);
      groups[10].add(unit);
      for (let triplet = 0; triplet < 9; triplet += 1) {
        for (let j = 0; j < 3; j += 1) {
          const angle = triplet*Math.PI*2/9 + (j-1)*.132;
          const r = .130 + j*.012;
          put(unit,centrioleRod,centrioleMat,[Math.cos(angle)*r,0,Math.sin(angle)*r],10);
        }
      }
      for (const end of [-.219,.219]) {
        const track = Array.from({length:22},(_,j) => {
          const a = j/22*Math.PI*2;
          return [.149*Math.cos(a),end,.149*Math.sin(a)];
        });
        tube(unit,new T.CatmullRomCurve3(track.map(vec),true),.022,centrioleEdge,10,32,6);
      }
    }

    const fiberMats = [
      material(0x7fc6fa,{transparent:true,opacity:.46,depthWrite:false,roughness:.65}),
      material(0x9691df,{transparent:true,opacity:.46,depthWrite:false,roughness:.65}),
      material(0x67b9c6,{transparent:true,opacity:.37,depthWrite:false,roughness:.65})
    ];
    for (let i = 0; i < 23; i += 1) {
      const a = i * 2.39996;
      const z = .60 * Math.sin(i*4.3);
      const r = Math.sqrt(1-z*z) * (.84+.08*random());
      const end = shellPoint(Math.cos(a)*r,Math.sin(a)*r,z);
      const root = [.50+(random()-.5)*.34,-.90+(random()-.5)*.37,-.26];
      const track = Array.from({length:12},(_,j) => {
        const t = j/11;
        return [
          scalar(root[0],end[0],t)+.28*Math.sin(Math.PI*t)*Math.cos(a*2+t*6),
          scalar(root[1],end[1],t)+.41*Math.sin(Math.PI*t)*Math.sin(a+t*5),
          scalar(root[2],end[2],t)+.70*Math.sin(Math.PI*t)*Math.cos(a+t*3)
        ];
      });
      tube(groups[11],makePath(track),.012+(i%4)*.003,fiberMats[i%3],11,39,5).renderOrder = 2;
    }

    return {
      canvas: renderer.domElement,
      resize(w,h) {
        camera.aspect = w/h;
        camera.updateProjectionMatrix();
        renderer.setSize(w,h,false);
      },
      draw(seconds) {
        const { back, distance } = model.pose;
        camera.position.set(...back.map((v,i) => v*distance + view.target[i]));
        camera.lookAt(...view.target);
        camera.updateMatrixWorld();
        cutPlane.constant = model.cut ? cutAt : 30;
        cutFace.visible = model.cut;
        for (const gel of [cellGel,nucleusGel]) {
          gel.uniforms.cut.value = cutPlane.constant;
          gel.uniforms.time.value = reduceMotion ? 0 : seconds;
        }
        for (let i = 1; i <= last; i += 1) {
          const group = groups[i];
          const move = model.motion[i];
          group.visible = model.reveal[i] > .008;
          group.position.set(...move.offset);
          group.scale.setScalar(move.scale);
        }
        renderer.render(scene,camera);
      },
      pick(x,y) {
        ray.setFromCamera(new T.Vector2(2*x/width-1,1-2*y/height),camera);
        const hits = ray.intersectObjects(targets.filter(mesh => mesh.userData.part <= model.step),false)
          .filter(hit => !model.cut || hit.point.z <= cutAt);
        let hit = hits[0];
        if (hit && hit.object.userData.part === 1) {
          const inside = hits.find(candidate => candidate.object.userData.part === 2);
          if (inside) hit = inside;
        }
        if (hit) return { id: hit.object.userData.part, point: hit.point.toArray() };
        const close = nearbyPart(x,y);
        if (close) return close;
        const boundary = ray.intersectObject(shell,false).find(item => !model.cut || item.point.z <= cutAt);
        if (boundary || (model.cut && ray.intersectObjects(cutFace.children,false).length)) {
          return { id: 0, point: boundary ? boundary.point.toArray() : null };
        }
        return null;
      }
    };
  }

  const flatModel = makeCanvasModel();
  function attach(next) {
    if (graphics && graphics.canvas.parentNode === surface) graphics.canvas.remove();
    graphics = next;
    surface.append(graphics.canvas);
    resizeNeeded = true;
  }

  attach(flatModel);
  if ("ResizeObserver" in window) {
    new ResizeObserver(() => { resizeNeeded = true; }).observe(surface);
  } else {
    window.addEventListener("resize", () => { resizeNeeded = true; });
  }

  import("https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js").then(three => {
    const graphics3D = makeThreeModel(three);
    graphics3D.canvas.addEventListener("webglcontextlost", event => {
      event.preventDefault();
      if (graphics === graphics3D) attach(flatModel);
    });
    attach(graphics3D);
  }).catch(() => {
    // The interactive canvas view is already active.
  });

  let previous = start;
  function frame(now) {
    if (resizeNeeded) {
      width = Math.max(1,surface.clientWidth);
      height = Math.max(1,surface.clientHeight);
      leader.setAttribute("viewBox","0 0 " + width + " " + height);
      graphics.resize(width,height);
      resizeNeeded = false;
    }
    const dt = clamp((now-previous)/1000,0,.07);
    previous = now;
    const seconds = (now-start)/1000;
    if (model.demo) runDemo(now);
    else if (model.playing && now >= model.next && model.step < last) {
      model.next = now + pace;
      if (model.step + 1 === last) model.playing = false;
      selectBuildStep(model.step + 1);
    }
    const transition = reduceMotion && !model.demo ? 1 : 1-Math.exp(-dt*6.5);
    view.yaw = scalar(view.yaw,goal.yaw,transition);
    view.pitch = scalar(view.pitch,goal.pitch,transition);
    view.zoom = scalar(view.zoom,goal.zoom,transition);
    view.target = view.target.map((v,i) => scalar(v,goal.target[i],transition));
    const c = Math.cos(view.yaw), s = Math.sin(view.yaw);
    const p = Math.cos(view.pitch), q = Math.sin(view.pitch);
    model.pose = {
      back: [s*p,q,c*p], right: [c,0,-s], up: [-s*q,p,-c*q],
      distance: Math.max(11.65,4.18/(tangent*width/height)) * view.zoom
    };

    for (let i = 1; i <= last; i += 1) {
      model.reveal[i] = i <= model.step ? scalar(model.reveal[i],1,reduceMotion ? 1 : 1-Math.exp(-dt*6)) : 0;
      const t = seconds * (.62 + (i % 4)*.14) + i*1.08;
      const amount = reduceMotion ? 0 : 1;
      model.motion[i] = {
        scale: .37+.63*(1-Math.pow(1-model.reveal[i],2))+.015*amount*Math.sin(t),
        offset: [.050*amount*Math.sin(t),.047*amount*Math.cos(t*.83),.041*amount*Math.sin(t*.69)]
      };
    }
    graphics.draw(seconds);
    positionPin();
    requestAnimationFrame(frame);
  }

  sync();
  requestAnimationFrame(frame);
})();
</script>
</body>
</html>