Back to the app
The code
Build a Cell, Part by Part by GPT-6.2 Astra
Exactly as the AI wrote it. Shown as text, so nothing runs on this page.
index.html
works · auto-checked (Checked by an automated pass. Not hand-played yet.)<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<meta name="theme-color" content="#151419">
<title>Animal cell · Cell Atlas</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='9' fill='%23f8cc65'/%3E%3Cg transform='rotate(-22 16 16)' fill='none' stroke='%2329222a' stroke-width='2'%3E%3Cellipse cx='16' cy='16' rx='12' ry='8'/%3E%3Cellipse cx='14' cy='16' rx='5' ry='3.5'/%3E%3C/g%3E%3C/svg%3E">
<style>
:root{color-scheme:dark;--bg:#151419;--panel:#201e25;--line:#38343d;--ink:#f5f1e7;--muted:#b5aebd;--gold:#f8cc65;--paper:#f0e9d9;--black:#29252a;--accent:#b69aee;--sans:"Inter","Segoe UI",Arial,sans-serif;--display:"Bricolage Grotesque","Inter","Segoe UI",Arial,sans-serif;--mono:"IBM Plex Mono","Cascadia Mono",Consolas,monospace}
*{box-sizing:border-box}
body{margin:0;background:var(--bg);color:var(--ink);font-family:var(--sans);-webkit-font-smoothing:antialiased}
button,input{font:inherit}
button{color:inherit;cursor:pointer;-webkit-tap-highlight-color:transparent;touch-action:manipulation}
button:disabled{cursor:default}
button:focus-visible,input:focus-visible,canvas:focus-visible,dialog:focus-visible{outline:3px solid #efaf35;outline-offset:3px}
button{transition:background .16s,border-color .16s,transform .16s}
button:active:not(:disabled){transform:translateY(1px)}
button svg,.icon{width:19px;height:19px;display:block;fill:none;stroke:currentColor;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round;flex-shrink:0}
.wrap{width:calc(100% - clamp(40px,7.8vw,128px));max-width:1490px;margin-inline:auto}
.mast{border-bottom:1px solid #322f36;background:#18171c}
.mast .wrap{height:66px;display:flex;align-items:center;justify-content:space-between}
.wordmark{display:flex;align-items:center;gap:11px;font-family:var(--display);font-size:23px;font-weight:730;letter-spacing:-1.2px}
.logo{width:35px;height:35px;display:grid;place-items:center;background:var(--gold);color:#29222a;border-radius:11px 10px 11px 9px;transform:rotate(-4deg)}
.logo svg{width:28px;height:28px}
.ghost,.guidebutton,.cut,.partnav,.zoombar,.play{display:inline-flex;align-items:center;justify-content:center}
.guidebutton,.ghost{min-height:42px;gap:9px;font-size:13px;font-weight:600;line-height:1;border:1px solid #45404b;background:transparent;border-radius:10px;padding:0 15px}
.guidebutton svg{color:var(--gold);width:17px}
.guidebutton{background:#211f26}
.ghost{background:#242128}
.ghost:hover,.guidebutton:hover,.zoombar button:hover{background:#302c35;border-color:#625969}
main{padding:clamp(23px,3.5vh,43px) 0 28px}
.intro{display:flex;align-items:center;justify-content:space-between;gap:18px;margin-bottom:clamp(17px,2.5vh,28px)}
h1,h2,h3,p{margin:0}
h1{font:650 clamp(40px,4vw,64px)/1 var(--display);letter-spacing:-.065em}
.intro p{font-size:clamp(14px,1.05vw,17px);line-height:1.5;color:#beb7c2;margin-top:9px}
.workbench{display:grid;grid-template-columns:minmax(0,1fr) clamp(280px,24.5%,358px);grid-template-areas:"stage note" "time time";gap:clamp(13px,1.2vw,21px)}
.stage{grid-area:stage;height:clamp(397px,56vh,615px);border-radius:18px;border:1px solid #49404f;position:relative;overflow:hidden;isolation:isolate;background:radial-gradient(ellipse 31% 4.5% at 50% 87%,#100d195c,transparent 100%),radial-gradient(ellipse at 49% 47%,#373042 0%,#282330 41%,#201c28 70%,#1e1b24 100%)}
.stage::before{content:"";position:absolute;inset:0;pointer-events:none;background-image:radial-gradient(circle,#a698be32 .8px,transparent 1px);background-size:18px 18px;mask-image:radial-gradient(ellipse at 50% 46%,#0006,black 85%)}
.stage::after{content:"";position:absolute;inset:0;pointer-events:none;border-radius:inherit;box-shadow:inset 0 0 55px #120f192d;z-index:1}
.instruments{position:absolute;inset:0;pointer-events:none;overflow:hidden}
.instruments i{position:absolute;width:11px;height:11px;opacity:.4}
.instruments i::before,.instruments i::after{content:"";background:#a49aad;position:absolute;left:5px;top:0;width:1px;height:11px}
.instruments i::after{transform:rotate(90deg)}
.instruments i:nth-child(1){top:26%;left:6%}.instruments i:nth-child(2){top:74%;right:6%}.instruments i:nth-child(3){top:23%;right:13%}.instruments i:nth-child(4){top:76%;left:14%}
#model{width:100%;height:100%;display:block;position:absolute;inset:0;touch-action:none;cursor:grab;outline-offset:-4px}
#model.dragging{cursor:grabbing}
.toptools,.bottomtools{position:absolute;left:16px;right:16px;z-index:4;display:flex;justify-content:space-between;align-items:center;pointer-events:none;gap:8px}
.toptools{top:14px}.bottomtools{bottom:13px;align-items:flex-end}
.toptools button,.bottomtools button,.zoombar{pointer-events:auto}
.live{display:flex;gap:8px;align-items:center;font-family:var(--mono);font-size:10px;font-weight:600;letter-spacing:.08em;text-transform:uppercase;color:#e0dbe2;border:1px solid #74667855;background:#26212dcc;border-radius:7px;padding:8px 10px}
.live i{width:6px;height:6px;border-radius:50%;background:#a9dbb1;box-shadow:0 0 8px #9fe1aa60}
.live[data-state="paused"] i{background:var(--gold);box-shadow:none}
.cut{min-height:40px;gap:10px;padding:0 11px 0 13px;border-radius:9px;background:#28232eea;border:1px solid #554b5b;font-size:12px;font-weight:600}
.switch{width:28px;height:16px;border-radius:99px;background:#5b5363;display:inline-flex;align-items:center;padding:3px;transition:background .2s}
.switch i{height:10px;width:10px;border-radius:50%;background:#f0eaf1;transition:transform .2s}
.cut[aria-checked="true"]{border-color:#a38758}
.cut[aria-checked="true"] .switch{background:var(--gold)}
.cut[aria-checked="true"] .switch i{transform:translateX(12px);background:#322a2b}
.hints{display:flex;align-items:center;gap:8px;font:11px/1.2 var(--sans);color:#c2b9ca;padding:7px 2px;text-shadow:0 1px 3px #17151a}
.hints svg{width:17px;height:17px;color:#c5b9d1}
.hints b{font-weight:400;color:#7f7388}
.touchword{display:none}
.zoombar{background:#28232eea;border:1px solid #554b5b;border-radius:9px;overflow:hidden}
.zoombar button{width:38px;height:37px;background:transparent;color:#e6dfeb;border:0;display:grid;place-items:center}
.zoombar svg{width:16px;height:16px}
.zoombar button:last-child{border-left:1px solid #49404f}
#leaders{pointer-events:none;position:absolute;inset:0;width:100%;height:100%;z-index:2;overflow:visible}
#leaders path{stroke:#e1d8e3;stroke-opacity:.76;stroke-width:1;fill:none}
#pinHalo{fill:#211a29;stroke:var(--accent);stroke-width:1.3}
#pinDot{fill:var(--accent)}
.callout{pointer-events:none;position:absolute;top:0;left:0;z-index:3;display:flex;align-items:center;gap:8px;border:1px solid #796c82;border-radius:7px;background:#27222eef;box-shadow:0 3px 12px #17121d33;padding:7px 11px;color:#f7f0f3;font:600 12px/1.1 var(--sans);white-space:nowrap;visibility:hidden}
.callout i,.role i{background:var(--accent);width:7px;height:7px;border-radius:50%;flex:none}
.note{grid-area:note;position:relative;overflow:hidden;border:1px solid #faf4e3;border-radius:17px;background:var(--paper);color:var(--black);display:flex;flex-direction:column;min-width:0}
.notehead,.guidehead{display:flex;justify-content:space-between;align-items:center}
.notehead{margin:0 20px;padding:16px 0 13px;border-bottom:1px solid #bbb09d77}
.notelabel,.noteindex,.role,.timecount,.guideindex{font-family:var(--mono)}
.notelabel{display:flex;align-items:center;gap:8px;text-transform:uppercase;font-size:11px;font-weight:700;letter-spacing:.095em}
.notelabel svg{width:16px;height:16px}
.noteindex{color:#71685f;font-size:11px;letter-spacing:.05em}
.plate{position:relative;margin:12px 14px 4px;min-height:105px;max-height:245px;flex:1 1 170px;border-radius:7px;background-image:linear-gradient(#b3a99028 1px,transparent 1px),linear-gradient(90deg,#b3a99028 1px,transparent 1px);background-size:14px 14px;background-position:center}
.plate::before,.plate::after{content:"";position:absolute;pointer-events:none;width:7px;height:7px;border:solid #a1967f8a}
.plate::before{top:5px;left:5px;border-width:1px 0 0 1px}.plate::after{bottom:5px;right:5px;border-width:0 1px 1px 0}
#plate{position:absolute;width:100%;height:100%;inset:0}
.notebody{padding:14px 22px 16px;flex:0 1 auto}
.role{font-size:10px;line-height:1.4;letter-spacing:.09em;font-weight:700;text-transform:uppercase;display:flex;gap:7px;align-items:center;color:#695f56}
.role i{outline:1px solid #3d304446;outline-offset:-1px}
.notebody h2{font:680 clamp(26px,2.25vw,37px)/1.04 var(--display);letter-spacing:-.05em;margin:7px 0 9px;overflow-wrap:break-word}
.notebody h2.long{font-size:clamp(24px,1.92vw,30px)}
.notebody p{font-size:clamp(14px,1.06vw,16px);line-height:1.5;color:#514a47}
.notefoot{margin:0 20px;padding:13px 0 16px;display:flex;gap:8px;border-top:1px solid #bbb09d8c}
.partnav{border:1px solid #b9ae9d;border-radius:8px;background:transparent;color:#332c2c;min-width:42px;min-height:41px}
.partnav:disabled{opacity:.4}
.partnav.next{gap:11px;flex:1;justify-content:space-between;padding:0 14px;border-color:#322c30;background:#322c30;color:#fff9ea;font-size:13px;font-weight:650}
.partnav.next:hover{background:#453c42}
.partnav svg{width:16px;height:16px}
.timeline{grid-area:time;display:flex;align-items:center;gap:clamp(14px,2vw,30px);background:#211f26;border:1px solid #3d3742;border-radius:15px;padding:16px 23px}
.timeintro{display:flex;align-items:center;gap:14px;flex:none;padding-right:clamp(13px,2.2vw,35px);border-right:1px solid #48404d}
.play{border:0;width:45px;height:45px;border-radius:50%;background:var(--gold);color:#2b2429;box-shadow:inset 0 0 0 1px #ffe9ab66}
.play:hover{background:#ffda83}
.play svg{width:18px;height:18px;fill:currentColor;stroke-width:0}
.timeintro h2{font-size:15px;line-height:1.3;font-weight:650;letter-spacing:-.025em}
.timecount{font-size:11px;color:#bdb4c6;margin-top:4px;letter-spacing:.01em}
.scrubber{flex:1;min-width:0;--progress:0%}
.railbox{position:relative;height:28px}
.rail{position:absolute;left:8px;right:8px;top:13px;height:3px;background:#4f4754;border-radius:4px}
.rail .fill{width:var(--progress);height:100%;background:var(--gold);border-radius:4px}
.ticks{position:absolute;left:0;right:0;inset-block:0}
.ticks i{position:absolute;top:50%;width:7px;height:7px;border-radius:50%;background:#6a6171;transform:translate(-50%,-50%);box-shadow:0 0 0 2px #211f26}
.ticks i.on{background:var(--gold);box-shadow:0 0 0 1px #211f26}
.thumb{position:absolute;top:50%;left:var(--progress);width:16px;height:16px;background:var(--gold);border:3px solid #f8cf73;box-shadow:0 0 0 3px #3d3330;border-radius:50%;transform:translate(-50%,-50%)}
#buildRange{width:100%;height:40px;position:absolute;inset:-5px 0 auto;margin:0;opacity:0;cursor:pointer;touch-action:pan-y}
.railbox:focus-within .thumb{outline:2px solid var(--ink);outline-offset:4px}
.ends{display:flex;justify-content:space-between;color:#b6aebd;font:10px/1.4 var(--mono);padding:0 2px}
dialog{width:min(660px,calc(100% - 28px));max-height:86vh;border:1px solid #e5d9c5;border-radius:18px;padding:0;background:var(--paper);color:var(--black);box-shadow:0 20px 90px #0c0914aa}
dialog::backdrop{background:#100e17bb;backdrop-filter:blur(5px)}
.guidehead{padding:21px 24px 12px;gap:15px}
.guidehead h2{font:680 31px/1.1 var(--display);letter-spacing:-.05em}
.guidehead p{font-size:14px;color:#63594f;margin-top:6px}
.closeguide{background:transparent;border:1px solid #c1b6a6;width:42px;height:42px;border-radius:50%;display:grid;place-items:center;flex:none}
.guidegrid{display:grid;grid-template-columns:1fr 1fr;gap:7px;padding:8px 24px 24px}
.guideentry{display:flex;align-items:center;gap:10px;position:relative;min-width:0;background:#f8f2e5;border:1px solid #ccc2b2;border-radius:10px;color:var(--black);text-align:left;padding:7px 10px}
.guideentry:hover,.guideentry[aria-current="true"]{background:#fffaee;border-color:#8e7d66}
.guideentry canvas{width:51px;height:42px;flex:none}
.guideentry span{font-size:13px;line-height:1.25;font-weight:630}
@media(min-width:1600px){.mast .wrap{height:74px}.toptools{top:18px}.bottomtools{bottom:17px}.notehead{padding-top:20px}.timeline{padding:20px 25px}}
@media(max-height:740px) and (min-width:761px){.mast .wrap{height:56px}main{padding-top:18px}.intro{margin-bottom:16px}h1{font-size:44px}.stage{height:clamp(350px,55vh,430px)}.plate{min-height:78px}.notehead{padding-block:12px}.notefoot{padding-block:10px}.notebody{padding-block:9px 12px}.timeline{padding-block:12px}}
@media(pointer:coarse){.mouseword{display:none}.touchword{display:inline}.cut,.ghost,.guidebutton,.partnav{min-height:44px}.zoombar button{width:42px;height:42px}}
@media(max-width:900px) and (min-width:761px){.wrap{width:calc(100% - 36px)}.workbench{grid-template-columns:minmax(0,1fr) 263px;gap:12px}.zoomtext,.hints b{display:none}.notehead,.notefoot{margin-inline:16px}.notebody{padding-inline:17px}}
@media(max-width:760px){
.wrap{width:calc(100% - 32px)}.mast .wrap{height:57px}.wordmark{font-size:21px}.logo{width:32px;height:32px;border-radius:9px}.guidebutton{padding-inline:11px}.ghost,.guidebutton{min-height:42px}main{padding-top:22px}.intro{align-items:flex-start;gap:10px;margin-bottom:16px}h1{font-size:43px}.intro p{font-size:13px;line-height:1.42;margin-top:7px;max-width:280px}.ghost{margin-top:2px;padding-inline:12px}.workbench{grid-template-columns:1fr;grid-template-areas:"stage" "time" "note";gap:12px}.stage{height:clamp(312px,78vw,433px);border-radius:14px}.toptools,.bottomtools{left:10px;right:10px}.toptools{top:9px}.bottomtools{bottom:9px}.hints{gap:5px;font-size:10px}.cut{gap:7px;min-height:40px}.timeline{padding:10px 13px;gap:12px;border-radius:12px}.timeintro{padding-right:12px;gap:8px}.timeintro h2{font-size:12px}.timecount{font-size:10px}.play{width:42px;height:42px}.railbox{height:25px}.ticks i{width:5px;height:5px}.ends{font-size:9px}.note{display:grid;grid-template-columns:34% minmax(0,1fr);grid-template-rows:auto auto auto;border-radius:14px}.notehead{grid-column:1/-1;margin:0 15px;padding:12px 0 10px}.plate{grid-column:1;grid-row:2/4;margin:12px;max-height:none;min-height:125px}.notebody{grid-column:2;padding:16px 14px 12px 4px}.notebody h2{font-size:26px}.notebody h2.long{font-size:23px}.notebody p{font-size:14px;line-height:1.45}.notefoot{grid-column:2;margin:0 14px 0 4px;padding:9px 0 13px}.partnav{min-height:40px}.callout{font-size:11px;padding:6px 8px}
}
@media(max-width:420px){.wrap{width:calc(100% - 22px)}.hints .zoomtext,.hints b{display:none}.guidebutton,.ghost{font-size:12px}.timeintro{padding-right:9px}.timeline{gap:9px;padding-inline:10px}.guidegrid{grid-template-columns:1fr;padding-inline:16px}.guidehead{padding-inline:16px}.guideentry canvas{width:47px;height:36px}}
@media(pointer:coarse){.cut,.ghost,.guidebutton,.partnav,.closeguide{min-height:44px}.zoombar button,.play,.partnav:not(.next){min-width:44px;height:44px}}
@media(prefers-reduced-motion:reduce){*,*::before,*::after{transition-duration:.01s!important}}
</style>
</head>
<body>
<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" style="position:absolute;width:0;height:0;overflow:hidden"><defs>
<symbol id="i-book" viewBox="0 0 24 24"><path d="M12 6.2C9 4.3 5.7 4.2 2.7 5.3v13.6c3.3-1.2 6.3-.9 9.3 1 3-1.9 6-2.2 9.3-1V5.3c-3-1.1-6.3-1-9.3.9Zm0 0v13.4"/></symbol>
<symbol id="i-note" viewBox="0 0 24 24"><path d="M6 3.5h12.5a1.5 1.5 0 0 1 1.5 1.5v15H6a2 2 0 0 1-2-2V5.5a2 2 0 0 1 2-2Zm2-.1V20m3.5-11h5M11.5 12h3"/></symbol>
<symbol id="i-rebuild" viewBox="0 0 24 24"><path d="M3.7 10a8.4 8.4 0 1 1 .6 6.1M3.5 4.8v5.7h5.7"/></symbol>
<symbol id="i-arrow" viewBox="0 0 24 24"><path d="M4 12h15m-6-6 6 6-6 6"/></symbol>
<symbol id="i-left" viewBox="0 0 24 24"><path d="m14.5 6-6 6 6 6"/></symbol>
<symbol id="i-minus" viewBox="0 0 24 24"><path d="M5 12h14"/></symbol>
<symbol id="i-plus" viewBox="0 0 24 24"><path d="M5 12h14m-7-7v14"/></symbol>
<symbol id="i-fit" viewBox="0 0 24 24"><path d="M8.6 4H4v4.6M15.4 4H20v4.6M20 15.4V20h-4.6M8.6 20H4v-4.6"/></symbol>
<symbol id="i-orbit" viewBox="0 0 24 24"><ellipse cx="12" cy="12" rx="11" ry="4.8" transform="rotate(-28 12 12)"/><circle cx="12" cy="12" r="2.4"/></symbol>
<symbol id="i-play" viewBox="0 0 24 24"><path d="M6.5 3.8q0-1.2 1-.6l14 8.2q1 .6 0 1.2l-14 8.2q-1 .6-1-.6z"/></symbol>
<symbol id="i-pause" viewBox="0 0 24 24"><rect x="5" y="4" width="5" height="16" rx="1.2"/><rect x="14" y="4" width="5" height="16" rx="1.2"/></symbol>
<symbol id="i-close" viewBox="0 0 24 24"><path d="m6 6 12 12M18 6 6 18"/></symbol>
</defs></svg>
<header class="mast"><div class="wrap">
<div class="wordmark"><span class="logo" aria-hidden="true"><svg viewBox="0 0 32 32" fill="none"><g transform="rotate(-26 16 16)" stroke="currentColor" stroke-width="1.8"><path d="M28 15.4c.6 5.7-6.2 9.9-13.4 9.1C8.2 24 3.5 20.2 4 15c.6-5.7 6.8-9 12.7-8.2C23.3 7.7 27.4 10.3 28 15.4Z"/><ellipse cx="14.2" cy="15.2" rx="5.2" ry="4.1"/><circle cx="14.4" cy="15.1" r="1.3" fill="currentColor" stroke="none"/><path d="M21.3 12.5q3 .7 3.5 2.8"/></g></svg></span>Cell Atlas</div>
<button id="guideButton" class="guidebutton" type="button"><svg aria-hidden="true"><use href="#i-book"/></svg>Field guide</button>
</div></header>
<main class="wrap">
<div class="intro"><div><h1>Animal cell</h1><p>Watch the cell assemble, then tap a part to explore.</p></div><button id="rebuild" class="ghost" type="button"><svg aria-hidden="true"><use href="#i-rebuild"/></svg>Rebuild</button></div>
<div class="workbench">
<section class="stage" id="stage" aria-label="Interactive animal cell model">
<div class="instruments" aria-hidden="true"><i></i><i></i><i></i><i></i></div>
<canvas id="model" tabindex="0" aria-label="3D animal cell. Drag to rotate, scroll or pinch to zoom, and select a part. The field guide also lets you select any part."></canvas>
<svg id="leaders" aria-hidden="true"><path id="leader"/><circle id="pinHalo" r="3.8"/><circle id="pinDot" r="1.55"/></svg>
<div id="callout" class="callout" aria-hidden="true"><i></i><span>Cell membrane</span></div>
<div class="toptools"><span class="live" id="live"><i></i><span>Assembling</span></span><button id="cut" class="cut" type="button" role="switch" aria-label="Cut open" aria-checked="false">Cut open<span class="switch" aria-hidden="true"><i></i></span></button></div>
<div class="bottomtools"><div class="hints"><svg class="icon" aria-hidden="true"><use href="#i-orbit"/></svg><span>Drag to orbit</span><b>·</b><span class="zoomtext"><span class="mouseword">Scroll</span><span class="touchword">Pinch</span> to zoom</span></div><div class="zoombar" role="group" aria-label="View controls"><button id="minus" aria-label="Zoom out" title="Zoom out"><svg><use href="#i-minus"/></svg></button><button id="plus" aria-label="Zoom in" title="Zoom in"><svg><use href="#i-plus"/></svg></button><button id="fit" aria-label="Fit whole cell" title="Fit whole cell"><svg><use href="#i-fit"/></svg></button></div></div>
</section>
<aside class="note" aria-label="Selected cell part">
<div class="notehead"><span class="notelabel"><svg class="icon" aria-hidden="true"><use href="#i-note"/></svg>Field note</span><span id="noteindex" class="noteindex">00 / 11</span></div>
<div class="plate"><canvas id="plate" aria-hidden="true"></canvas></div>
<div class="notebody" aria-live="polite" aria-atomic="true"><span class="role"><i></i><span id="role">Boundary</span></span><h2 id="partTitle">Cell membrane</h2><p id="fact">This thin, flexible skin controls what enters and leaves the cell.</p></div>
<div class="notefoot"><button type="button" class="partnav" id="previous" aria-label="Previous part" disabled><svg aria-hidden="true"><use href="#i-left"/></svg></button><button type="button" class="partnav next" id="next"><span>Next part</span><svg aria-hidden="true"><use href="#i-arrow"/></svg></button></div>
</aside>
<section class="timeline" aria-label="Cell build controls">
<div class="timeintro"><button type="button" class="play" id="play" aria-label="Pause build" title="Pause build"><svg aria-hidden="true"><use href="#i-pause"/></svg></button><div><h2>Build timeline</h2><p class="timecount" id="timecount">0 of 11 parts</p></div></div>
<div class="scrubber" id="scrubber"><div class="railbox"><div class="rail" aria-hidden="true"><div class="fill"></div><div class="ticks" id="ticks"></div><div class="thumb"></div></div><input id="buildRange" aria-label="Build stage" type="range" min="0" max="11" value="0" step="1"></div><div class="ends" aria-hidden="true"><span>Empty cell</span><span>Complete cell</span></div></div>
</section>
</div></main>
<dialog id="guide" aria-labelledby="guideTitle"><div class="guidehead"><div><h2 id="guideTitle">Field guide</h2><p>Choose a part to see it inside the cell.</p></div><button class="closeguide" id="closeGuide" aria-label="Close field guide"><svg aria-hidden="true"><use href="#i-close"/></svg></button></div><div class="guidegrid" id="guideGrid"></div></dialog>
<script>
"use strict";
const $=id=>document.getElementById(id);
const TAU=Math.PI*2, PI=Math.PI;
const clamp=(x,lo,hi)=>Math.min(hi,Math.max(lo,x));
const mix=(a,b,t)=>a+(b-a)*t;
const smooth=t=>{t=clamp(t,0,1);return t*t*(3-2*t)};
const parts=[
["Cell membrane","Cell membrane","Boundary","#bdabed","This thin, flexible skin controls what enters and leaves the cell."],
["Nucleus","Nucleus","Instructions","#b695ed","The nucleus holds the cell’s DNA, the instructions it needs to work and grow."],
["Nucleolus","Nucleolus","Assembly","#e287b9","The nucleolus makes the pieces that fit together to form ribosomes."],
["Rough endoplasmic reticulum","Rough ER","Protein workshop","#899de6","Ribosomes on these folded sheets make proteins that the cell can send to other places."],
["Smooth endoplasmic reticulum","Smooth ER","Fat production","#79cdb0","These smooth tubes make fats and help the cell break down harmful chemicals."],
["Ribosomes","Ribosomes","Protein builders","#f2cf7f","Ribosomes read instructions and link small building blocks together to make proteins."],
["Golgi apparatus","Golgi apparatus","Sorting & packing","#e99494","The Golgi apparatus sorts and packages proteins so they reach the right place."],
["Mitochondria","Mitochondria","Energy supply","#ffab68","Mitochondria turn energy from food into a form the cell can use."],
["Lysosomes","Lysosomes","Recycling","#b0cf7c","Lysosomes break down worn-out cell parts so their materials can be used again."],
["Vesicles","Vesicles","Transport","#85d8dc","Vesicles are tiny bubbles that carry supplies from one place to another."],
["Centrioles","Centrioles","Cell division","#f3c465","Centrioles help organize the fibers that pull chromosomes apart when a cell divides."],
["Cytoskeleton","Cytoskeleton","Shape & movement","#83c5bd","This web of fibers supports the cell and gives supplies tracks to travel along."]
];
function random(seed){return ()=>{seed=(Math.imul(seed,1664525)+1013904223)>>>0;return seed/4294967296}}
function rgb(hex){return [1,3,5].map(i=>parseInt(hex.slice(i,i+2),16)/255)}
function tone(a,s,b=0){return a.map(x=>clamp(x*s+b,0,1))}
const add=(a,b)=>a.map((v,i)=>v+b[i]),sub=(a,b)=>a.map((v,i)=>v-b[i]),mul=(a,n)=>a.map(v=>v*n);
const dot=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2];
const cross=(a,b)=>[a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0]];
const unit=a=>mul(a,1/(Math.hypot(...a)||1));
const lerp3=(a,b,t)=>a.map((v,i)=>mix(v,b[i],t));
function frame(axis){const t=unit(axis),n=unit(cross(Math.abs(t[2])>.85?[0,1,0]:[0,0,1],t));return [n,cross(t,n),t]}
function basisAt(c,axes,x,y,z){return c.map((v,i)=>v+x*axes[0][i]+y*axes[1][i]+z*axes[2][i])}
function curve(n,fn){return Array.from({length:n+1},(_,i)=>fn(i/n))}
// The field notes are drawn as small, inked anatomical plates.
function drawArt(c,id){
const ink="#493e46", tint=parts[id][3], rng=random(2893+id*193);
const path=(d,fill,stroke=ink,w=1.35)=>{const p=typeof d==="string"?new Path2D(d):d;if(fill){c.fillStyle=fill;c.fill(p)}if(stroke){c.strokeStyle=stroke;c.lineWidth=w;c.stroke(p)}};
function ellipse(x,y,rx,ry,angle,fill,stroke=null,w=1){c.beginPath();c.ellipse(x,y,rx,ry,angle,0,TAU);if(fill){c.fillStyle=fill;c.fill()}if(stroke){c.strokeStyle=stroke;c.lineWidth=w;c.stroke()}}
function grad(x,y,r,light,mid,dark){const g=c.createRadialGradient(x-r*.32,y-r*.42,r*.025,x,y,r*1.14);g.addColorStop(0,light);g.addColorStop(.61,mid);g.addColorStop(1,dark);return g}
function stripe(d,col,w){path(d,null,col,w)}
function stipple(shape,amt=140,alpha=.26){
c.save();c.clip(shape instanceof Path2D?shape:new Path2D(shape));
for(let i=0;i<amt;i++){const x=rng()*160-80,y=rng()*104-52;c.globalAlpha=alpha*(.3+rng()*.7);ellipse(x,y,.35+rng()*.75,.32+rng()*.54,-.4,ink)}
c.restore()
}
function ball(x,y,r,kind){
const scheme=kind===8?["#f1eaa5","#b9ce75","#71956f"]:kind===9?["#ddf3de","#a1dcd2","#68a1ad"]:kind===2?["#f0b4d4","#ca74a4","#905783"]:["#e6d8f7","#b89bd7","#83709f"];
ellipse(x,y,r,r*.93,-.28,grad(x,y,r,...scheme),ink,1.45);
c.save();c.translate(x,y);c.scale(1,.93);
c.beginPath();c.arc(0,0,r-1,0,TAU);c.clip();
for(let i=0;i<r*2;i++){
const a=rng()*TAU,l=Math.sqrt(rng())*r,X=Math.cos(a)*l,Y=Math.sin(a)*l;
if(kind===8&&i%4===0){ellipse(X,Y,1.3+rng()*2,.9+rng(),a,"#839656","#697d50",.6)}
else if(kind===2&&i%3===0){stripe("M"+X+" "+Y+"q3 -4 6 -1t6 0","#a45d91",.8)}
else{c.globalAlpha=.17+.18*rng();ellipse(X,Y,.55+rng(),.38+rng()*.5,a,ink);c.globalAlpha=1}
}
for(let k=0;k<4;k++){c.beginPath();c.ellipse(0,0,r-3-k*1.8,r-3-k*2.2,0,.08+k*.1,1.65-k*.09);c.strokeStyle="#503e5639";c.lineWidth=.65;c.stroke()}
c.beginPath();c.arc(0,0,r*.84,3.74,4.76);c.strokeStyle="#fff9ebaa";c.lineWidth=2.2;c.stroke();c.restore()
}
c.save();c.lineJoin="round";c.lineCap="round";
if(id===0){
c.rotate(-.16);
const shell="M-71 -1C-75 -22 -53 -40 -25 -43C5 -49 20 -39 40 -36C61 -33 76 -20 74 1C71 23 51 36 25 39C3 42 -4 48 -28 44C-53 40 -68 25 -71 -1Z";
path(shell,grad(-12,-7,77,"#eee5fa","#c8bcda","#9486a9"),ink,1.85);
c.save();c.scale(.952,.917);path(shell,null,"#71667f",1);c.restore();
c.save();c.scale(.915,.855);path(shell,null,"#93819e",1.3);c.restore();
stipple(shell,620,.30);
stripe("M-61 -3C-64 -22 -43 -33 -24 -34S1 -33 13 -34","#f7ecf9",2.1);
stripe("M-49 24Q-26 43 1 34T48 23","#8d829c",.9);
for(let k=0;k<9;k++){const x=14+k*5;stripe("M"+x+" "+(36-.15*k*k)+"l2 -4","#766a81",.65)}
for(let k=0;k<17;k++){let x=rng()*113-57,y=(rng()-.5)*49;ellipse(x,y,1.8+rng()*1.4,.8+rng()*.5,-.62,"#ccbdd7","#8f7e9f",.65)}
}else if(id===1){
c.rotate(-.16);
const shell="M-48 1C-50 -25 -32 -43 -6 -45C24 -49 49 -29 50 -3C53 22 35 43 9 46C-20 49 -44 29 -48 1Z";
path(shell,grad(-4,-6,55,"#e1d3f3","#b89bd8","#8f79aa"),ink,1.7);
c.save();c.scale(.932,.916);path(shell,null,"#7e6996",1);c.restore();stipple(shell,490,.37);
for(const a of [[-31,-19,4,2,-.8],[-5,-33,4.8,2.2,-.15],[26,-22,4.5,2.3,.75],[-33,11,3,4.5,-.4],[10,29,4.3,2,.05],[31,15,2.7,4.4,.6]]){
ellipse(...a,"#9e86b9","#584861",1);ellipse(a[0],a[1],a[2]*.55,a[3]*.5,a[4],"#695574")
}
for(let i=0;i<4;i++){c.save();c.rotate(i*1.51);stripe("M-26 -11Q-18 -24 -9 -21T8 -22Q16 -26 19 -18","#827096",1.65);c.restore()}
ball(4,-3,16.5,2);
}else if(id===2){
ball(0,0,42,2);
for(let i=0;i<5;i++){c.save();c.rotate(i*1.28);stripe("M-23 -16Q-19 -25 -12 -21T1 -25","#a36492",1.1);c.restore()}
}else if(id===3||id===6){
c.rotate(id===3?-.19:-.14);
const isR=id===3;
for(let i=0;i<5;i++){
const y=(2-i)*9,span=56+(i===2?8:0)-Math.abs(i-2)*3;
c.save();c.translate((i-2)*1.7,y);c.scale(span/60,1);
const d=isR?"M-62 -7C-50 -17 -36 -1 -17 0C9 1 33 -15 52 -12Q65 -11 61 -5C46 4 13 15 -14 14C-41 12 -48 0 -58 3Q-65 3 -62 -7Z":"M-61 -10Q-59 -17 -52 -11C-31 7 3 10 37 -4Q46 -8 55 -16C61 -20 67 -13 60 -6C42 12 7 23 -26 15C-43 12 -57 2 -61 -10Z";
path(d,isR?["#8794bd","#929dc8","#9da9d4","#a7b5d8","#bcc5e1"][i]:["#b97d81","#cb8a88","#dd9c95","#e8aaa1","#efb9ad"][i],ink,1.3);
stripe(isR?"M-54 -7C-35 -8 -32 7 -10 6S25 -1 48 -7":"M-54 -7C-28 14 12 21 50 -4",isR?"#e0dff2":"#fbe0c4",1.4);
if(isR){for(let j=0;j<13;j++){const x=-51+j*8+rng()*3,Y=-1+4*Math.cos((x+6)/18);ellipse(x,Y,1.6,1.3,-.3,"#625880",ink,.45)}}
c.restore()
}
if(!isR){for(const a of [[66,-30,4.6],[57,-41,3],[-61,14,4.1],[70,-11,3.1]])ellipse(a[0],a[1],a[2],a[2]*.9,-.3,"#e9b4a0",ink,1)}
}else if(id===4){
c.rotate(-.18);
const routes=["M-63 13C-52 12 -51 -9 -35 -6S-15 20 0 14S19 -13 33 -10S55 7 64 -8","M-56 -16C-49 -28 -36 -23 -29 -19S-10 -3 0 -8S18 -34 33 -28S49 -13 62 -23","M-48 34C-33 20 -22 32 -12 34S2 34 10 26S25 10 36 14S47 23 59 12","M-36 -23C-42 -15 -29 -12 -35 -6S-44 7 -36 14S-28 26 -34 29","M-10 -11C-17 -3 -4 1 -9 11S-17 22 -12 34","M17 -22C11 -12 26 -11 19 -2S12 14 20 18","M46 -19C36 -9 51 -5 44 4S39 11 44 16"];
for(const d of routes)stripe(d,ink,7.8);for(const d of routes)stripe(d,"#84bda5",5.6);for(const d of routes)stripe(d,"#d4e4bf",1.35);
}else if(id===5){
function rib(x,y,s){c.save();c.translate(x,y);c.scale(s,s);c.rotate(-.21);
const lower="M-28 5C-19 -5 6 -7 23 1Q34 8 30 16C26 27 10 31 -6 26Q-24 24 -29 15Q-33 9 -28 5Z";
const upper="M-30 2C-36 -8 -27 -20 -15 -21C-10 -37 13 -34 18 -23C30 -23 38 -9 30 0C23 8 16 4 10 5C-6 12 -19 13 -30 2Z";
path(lower,"#c7a164",ink,1.6);path(upper,grad(-6,-9,38,"#f8e5ae","#e6c27f","#c1a16d"),ink,1.65);stipple(upper,300,.4);stripe("M-22 -12Q-17 -18 -10 -16Q-5 -28 4 -26","#fff1c2",1.8);c.restore()}
rib(-38,-21,.43);rib(39,22,.50);rib(-1,0,1.18);
}else if(id===7){
c.rotate(-.27);
const d="M-65 1C-67 -20 -42 -35 -14 -30C4 -28 10 -23 28 -25C51 -29 67 -19 66 0C65 21 38 31 14 27C-4 23 -8 25 -24 28C-46 33 -63 21 -65 1Z";
path(d,grad(-4,-10,69,"#ffdb9b","#edac73","#c98265"),ink,1.7);
c.save();c.scale(.906,.797);path(d,"#d88f66","#805a51",1.2);c.restore();
const folds="M-56 1Q-44 -28 -40 -15C-37 -4 -46 14 -38 16S-25 2 -24 -10S-14 -21 -15 -8S-24 18 -17 18S-3 7 -2 -9S6 -19 6 -9S-1 15 6 15S18 7 19 -8S28 -20 28 -8S20 17 28 15S40 4 41 -6S48 -12 48 -5S44 6 51 3";
stripe(folds,"#815746",5.1);stripe(folds,"#f8c688",3.1);stipple(d,270,.24);
}else if(id===8){ball(0,-1,42,8);for(const [x,y,r] of [[-12,-14,3],[7,6,2],[-7,23,3.3],[19,-12,2.6],[21,13,1.8]])ellipse(x,y,r,r*.69,-.6,"#90a768","#6f8458",.8)
}else if(id===9){ball(-26,-13,23,9);ball(37,-23,12,9);ball(17,12,31,9);
}else if(id===10){
function barrel(x,y,angle,s){c.save();c.translate(x,y);c.rotate(angle);c.scale(s,s);
for(let j=0;j<9;j++){const a=j/9*TAU,X=Math.cos(a)*15,Y=Math.sin(a)*11;const d="M"+(X-24)+" "+(Y-2.7)+"l48 -5q5 3 0 6l-48 5q-5 -2 0 -6Z";path(d,j<5?"#d8ac5e":"#f1ce7b",ink,.9)}
ellipse(24,-3,5,12,0,"#d6b065",ink,1);for(let j=0;j<9;j++){const a=j/9*TAU;ellipse(24+Math.cos(a)*3.9,-3+Math.sin(a)*9.3,1.3,2.4,0,"#88724e",ink,.5)}c.restore()}
barrel(-20,14,-.33,1.16);barrel(21,-12,-1.55,.94);
}else{
c.rotate(-.13);
const net=[[-64,16],[-44,-20],[-22,28],[-17,-3],[-5,-34],[13,17],[26,-15],[46,30],[62,-6],[47,-33],[-46,37],[1,38]];
const edges=[[0,1],[0,3],[0,10],[1,3],[1,4],[1,6],[2,3],[2,5],[2,10],[2,11],[3,4],[3,5],[3,6],[4,6],[4,9],[5,6],[5,7],[5,8],[5,11],[6,8],[6,9],[7,8],[7,11],[8,9],[10,11]];
for(const [a,b] of edges){const A=net[a],B=net[b],mx=(A[0]+B[0])/2+3,my=(A[1]+B[1])/2+2;const d="M"+A.join(" ")+"Q"+mx+" "+my+" "+B.join(" ");stripe(d,"#647e76",2.2);stripe(d,"#b6cfb8",.9)}
for(const [x,y] of net)ellipse(x,y,2.8,2,-.4,tint,ink,.75)
}
c.restore()
}
function drawPlate(canvas,id){
const box=canvas.getBoundingClientRect(),w=box.width,h=box.height;
if(w<1||h<1)return;
const d=Math.min(window.devicePixelRatio||1,2);
canvas.width=Math.round(w*d);canvas.height=Math.round(h*d);const c=canvas.getContext("2d");
if(!c)return;
c.setTransform(d,0,0,d,w*d/2,h*d/2);const scale=Math.min(w/177,h/113);
c.scale(scale,scale);drawArt(c,id);
}
// All coordinates and surfaces are generated here, including the two membrane leaflets.
const objects=[], defaults=Array(12).fill(null);
const palette=parts.map(p=>rgb(p[3]));
const rand=random(4077);
function object(id,center,pin,material=0,radius=.35,picture=true,angle=0){
const o={id,center,pin,material,radius,picture,angle,seed:rand()*TAU,verts:[],inds:[],paths:[]};
objects.push(o);if(!defaults[id])defaults[id]=o;return o
}
function vertex(o,p,n,col){const idx=o.verts.length/9;o.verts.push(...p,...n,...col);return idx}
function grid(o,U,V,fn,col,flip=false){
const base=o.verts.length/9,eps=.0003;
for(let j=0;j<=V;j++)for(let i=0;i<=U;i++){
const u=i/U,v=j/V,ui=clamp(u,eps,1-eps),vi=clamp(v,eps,1-eps);
const du=sub(fn(ui+eps,vi),fn(ui-eps,vi)),dv=sub(fn(ui,vi+eps),fn(ui,vi-eps));
const n=unit(flip?cross(du,dv):cross(dv,du));vertex(o,fn(u,v),n,col)
}
for(let j=0;j<V;j++)for(let i=0;i<U;i++){
const a=base+j*(U+1)+i,b=a+U+1;
if(flip)o.inds.push(a,a+1,b,a+1,b+1,b);else o.inds.push(a,b,a+1,a+1,b,b+1)
}
}
function orb(o,c,r,color,U=12,V=8,rough=0){
const base=o.verts.length/9;
for(let j=0;j<=V;j++){
const a=j/V*PI,sa=Math.sin(a),z=Math.cos(a);
for(let i=0;i<=U;i++){const b=i/U*TAU,x=sa*Math.cos(b),y=sa*Math.sin(b);
const f=1+rough*(.58*Math.sin(4*x+2*z)*Math.cos(3*y-z)+.42*Math.sin(6*y-3*x+z));
vertex(o,[c[0]+x*r[0]*f,c[1]+y*r[1]*f,c[2]+z*r[2]*f],unit([x/r[0],y/r[1],z/r[2]]),color)
}
}
for(let j=0;j<V;j++)for(let i=0;i<U;i++){const a=base+j*(U+1)+i,b=a+U+1;o.inds.push(a,b,a+1,a+1,b,b+1)}
}
function tube(o,points,rad,color,sides=8,record=false){
if(record)o.paths.push({points,rad:typeof rad==="number"?rad:.02,color});
const base=o.verts.length/9;let previous=null;
for(let j=0;j<points.length;j++){
const p=points[j],t=unit(sub(points[Math.min(points.length-1,j+1)],points[Math.max(0,j-1)]));
const n=previous?unit(sub(previous,mul(t,dot(previous,t)))):frame(t)[0],b=cross(t,n);
previous=n;const r=typeof rad==="function"?rad(j/(points.length-1)):rad;
for(let i=0;i<=sides;i++){const a=i/sides*TAU,v=add(mul(n,Math.cos(a)),mul(b,Math.sin(a)));
vertex(o,add(p,mul(v,r)),v,color)
}
}
for(let j=0;j<points.length-1;j++)for(let i=0;i<sides;i++){const a=base+j*(sides+1)+i,b=a+sides+1;o.inds.push(a,a+1,b,a+1,b+1,b)}
}
function ring(o,c,n,r,width,color,segments=18){
const f=frame(n);tube(o,curve(segments,t=>basisAt(c,f,r*Math.cos(t*TAU),r*Math.sin(t*TAU),0)),width,color,6)
}
function shellPoint(x,y,z){
const k=1+.055*Math.sin(3*x-2.8*y+1.9*z+.6)*Math.cos(2.8*y+.8*z)+.03*Math.sin(4*y+2*x-1.6*z)+.017*Math.cos(5*x+3*z);
return [2.72*x*k+.105*y*y-.055+.105*y,1.66*y*k+.22*x+.105*Math.sin(2.7*x)*(.7-.3*z)-.035,1.59*z*k*(1-.05*x)]
}
function shellUV(u,v){const a=v*PI,b=u*TAU,s=Math.sin(a);return shellPoint(s*Math.cos(b),s*Math.sin(b),Math.cos(a))}
const membrane=object(0,[0,0,0],shellPoint(-.78,.56,.277),1,2.7,false);
grid(membrane,112,72,shellUV,palette[0]);
const skinDust=object(0,[0,0,0],membrane.pin,5,2.7,false);
const ambientDots=object(0,[0,0,0],membrane.pin,6,2.7,false);
const shellSamples=[];
for(let k=0;k<7200;k++){
const z=1-2*(k+.5)/7200,r=Math.sqrt(1-z*z),t=k*2.39996323+(rand()-.5)*.013;
const x=r*Math.cos(t),y=r*Math.sin(t),p=shellPoint(x,y,z),n=unit([x/2.72,y/1.66,z/1.59]);
const shade=rand();vertex(skinDust,mul(p,.974+rand()*.025),n,[.65+shade*.27,.60+shade*.23,.78+shade*.2]);
if(k%7===0)shellSamples.push(p)
}
for(let k=0;k<210;k++){
const z=rand()*2-1,a=rand()*TAU,r=Math.sqrt(1-z*z),k2=.28+rand()*.68;
vertex(ambientDots,mul(shellPoint(r*Math.cos(a),r*Math.sin(a),z),k2),[0,0,1],[.67,.62,.77+rand()*.18])
}
const channels=object(0,[0,0,0],membrane.pin,0,2.7,false);
for(let i=0;i<63;i++){
const z=1-2*(i+.5)/63,r=Math.sqrt(1-z*z),t=i*2.39996+.41,x=Math.cos(t)*r,y=Math.sin(t)*r;
const p=mul(shellPoint(x,y,z),.994),n=unit([x/2.72,y/1.66,z/1.59]);
ring(channels,p,n,.019+rand()*.021,.0065,[.61,.55,.72],11)
}
const edge=object(0,[0,0,0],membrane.pin,7,2.7,false);
const cutRim=curve(168,t=>shellPoint(Math.cos(t*TAU),Math.sin(t*TAU),0));
tube(edge,cutRim,.018,[.90,.85,.97],8);
tube(edge,cutRim.map(p=>mul(p,.963)),.014,[.77,.70,.88],7);
for(let j=0;j<200;j++){
const p=shellPoint(Math.cos(j/200*TAU),Math.sin(j/200*TAU),0);
tube(edge,[mul(p,.965),mul(p,.998)],.0055,[.73,.63,.82],4)
}
const N=[-.49,.15,-.20],NR=[.77,.70,.66];
const nucleus=object(1,N,add(N,[-.31,.30,.45]),3,.78);
orb(nucleus,N,NR,palette[1],60,38,.027);
const nuclearDetail=object(1,N,nucleus.pin,0,.78,false);
nuclearDetail.seed=nucleus.seed;
for(let j=0;j<36;j++){
const z=1-2*(j+.46)/36,t=j*2.39996,r=Math.sqrt(1-z*z),d=[r*Math.cos(t),r*Math.sin(t),z];
const p=N.map((v,i)=>v+d[i]*NR[i]*1.008);
const n=unit(d.map((v,i)=>v/NR[i]));
ring(nuclearDetail,p,n,.039+rand()*.015,.012,rgb(j%3?"#c1a0db":"#d2b7e8"),15);
ring(nuclearDetail,add(p,mul(n,-.004)),n,.026,.006,rgb("#78548e"),12)
}
for(let j=0;j<6;j++){
const a=j*.99;const color=rgb(j%2?"#b382be":"#976baa");
tube(nuclearDetail,curve(36,t=>{const th=a+t*2.62,d=.42+.038*Math.sin(t*14+j);
return [N[0]+d*Math.cos(th),N[1]+(.39+.046*Math.sin(t*17))*Math.sin(th),N[2]-.18+.19*Math.sin(th*1.7)+.04*Math.sin(t*13+j)]}),.016,color,6)
}
const NO=add(N,[.085,-.055,.085]);
const nucleolus=object(2,NO,add(NO,[-.04,.03,.20]),0,.32);
orb(nucleolus,NO,[.315,.29,.28],rgb("#d881b3"),38,26,.068);
for(let j=0;j<55;j++){
const z=rand()*2-1,a=rand()*TAU,r=Math.sqrt(1-z*z);
const p=[NO[0]+.301*r*Math.cos(a),NO[1]+.277*r*Math.sin(a),NO[2]+.265*z];
const s=.017+rand()*.022;orb(nucleolus,p,[s,s*.79,s*.75],rgb(j%3?"#d897be":"#b7699b"),8,5)
}
const rough=object(3,[-.78,-.17,-.16],[-1.38,-.20,.03],0,1.0,true,-.32);
for(let row=0;row<5;row++){
const start=1.98+.058*row,end=5.66-.055*row,r0=.74+row*.125;
function sheet(u,v){
const t=mix(start,end,u),b=v*TAU;
const taper=.07+.93*Math.pow(Math.max(0,Math.sin(PI*u)),.29);
const rr=r0+.038*Math.sin(t*5+.33*row)+.023*Math.cos(t*8+row*.46)+.086*taper*Math.cos(b);
return [N[0]+rr*Math.cos(t)*1.12,N[1]+rr*Math.sin(t)*.86,-.23+.052*row+.11*Math.sin(t*2.3+row*.26)-.053*taper*Math.sin(b)]
}
grid(rough,62,14,sheet,tone(palette[3],.83+row*.045));
tube(rough,curve(61,t=>sheet(t,.90)),.011,rgb("#b1bce9"),6);
for(let j=0;j<22;j++){
const u=.034+.927*(j+rand()*.6)/22;
const p=sheet(u,.62+rand()*.24);p[2]+=.009;const s=.022+rand()*.008;
orb(rough,p,[s*1.15,s,s*.8],rgb(j%3?"#e5c694":"#c0a780"),7,5)
}
}
const smoothER=object(4,[.01,1.02,-.34],[.35,1.11,-.12],0,.7,true,-.19);
function networkPoint(row,col){
return [-.79+col*.327+.062*Math.sin(row*1.9+col),.84+row*.155+.088*Math.sin(col*1.5+row*.43),-.39+.117*Math.sin(col*1.66+row*.83)]
}
function smoothLink(a,b,phase,bend){
return curve(13,t=>{const p=lerp3(a,b,t),s=Math.sin(t*PI);
return [p[0]+s*.044*Math.sin(phase),p[1]+s*bend*Math.cos(t*PI+.5*phase),p[2]+s*.09*Math.sin(phase+t*2.1)]})
}
for(let j=0;j<4;j++)for(let i=0;i<5;i++){
const a=networkPoint(j,i);
if(i<4)tube(smoothER,smoothLink(a,networkPoint(j,i+1),i+j*.63,.089),.044+.007*Math.cos(j),tone(palette[4],.84+.043*j),9,true);
if(j<3&&(i+j)%2===0)tube(smoothER,smoothLink(a,networkPoint(j+1,i),i*.65+j,.05),.042,tone(palette[4],.91),8,true);
orb(smoothER,a,[.052,.053,.052],tone(palette[4],.94),9,6)
}
const ribCenters=[[1.61,-.44,.40],[-1.79,.11,.29],[.40,.49,-.62],[-.98,1.05,.10],[.10,-.79,.37],[1.84,.56,-.24],[-1.33,-.92,-.12],[.81,-.17,.84],[-.18,1.35,-.02]];
for(let j=0;j<ribCenters.length;j++){
const center=ribCenters[j],o=object(5,center,center,0,.16,true,-.2);
for(let k=0;k<8;k++){
const a=k*.93+j*.7,p=k?add(center,[(k-4)*.063,.075*Math.sin(a)+(rand()-.5)*.09,.075*Math.cos(a)+(rand()-.5)*.09]):center;
const r=.032+rand()*.014;
orb(o,p,[r*1.07,r,r*.86],rgb("#eccc83"),9,6);
orb(o,add(p,[r*.48,-r*.59,r*.15]),[r*.78,r*.59,r*.74],rgb("#c9a46a"),8,5)
}
}
const G=[1.12,.07,-.27];
const golgi=object(6,G,add(G,[.25,.10,.19]),0,.7,true,-.14);
for(let row=0;row<6;row++){
const len=.535+.088*Math.sin((row+1)*.65);
function sac(u,v){
const t=2*u-1,b=TAU*v,thick=.035+.965*Math.pow(Math.max(0,Math.sin(u*PI)),.48);
return [G[0]+t*len+(row-2.5)*.026,G[1]+(row-2.5)*.104+.19*t*t+.085*t+.035*Math.sin(t*3.6+row*.39)+Math.cos(b)*.049*thick,
G[2]+.101*t+.045*Math.sin(t*5+row*.4)+(row-2.5)*.037+Math.sin(b)*.25*thick]
}
grid(golgi,43,18,sac,tone(palette[6],.81+row*.041));
tube(golgi,curve(33,t=>sac(t,.23)),.012,rgb("#f7b7a6"),6)
}
for(let j=0;j<6;j++){
const p=add(G,[.56+rand()*.20,.27+rand()*.25,(rand()-.5)*.35]),r=.043+rand()*.039;
orb(golgi,p,[r,r*.87,r*.93],rgb("#dc998f"),12,8)
}
function mitochondrion(center,L,Y,Z,tilt,roll){
const axes=[[Math.cos(tilt),Math.sin(tilt),0],[-Math.sin(tilt)*Math.cos(roll),Math.cos(tilt)*Math.cos(roll),Math.sin(roll)],[Math.sin(tilt)*Math.sin(roll),-Math.cos(tilt)*Math.sin(roll),Math.cos(roll)]];
const o=object(7,center,center,0,L,true,-tilt);
function point(x,y,z){return basisAt(center,axes,L*x,Y*(y+.43*x*x-.14+.075*Math.sin(x*4.1)),Z*z)}
o.pin=point(.02,.03,1.025);
grid(o,42,26,(u,v)=>{const a=v*PI,b=u*TAU,s=Math.sin(a);return point(s*Math.cos(b),s*Math.sin(b),Math.cos(a))},rgb("#ec9862"));
for(const side of [-1,1]){
function face(x,y,lift=0){return point(x,y,side*(Math.sqrt(Math.max(0,1-x*x-y*y))+lift))}
grid(o,42,8,(u,v)=>{const t=u*TAU,r=v*.835;return face(r*Math.cos(t),r*Math.sin(t),.018)},rgb("#bf7357"),side<0);
tube(o,curve(49,t=>face(.85*Math.cos(t*TAU),.85*Math.sin(t*TAU),.035)),.016,rgb("#fbc08a"),7);
const foldpts=curve(100,t=>{const x=-.748+1.496*t,y=(.53*Math.sin(t*TAU*4.4+.5)+.045*Math.sin(t*45))*Math.sqrt(1-x*x);
return face(x+.034*Math.sin(t*TAU*4.4+1.1),y,.058)});
tube(o,foldpts,.022,rgb("#ffc087"),8)
}
return o
}
mitochondrion([.68,-.98,-.32],.57,.238,.205,-.25,-.12);
mitochondrion([-1.63,.62,-.28],.51,.23,.22,.53,.13);
mitochondrion([1.36,.88,-.28],.47,.216,.175,-.34,.43);
mitochondrion([2.13,-.31,-.33],.37,.185,.16,.82,-.43);
const lysoSpec=[[-1.70,-.52,.13,.206],[1.89,.40,-.23,.166],[-.92,1.14,-.20,.15],[.10,-.82,-.42,.133]];
for(const [x,y,z,r] of lysoSpec){
const c=[x,y,z],o=object(8,c,add(c,[0,.02,r*.8]),0,r);
orb(o,c,[r,r*.98,r*.96],rgb("#a6bf74"),25,17,.069);
for(let k=0;k<17;k++){
const zz=1-2*(k+.5)/17,a=k*2.39996,rr=Math.sqrt(1-zz*zz),q=add(c,mul([rr*Math.cos(a),rr*Math.sin(a),zz],r*.932)),b=r*(.11+rand()*.06);
orb(o,q,[b,b*.77,b],rgb(k%3?"#bbcf85":"#91a86a"),8,5)
}
}
for(const [x,y,z,r] of [[1.78,-.22,-.06,.125],[2.02,.04,-.27,.099],[1.50,-.57,.09,.094],[-1.97,-.08,-.26,.134],[-.04,-1.31,-.21,.11],[.69,.78,.43,.112],[-.99,.72,.79,.083],[1.07,.49,.42,.076]]){
const c=[x,y,z],o=object(9,c,add(c,[0,.01,r*.78]),4,r);
orb(o,c,[r,r*.96,r],palette[9],24,16,.018)
}
const cc=[-.78,-1.13,-.08],centrioles=object(10,cc,add(cc,[-.06,.02,.03]),0,.39);
function barrel3(c,axis,length,r){
const f=frame(axis);
for(let j=0;j<9;j++){
const a=j*TAU/9,ca=Math.cos(a),sa=Math.sin(a);
for(let q=0;q<3;q++){
const x=ca*r+Math.cos(a+q*TAU/3)*r*.11,y=sa*r+Math.sin(a+q*TAU/3)*r*.11;
const A=basisAt(c,f,x,y,-length*.5),B=basisAt(c,f,x,y,length*.5);
tube(centrioles,[A,B],r*.153,tone(palette[10],.81+.085*q),8);
ring(centrioles,B,f[2],r*.127,r*.030,rgb("#ffe0a0"),8);
ring(centrioles,A,f[2],r*.127,r*.030,rgb("#ffe0a0"),8)
}
}
for(const v of [-.34,.33])ring(centrioles,add(c,mul(f[2],length*v)),f[2],r*.93,r*.042,rgb("#b69256"),25)
}
barrel3(add(cc,[-.13,-.03,-.03]),[.82,.37,.54],.47,.115);
barrel3(add(cc,[.15,.07,.05]),[-.47,.87,.12],.42,.105);
const cyt=object(11,[0,0,-.25],[1.52,-.63,-.52],0,1.0,false),fiberOrigin=add(cc,[.05,.12,-.22]);
for(let j=0;j<20;j++){
const a=j*TAU/20+.12*Math.sin(j*4),z=-.08-.61*rand(),rr=Math.sqrt(1-z*z);
const end=mul(shellPoint(rr*Math.cos(a),rr*Math.sin(a),z),.94);
const bend=[(rand()-.5)*1.18,(rand()-.5)*.89,-.36-rand()*.38];
const pts=curve(30,t=>add(lerp3(fiberOrigin,end,t),mul(bend,Math.sin(t*PI))));
tube(cyt,pts,.009+rand()*.007,rgb(j%3?"#6caaa8":"#95c3b8"),6,true);
if(j%3===0){
const branch=curve(16,t=>{const p=lerp3(pts[17],end,t);return [p[0]+.28*t*Math.sin(a),p[1]-.31*t*Math.cos(a),p[2]-.16*Math.sin(t*PI)]});
tube(cyt,branch,.008,rgb("#83aaa8"),5,true)
}
if(j===18)cyt.pin=pts[22]
}
for(let j=0;j<7;j++){
const a=j*.94,dz=-.3-.33*rand();
const line=curve(29,t=>{const th=a+t*.94,z=dz+.17*Math.sin(t*4+j),r=Math.sqrt(1-z*z);return mul(shellPoint(r*Math.cos(th),r*Math.sin(th),z),.90-.032*Math.sin(t*5))});
tube(cyt,line,.009,rgb("#78aaa4"),6,true)
}
const caps=[];
function sectionOf(o){
const links=new Map(),p=o.verts,ix=o.inds;
function key(a){return Math.round(a[0]*14000)+","+Math.round(a[1]*14000)}
function junction(v){const k=key(v);if(!links.has(k))links.set(k,{p:v,ad:[]});return links.get(k)}
for(let i=0;i<ix.length;i+=3){
const ids=[ix[i]*9,ix[i+1]*9,ix[i+2]*9],hits=[];
for(let j=0;j<3;j++){
const a=ids[j],b=ids[(j+1)%3],za=p[a+2],zb=p[b+2];
if((za>0)===(zb>0))continue;
const t=za/(za-zb);hits.push([mix(p[a],p[b],t),mix(p[a+1],p[b+1],t),0])
}
if(hits.length!==2||key(hits[0])===key(hits[1]))continue;
const a=junction(hits[0]),b=junction(hits[1]);
a.ad.push(b);b.ad.push(a)
}
if(links.size<3)return;
const cap={...o,verts:[],inds:[],material:8,parent:o},visited=new Set(),color=tone(palette[o.id],.81,.105);
for(const start of links.values()){
if(visited.has(start))continue;
let prev=null,here=start,closed=false;const loop=[];
while(here&&!visited.has(here)){
visited.add(here);loop.push(here.p);
const next=here.ad.find(k=>k!==prev);prev=here;here=next;if(here===start){closed=true;break}
}
if(!closed||loop.length<3)continue;
const center=mul(loop.reduce((s,v)=>add(s,v),[0,0,0]),1/loop.length),base=vertex(cap,center,[0,0,1],color);
for(const q of loop)vertex(cap,q,[0,0,1],color);
for(let j=0;j<loop.length;j++)cap.inds.push(base,base+1+j,base+1+(j+1)%loop.length)
}
if(cap.inds.length)caps.push(cap)
}
for(const o of objects)if(o.id>0)sectionOf(o);
const state={step:0,selected:0,active:membrane,playing:true,cut:false,cutAmount:0,demo:location.hash==="#demo",demoStart:0,clock:0,nextAt:0,focus:false,anchor:null};
const camera={yaw:-.115,pitch:.14,tyaw:-.115,tpitch:.14,zoom:1,tzoom:1,center:[0,0,0],goal:[0,0,0],spin:0,tiltSpin:0};
const born=Array(12).fill(-20),reduceMotion=matchMedia("(prefers-reduced-motion: reduce)").matches;
let model=$("model"),stage=$("stage"),W=1,H=1,dpr=1,scale=1,rot=new Float32Array(9),motionT=0,gpu=null,soft=null;
function moveOf(o){
const k=o.id===0?0:1,age=state.clock-born[o.id],u=o.id===0?1:smooth(age/.60);
const life=reduceMotion ? .18 : 1,s=o.seed,t=motionT;
const d=[.029*Math.sin(t*.64+s),.032*Math.sin(t*.53+s*1.83),.025*Math.cos(t*.48+s*1.33)*(1-state.cutAmount)];
return {shift:mul(d,k*life),grow:(o.id===0?1:.035+.965*u)*(1+.011*k*life*Math.sin(t*.85+s)),alpha:o.id===0?1:smooth(age/.40)}
}
function deform(p){
const k=reduceMotion ? .28 : 1,t=motionT;
return [p[0]*(1+.005*k*Math.sin(t*.63)),p[1]*(1+.006*k*Math.sin(t*.76))+.014*k*Math.sin(p[0]*1.31+t*.64),p[2]*(1+.008*k*Math.cos(t*.56))]
}
function world(o,p){const m=moveOf(o);return deform(add(add(o.center,mul(sub(p,o.center),m.grow)),m.shift))}
function rotation(){
const y=camera.yaw,p=camera.pitch,cy=Math.cos(y),sy=Math.sin(y),cp=Math.cos(p),sp=Math.sin(p);
rot.set([cy,sp*sy,-cp*sy,0,cp,sp,sy,-sp*cy,cp*cy]);
scale=Math.min(W/6.38,H/4.40)*camera.zoom
}
function project(p){
const a=sub(p,camera.center),x=rot[0]*a[0]+rot[3]*a[1]+rot[6]*a[2],y=rot[1]*a[0]+rot[4]*a[1]+rot[7]*a[2],z=rot[2]*a[0]+rot[5]*a[1]+rot[8]*a[2];
const s=scale/(1-z/13.5);return {x:W*.5+x*s,y:H*.5-y*s,z,s}
}
function sectionHeight(){return state.cutAmount<.0001?4:1.87*(1-state.cutAmount)}
const vertexSource=[
"precision highp float;",
"attribute vec3 aPos,aNorm,aColor;",
"uniform mat3 uRot; uniform vec3 uTarget,uOrigin,uShift;",
"uniform vec2 uProjection; uniform float uGrow,uTime,uKind,uPointScale,uMotion;",
"varying vec3 vWorld,vEye,vNormal,vColor,vRest;",
"void main(){",
" vec3 p=uOrigin+(aPos-uOrigin)*uGrow+uShift;",
" if(uKind>1.5&&uKind<2.5)p*=.964;",
" p.x*=1.+.005*uMotion*sin(uTime*.63);",
" p.y=p.y*(1.+.006*uMotion*sin(uTime*.76))+.014*uMotion*sin(p.x*1.31+uTime*.64);",
" p.z*=1.+.008*uMotion*cos(uTime*.56);",
" vRest=aPos;vWorld=p;vEye=uRot*(p-uTarget);vNormal=uRot*aNorm;vColor=aColor;",
" float d=1.-vEye.z/13.5;",
" gl_Position=vec4(vEye.xy*uProjection,-vEye.z*.09,d);",
" float rim=1.-abs(dot(normalize(vNormal),normalize(vec3(-vEye.xy,13.5-vEye.z))));",
" gl_PointSize=clamp(uPointScale*(.85+1.65*rim+1.8*(aColor.r-.64))/max(.45,d),1.,11.);",
" if(uKind>5.5&&uKind<6.5)gl_PointSize=clamp(uPointScale*(1.2+2.8*(aColor.b-.7)),1.,7.);",
"}"].join("\n");
const fragmentSource=[
"#ifdef GL_FRAGMENT_PRECISION_HIGH","precision highp float;","#else","precision mediump float;","#endif",
"varying vec3 vWorld,vEye,vNormal,vColor,vRest;",
"uniform float uKind,uAlpha,uSlice,uCut,uPicking,uId,uFocus;",
"float hash(vec3 p){p=fract(p*.3171+vec3(.17,.43,.79)); p+=dot(p,p.yzx+19.19);return fract((p.x+p.y)*p.z);}",
"float tissueNoise(vec3 p){vec3 a=floor(p),f=fract(p);f=f*f*(3.-2.*f);return mix(mix(mix(hash(a),hash(a+vec3(1,0,0)),f.x),mix(hash(a+vec3(0,1,0)),hash(a+vec3(1,1,0)),f.x),f.y),mix(mix(hash(a+vec3(0,0,1)),hash(a+vec3(1,0,1)),f.x),mix(hash(a+vec3(0,1,1)),hash(a+vec3(1,1,1)),f.x),f.y),f.z);}",
"void main(){",
" if(uKind<6.5 && vWorld.z>uSlice)discard;",
" if(uPicking>.5){gl_FragColor=vec4((uId+1.)/255.,0,0,1);return;}",
" vec3 V=normalize(vec3(-vEye.xy,13.5-vEye.z)),N=normalize(vNormal);",
" float f=abs(dot(N,V)),rim=1.-f;",
" if(uKind>4.5&&uKind<6.5){float r=length(gl_PointCoord-.5)*2.;if(r>=1.)discard;float a=(1.-smoothstep(.48,1.,r))*(uKind<5.5?(.13+.57*pow(rim,1.8)):.35);gl_FragColor=vec4(vColor,a*uAlpha);return;}",
" if(dot(N,V)<0.)N=-N;",
" vec3 L=normalize(vec3(-.48,.69,.65)),H=normalize(L+V);",
" float light=max(0.,dot(N,L)),spec=max(0.,dot(N,H));",
" float haze=tissueNoise(vRest*3.8),grain=tissueNoise(vRest*45.);",
" float slit=(1.-smoothstep(.003,.028,abs(vWorld.z-uSlice)))*smoothstep(.001,.12,uCut);",
" vec3 color=vColor;float alpha=1.;",
" if(uKind>.5&&uKind<2.5){",
" float edge=pow(rim,1.53),irid=.5+.5*sin(vRest.x*1.65-vRest.y*2.5+haze*2.7);",
" vec3 shine=mix(vec3(.62,.77,.89),vec3(.90,.69,.90),irid);",
" float folds=.5+.5*sin(vRest.x*9.7+vRest.y*12.+vRest.z*8.+haze*12.);",
" color=mix(vec3(.48,.40,.66),shine,.23+.72*edge);",
" color+=.095*(haze-.45)+.075*(grain-.47)+.12*pow(spec,13.)+.15*pow(spec,88.);",
" alpha=.115+.076*haze+.68*edge+.095*pow(spec,23.)+.022*folds;",
" if(!gl_FrontFacing){color*=.86;alpha*=.79;}",
" if(uKind>1.5){color=mix(color,vec3(.80,.72,.90),.33);alpha=.012+.33*pow(rim,3.7);}",
" color=mix(color,shine+.10,slit*.88);alpha=max(alpha,slit*.86);",
" }else if(uKind>2.5&&uKind<3.5){",
" float threads=smoothstep(.76,.98,.5+.5*sin(16.*vRest.y+21.*vRest.x+9.*haze));",
" color=vColor*(.69+.32*light+.14*haze)+vec3(.09,.05,.11)*threads+.17*pow(spec,21.);",
" color=mix(color,vec3(.93,.79,.97),.55*pow(rim,2.));",
" alpha=gl_FrontFacing?(.25+.41*pow(rim,1.3)+.08*grain):(.61+.20*rim);",
" color=mix(color,vec3(.92,.80,.97),slit);alpha=max(alpha,slit);",
" }else if(uKind>3.5&&uKind<4.5){",
" color=vColor*(.67+.35*light)+.27*pow(spec,24.)+vec3(.15,.16,.17)*rim;",
" alpha=.30+.64*pow(rim,1.3)+.16*pow(spec,18.);",
" }else if(uKind>7.5){",
" color=vColor*(.87+.17*haze+.10*grain);alpha=uId<1.5?.22:.95;",
" }else{",
" float back=max(dot(N,normalize(vec3(.6,-.35,.5))),0.);",
" color=vColor*(.57+.41*light+.13*back+.13*haze+.068*(grain-.50));",
" color+=vec3(.14,.115,.12)*pow(spec,26.)+vec3(.08,.07,.115)*pow(rim,2.);",
" color=mix(color,vColor*1.05+.12,slit*.67);",
" }",
" color+=vec3(.04,.032,.025)*uFocus*rim;",
" gl_FragColor=vec4(clamp(color,0.,1.),clamp(alpha*uAlpha,0.,1.));",
"}"].join("\n");
function initGPU(canvas){
const gl=canvas.getContext("webgl",{alpha:true,antialias:true,depth:true,premultipliedAlpha:true,powerPreference:"default"});
if(!gl)return null;
function shader(type,src){const s=gl.createShader(type);gl.shaderSource(s,src);gl.compileShader(s);if(!gl.getShaderParameter(s,gl.COMPILE_STATUS))throw Error("Shader unavailable");return s}
const pg=gl.createProgram();gl.attachShader(pg,shader(gl.VERTEX_SHADER,vertexSource));gl.attachShader(pg,shader(gl.FRAGMENT_SHADER,fragmentSource));gl.linkProgram(pg);
if(!gl.getProgramParameter(pg,gl.LINK_STATUS))throw Error("Renderer unavailable");
gl.useProgram(pg);
const loc={};for(const name of ["Rot","Target","Origin","Shift","Projection","Grow","Time","Kind","PointScale","Motion","Alpha","Slice","Cut","Picking","Id","Focus"])loc[name]=gl.getUniformLocation(pg,"u"+name);
const attr=["aPos","aNorm","aColor"].map(n=>gl.getAttribLocation(pg,n));
for(const i of attr)gl.enableVertexAttribArray(i);
for(const o of [...objects,...caps]){
o.vbo=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,o.vbo);gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(o.verts),gl.STATIC_DRAW);
if(o.inds.length){o.ibo=gl.createBuffer();gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,o.ibo);gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,new Uint16Array(o.inds),gl.STATIC_DRAW)}
}
gl.enable(gl.DEPTH_TEST);gl.depthFunc(gl.LEQUAL);gl.disable(gl.DITHER);
gl.blendFuncSeparate(gl.SRC_ALPHA,gl.ONE_MINUS_SRC_ALPHA,gl.ONE,gl.ONE_MINUS_SRC_ALPHA);
const fbo=gl.createFramebuffer(),texture=gl.createTexture(),depth=gl.createRenderbuffer();let fw=0,fh=0;
function pickSurface(){
const w=canvas.width,h=canvas.height;
gl.bindFramebuffer(gl.FRAMEBUFFER,fbo);
if(fw===w&&fh===h)return;
gl.bindTexture(gl.TEXTURE_2D,texture);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);
gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,w,h,0,gl.RGBA,gl.UNSIGNED_BYTE,null);
gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.TEXTURE_2D,texture,0);
gl.bindRenderbuffer(gl.RENDERBUFFER,depth);gl.renderbufferStorage(gl.RENDERBUFFER,gl.DEPTH_COMPONENT16,w,h);
gl.framebufferRenderbuffer(gl.FRAMEBUFFER,gl.DEPTH_ATTACHMENT,gl.RENDERBUFFER,depth);fw=w;fh=h
}
function draw(o,type=o.material,alpha=1){
if(o.id>state.step)return;const motion=moveOf(o);
if(motion.alpha<.018)return;
gl.uniform1f(loc.Kind,type);gl.uniform3fv(loc.Origin,o.center);gl.uniform3fv(loc.Shift,motion.shift);
gl.uniform1f(loc.Grow,motion.grow);gl.uniform1f(loc.Alpha,motion.alpha*alpha);gl.uniform1f(loc.Id,o.id);
gl.uniform1f(loc.Focus,state.focus&&state.selected===o.id?1:0);
gl.bindBuffer(gl.ARRAY_BUFFER,o.vbo);for(let i=0;i<3;i++)gl.vertexAttribPointer(attr[i],3,gl.FLOAT,false,36,i*12);
if(o.ibo){gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,o.ibo);gl.drawElements(gl.TRIANGLES,o.inds.length,gl.UNSIGNED_SHORT,0)}
else gl.drawArrays(gl.POINTS,0,o.verts.length/9)
}
function render(picking=false){
if(picking)pickSurface();else gl.bindFramebuffer(gl.FRAMEBUFFER,null);
gl.viewport(0,0,canvas.width,canvas.height);gl.clearColor(0,0,0,0);gl.depthMask(true);gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT);
gl.uniformMatrix3fv(loc.Rot,false,rot);gl.uniform3fv(loc.Target,camera.center);gl.uniform2f(loc.Projection,2*scale/W,2*scale/H);
gl.uniform1f(loc.Time,motionT);gl.uniform1f(loc.PointScale,dpr*scale/84);gl.uniform1f(loc.Slice,sectionHeight());
gl.uniform1f(loc.Motion,reduceMotion ? .28 : 1);gl.uniform1f(loc.Cut,state.cutAmount);gl.uniform1f(loc.Picking,picking?1:0);
if(picking)gl.disable(gl.BLEND);else gl.enable(gl.BLEND);
gl.depthMask(picking);gl.enable(gl.CULL_FACE);gl.cullFace(gl.FRONT);
draw(membrane);if(!picking)draw(membrane,2);
if(picking)draw(nucleus);
gl.disable(gl.CULL_FACE);gl.depthMask(true);
for(const o of objects)if(o.material===0)draw(o);
if(state.cutAmount>.991)draw(edge);
if(state.cutAmount>.985){for(const cap of caps)if(cap.id!==1)draw(cap,8,smooth((state.cutAmount-.985)/.015))}
if(picking){
for(const o of objects)if(o.material===4)draw(o);
return
}
gl.depthMask(false);gl.enable(gl.CULL_FACE);gl.cullFace(gl.FRONT);draw(nucleus);
gl.cullFace(gl.BACK);draw(nucleus);
if(state.cutAmount>.985){gl.disable(gl.CULL_FACE);for(const cap of caps)if(cap.id===1)draw(cap,8,smooth((state.cutAmount-.985)/.015))}
gl.enable(gl.CULL_FACE);gl.cullFace(gl.BACK);
for(const o of objects)if(o.material===4)draw(o);
gl.disable(gl.CULL_FACE);if(state.step>0)draw(ambientDots,6,.66);
draw(skinDust);gl.enable(gl.CULL_FACE);gl.cullFace(gl.BACK);draw(membrane,2);draw(membrane);
gl.disable(gl.CULL_FACE);gl.depthMask(true)
}
function pick(x,y){
render(true);
const px=clamp(Math.round(x/W*(canvas.width-1)),0,canvas.width-1),py=clamp(Math.round((1-y/H)*(canvas.height-1)),0,canvas.height-1);
const r=Math.ceil(dpr*3),l=Math.max(px-r,0),b=Math.max(py-r,0),w=Math.min(canvas.width-l,2*r+1),h=Math.min(canvas.height-b,2*r+1);
const data=new Uint8Array(w*h*4);gl.readPixels(l,b,w,h,gl.RGBA,gl.UNSIGNED_BYTE,data);
let id=data[((py-b)*w+px-l)*4]-1,best=Infinity;
if(id<=0)for(let j=0;j<h;j++)for(let i=0;i<w;i++){const n=data[(j*w+i)*4]-1,dd=(l+i-px)**2+(b+j-py)**2;if(n>0&&dd<best){id=n;best=dd}}
gl.bindFramebuffer(gl.FRAMEBUFFER,null);return id
}
return {render,pick}
}
// A software depth buffer keeps the same 3D model interactive on devices without WebGL.
function initSoftware(canvas){
const ctx=canvas.getContext("2d"),all=[...objects,...caps];
for(const o of all){
o.sv=new Float32Array(o.verts);o.si=new Uint16Array(o.inds);
const n=o.sv.length/9;o.screen=new Float32Array(n*8);o.texture=new Float32Array(n);
for(let i=0;i<n;i++){
const k=i*9,x=o.sv[k],y=o.sv[k+1],z=o.sv[k+2];
o.texture[i]=.5+.24*Math.sin(4.8*x+2.8*z+1.3*Math.sin(4.1*y))*Math.cos(5*y-2*z)+.19*Math.sin(32*x+39*y-27*z+.3)*Math.cos(21*z+13*y)
}
}
let w=0,h=0,img,data,depth,ids,pickZ;
function resize(){
if(w===canvas.width&&h===canvas.height)return;
w=canvas.width;h=canvas.height;img=ctx.createImageData(w,h);data=img.data;depth=new Float32Array(w*h);ids=new Int8Array(w*h);pickZ=new Float32Array(w*h)
}
function prepare(o,type){
const m=moveOf(o),p=o.sv,s=o.screen,g=m.grow,sh=m.shift,c=o.center,k=reduceMotion ? .28 : 1;
const mx=1+.005*k*Math.sin(motionT*.63),my=1+.006*k*Math.sin(motionT*.76),mz=1+.008*k*Math.cos(motionT*.56),phase=motionT*.64;
const radial=type===2?.964:1,halfW=w/2,halfH=h/2,pixScale=w/W*scale,goal=camera.center;
for(let i=0,j=0,n=0;i<p.length;i+=9,j+=8,n++){
let x=((p[i]-c[0])*g+c[0]+sh[0])*radial*mx;
let y=((p[i+1]-c[1])*g+c[1]+sh[1])*radial*my+.014*k*Math.sin(1.31*x+phase);
const z=((p[i+2]-c[2])*g+c[2]+sh[2])*radial*mz;s[j+3]=z;
x-=goal[0];y-=goal[1];const q=z-goal[2];
const vx=rot[0]*x+rot[3]*y+rot[6]*q,vy=rot[1]*x+rot[4]*y+rot[7]*q,vz=rot[2]*x+rot[5]*y+rot[8]*q;
const ps=pixScale/(1-vz/13.5);s[j]=halfW+vx*ps;s[j+1]=halfH-vy*ps;s[j+2]=vz;
let nx=rot[0]*p[i+3]+rot[3]*p[i+4]+rot[6]*p[i+5],ny=rot[1]*p[i+3]+rot[4]*p[i+4]+rot[7]*p[i+5],nz=rot[2]*p[i+3]+rot[5]*p[i+4]+rot[8]*p[i+5];
const facing=(nz*(13.5-vz)-nx*vx-ny*vy)/Math.sqrt(vx*vx+vy*vy+(13.5-vz)**2);
const rim=1-Math.min(1,Math.abs(facing)),tex=o.texture[n];if(facing<0){nx=-nx;ny=-ny;nz=-nz}
const lit=Math.max(0,-nx*.48+ny*.69+nz*.55),spec=Math.max(0,-nx*.263+ny*.381+nz*.885);
let r=p[i+6],gg=p[i+7],b=p[i+8],a=1;
if(type===1||type===2){
const e=Math.pow(rim,1.53),ir=.5+.5*Math.sin(p[i]*1.65-p[i+1]*2.5+2.7*tex),f=.23+.72*e;
const sp=.12*Math.pow(spec,13)+.15*Math.pow(spec,88)+.11*(tex-.45);
r=mix(.48,.62+.28*ir,f)+sp;gg=mix(.40,.77-.08*ir,f)+sp;b=mix(.66,.89+.02*ir,f)+sp;
a=type===1?.13+.08*tex+.68*e+.095*Math.pow(spec,23):.012+.33*Math.pow(rim,3.7);
}else if(type===3){
const v=.68+.32*lit+.16*tex,st=.17*Math.pow(spec,21),ed=rim*rim*.55;
r=mix(r*v+st,.93,ed);gg=mix(gg*v+st,.79,ed);b=mix(b*v+st,.97,ed);a=.27+.42*Math.pow(rim,1.3)+.08*tex;
}else if(type===4){
const v=.67+.35*lit,extra=.27*Math.pow(spec,24)+.15*rim;r=r*v+extra;gg=gg*v+extra;b=b*v+extra;a=.32+.64*Math.pow(rim,1.3);
}else if(type===5){a=.13+.57*Math.pow(rim,1.8)}
else if(type===6){a=.30}
else if(type===8){const v=.88+.19*tex;r*=v;gg*=v;b*=v;a=o.id===1?.22:.95}
else{const v=.57+.41*lit+.13*Math.max(0,nx*.63-ny*.37+nz*.52)+.14*tex,sp=.15*Math.pow(spec,26)+.083*rim*rim;r=r*v+sp;gg=gg*v+sp*.88;b=b*v+sp}
s[j+4]=Math.min(255,r*255);s[j+5]=Math.min(255,gg*255);s[j+6]=Math.min(255,b*255);s[j+7]=a*m.alpha
}
}
function composite(pixel,r,g,b,a){
const k=pixel*4,k2=1-a;
data[k]=r*a+data[k]*k2;data[k+1]=g*a+data[k+1]*k2;data[k+2]=b*a+data[k+2]*k2;data[k+3]=255*a+data[k+3]*k2
}
function mesh(o,type,side=0,write=false){
if(o.id>state.step||moveOf(o).alpha<.018)return;
prepare(o,type);
const v=o.screen,ix=o.si,cut=type>=7?4:sectionHeight(),pickable=type!==2&&(type!==1||side===-1)&&(type!==3||side===-1)&&(type!==8||o.id!==1);
const opacity=type===1&&side===-1?.79:type===3&&side===-1?1.52:1;
for(let i=0;i<ix.length;i+=3){
const a=ix[i]*8,b=ix[i+1]*8,c=ix[i+2]*8,az=v[a+3],bz=v[b+3],cz=v[c+3];
if(az>cut&&bz>cut&&cz>cut)continue;
const ax=v[a],ay=v[a+1],bx=v[b],by=v[b+1],cx=v[c],cy=v[c+1],BAx=bx-ax,BAy=by-ay,CAx=cx-ax,CAy=cy-ay,det=BAx*CAy-BAy*CAx;
if(Math.abs(det)<.0001||(side===1&&det>=0)||(side===-1&&det<=0))continue;
const x0=Math.max(0,Math.ceil(Math.min(ax,bx,cx)-.5)),x1=Math.min(w-1,Math.floor(Math.max(ax,bx,cx)-.5));
const y0=Math.max(0,Math.ceil(Math.min(ay,by,cy)-.5)),y1=Math.min(h-1,Math.floor(Math.max(ay,by,cy)-.5));
if(x0>x1||y0>y1)continue;
const dbx=CAy/det,dcx=-BAy/det,dby=-CAx/det,dcy=BAx/det;
let startB=(x0+.5-ax)*dbx+(y0+.5-ay)*dby,startC=(x0+.5-ax)*dcx+(y0+.5-ay)*dcy;
const z0=v[a+2],zb=v[b+2]-z0,zc=v[c+2]-z0,r0=v[a+4],rb=v[b+4]-r0,rc=v[c+4]-r0,g0=v[a+5],gb=v[b+5]-g0,gc=v[c+5]-g0,bl0=v[a+6],blb=v[b+6]-bl0,blc=v[c+6]-bl0,al0=v[a+7],alb=v[b+7]-al0,alc=v[c+7]-al0;
const clip=az>cut||bz>cut||cz>cut;
for(let y=y0;y<=y1;y++,startB+=dby,startC+=dcy){
let B=startB,C=startC;
for(let x=x0,pix=y*w+x0;x<=x1;x++,pix++,B+=dbx,C+=dcx){
if(B<-.00001||C<-.00001||B+C>1.00001)continue;
if(clip&&az+B*(bz-az)+C*(cz-az)>cut)continue;
const z=z0+zb*B+zc*C;if(z<depth[pix]-.00003)continue;
if(write)depth[pix]=z;
if(pickable&&z>=pickZ[pix]-.00003){ids[pix]=o.id;pickZ[pix]=z}
const alpha=Math.min(1,(al0+alb*B+alc*C)*opacity);
composite(pix,r0+rb*B+rc*C,g0+gb*B+gc*C,bl0+blb*B+blc*C,alpha)
}
}
}
}
function particles(o,type){
prepare(o,type);const s=o.screen,cut=sectionHeight(),unitPx=clamp(w/W*scale/87,.6,2.4);
for(let j=0;j<s.length;j+=8){
if(s[j+3]>cut)continue;
const x=s[j],y=s[j+1],a=s[j+7]*(type===6?.60:1),radius=unitPx*(.50+.95*a);
for(let yy=Math.max(0,Math.ceil(y-radius));yy<=Math.min(h-1,Math.floor(y+radius));yy++)
for(let xx=Math.max(0,Math.ceil(x-radius));xx<=Math.min(w-1,Math.floor(x+radius));xx++){
const d2=((xx-x)**2+(yy-y)**2)/(radius*radius),p=yy*w+xx;
if(d2<1&&s[j+2]>=depth[p])composite(p,s[j+4],s[j+5],s[j+6],a*(1-d2))
}
}
}
function render(){
resize();data.fill(0);depth.fill(-100);pickZ.fill(-100);ids.fill(-1);
mesh(membrane,1,-1);mesh(membrane,2,-1);
for(const o of objects)if(o.material===0)mesh(o,0,0,true);
if(state.cutAmount>.991){mesh(edge,7,0,true);for(const o of caps)if(o.id!==1)mesh(o,8,0,true)}
mesh(nucleus,3,-1);mesh(nucleus,3,1);
if(state.cutAmount>.991)for(const o of caps)if(o.id===1)mesh(o,8);
for(const o of objects)if(o.material===4)mesh(o,4,1);
if(state.step)particles(ambientDots,6);particles(skinDust,5);
mesh(membrane,2,1);mesh(membrane,1,1);
for(let i=0;i<data.length;i+=4){
const a=data[i+3];if(a>0&&a<255){const f=255/a;data[i]*=f;data[i+1]*=f;data[i+2]*=f}
}
ctx.putImageData(img,0,0)
}
function pick(x,y){
if(!ids)return -1;
const X=clamp(Math.round(x*w/W),0,w-1),Y=clamp(Math.round(y*h/H),0,h-1),n=ids[Y*w+X];
if(n>0)return n;
let id=n,d=Infinity;
for(let j=Math.max(0,Y-3);j<=Math.min(h-1,Y+3);j++)for(let i=Math.max(0,X-3);i<=Math.min(w-1,X+3);i++){
const v=ids[j*w+i],dist=(i-X)**2+(j-Y)**2;if(v>0&&dist<d){id=v;d=dist}
}
return id
}
return {render,pick}
}
const members=id=>objects.filter(o=>o.id===id&&(o.picture||o===membrane||o===cyt));
const ticks=$("ticks"),guide=$("guide"),guideGrid=$("guideGrid"),range=$("buildRange"),tag=$("callout");
const pointers=new Map();
let tagW=94,tagH=29,holdStill=0,guideResume=false,lastFrame=0,previousTime=0,beforeCut=null;
let resolutionFactor=1,slowFrames=0,lastResize=0,lastHidden=0;
for(let i=0;i<parts.length;i++){
const tick=document.createElement("i");tick.style.left=(i/11*100)+"%";ticks.append(tick);
const button=document.createElement("button"),icon=document.createElement("canvas"),name=document.createElement("span");
button.type="button";button.className="guideentry";button.dataset.part=String(i);icon.setAttribute("aria-hidden","true");name.textContent=parts[i][0];
button.append(icon,name);guideGrid.append(button);button.addEventListener("click",()=>{guideResume=false;closeGuide();browse(i)})
}
function showControls(){
const s=state,complete=s.step===11,running=s.playing&&!complete;
range.value=String(s.step);range.setAttribute("aria-valuetext",s.step+" of 11 parts, "+parts[s.step][0]);
$("timecount").textContent=s.step+" of 11 parts";$("scrubber").style.setProperty("--progress",(s.step/11*100)+"%");
[...ticks.children].forEach((t,n)=>t.classList.toggle("on",n<=s.step));
const label=running?"Pause build":complete?"Replay build":"Play build",play=$("play");
play.setAttribute("title",label);play.setAttribute("aria-label",label);play.querySelector("use").setAttribute("href",running?"#i-pause":"#i-play");
const live=$("live");live.lastElementChild.textContent=complete?"Explore mode":running?"Assembling":"Build paused";live.dataset.state=running||complete?"live":"paused";
$("cut").setAttribute("aria-checked",String(s.cut))
}
function showNote(){
const id=state.selected,p=parts[id];
document.documentElement.style.setProperty("--accent",p[3]);
$("role").textContent=p[2];$("partTitle").textContent=p[0];$("partTitle").classList.toggle("long",p[0].length>19);
$("fact").textContent=p[4];$("noteindex").textContent=String(id).padStart(2,"0")+" / 11";
$("previous").disabled=id===0;$("next").firstElementChild.textContent=id===11?"Whole cell":"Next part";
tag.lastElementChild.textContent=p[1];tagW=tag.offsetWidth;tagH=tag.offsetHeight;
for(const btn of guideGrid.children)btn.setAttribute("aria-current",String(Number(btn.dataset.part)===id));
drawPlate($("plate"),id)
}
function pinWorld(o){
let p=state.anchor&&state.active===o?state.anchor:o.pin;
if(o===membrane&&!state.anchor&&state.cutAmount>.45)p=shellPoint(-.799,.601,0);
const q=world(o,p);q[2]=Math.min(q[2],sectionHeight()-.003);return q
}
function representative(id,x,y){
const choices=members(id);
if(id===0||choices.length===1)return choices[0]||defaults[id];
let score=Infinity,best=choices[0];
for(let i=0;i<choices.length;i++){
const o=choices[i],q=world(o,o.center),p=project(q),distance=x==null?i:(p.x-x)**2+(p.y-y)**2;
const hidden=q[2]-o.radius*.8>sectionHeight()?1e6:0;
if(distance+hidden<score){score=distance+hidden;best=o}
}
return best
}
function focusObject(o){
const id=o.id;camera.spin=0;camera.tiltSpin=0;
if(id===0){
if(!state.anchor){fitView();return}
camera.goal=mul(pinWorld(o),.64);camera.tzoom=1.47;state.focus=true;holdStill=state.clock+8;return
}
const target=pinWorld(o),center=world(o,o.center);
const wide=id===3||id===4||id===11;
camera.goal=wide?mul(target,.87):lerp3(center,target,.36);
camera.tzoom=({1:1.64,2:2.08,3:1.49,4:1.72,5:2.40,6:1.83,7:2.06,8:2.33,9:2.45,10:2.22,11:1.55})[id];
state.focus=true;holdStill=state.clock+8
}
function selectPart(id,o=null,fly=false){
state.selected=id;state.active=o||representative(id);state.anchor=null;showNote();
if(fly)focusObject(state.active)
}
function setStep(n,show=true,animate=true){
n=clamp(Math.round(n),0,11);const prev=state.step;
if(n>prev)for(let i=prev+1;i<=n;i++)born[i]=animate&&i===n?state.clock:state.clock-2;
state.step=n;
if(n===11)state.playing=false;
if(show||state.selected>n)selectPart(n);
showControls()
}
function nearestAngle(angle,reference){return reference+Math.atan2(Math.sin(angle-reference),Math.cos(angle-reference))}
function fitView(){
camera.goal=[0,0,0];camera.tzoom=1;camera.spin=camera.tiltSpin=0;
camera.tyaw=nearestAngle(state.cut?-.73:-.115,camera.yaw);camera.tpitch=state.cut?.28:.14;
state.focus=false;holdStill=state.clock+3
}
function setCut(open,orient=true){
if(open===state.cut)return;
state.cut=open;camera.spin=camera.tiltSpin=0;
if(orient){
if(open){beforeCut=[camera.tyaw,camera.tpitch];camera.tyaw=nearestAngle(-.73,camera.yaw);camera.tpitch=.28}
else if(beforeCut){camera.tyaw=nearestAngle(beforeCut[0],camera.yaw);camera.tpitch=beforeCut[1];beforeCut=null}
}
holdStill=state.clock+3;showControls()
}
function rebuild(){
state.playing=true;setCut(false,false);state.focus=false;state.anchor=null;beforeCut=null;fitView();
setStep(0);born.fill(-20);state.nextAt=state.clock+1.30;showControls()
}
function pauseBuild(){if(state.playing){state.playing=false;showControls()}}
function browse(id){
pauseBuild();if(id>state.step)setStep(id,false,false);selectPart(id,null,true);showControls()
}
function stopDemo(){
if(!state.demo)return;
state.demo=false;pauseBuild();camera.spin=camera.tiltSpin=0;holdStill=state.clock+4
}
function togglePlay(){
if(state.playing){pauseBuild();return}
if(state.step===11){rebuild();return}
state.focus=false;fitView();selectPart(state.step);state.playing=true;state.nextAt=state.clock+1.75;showControls()
}
function zoomBy(factor){
camera.tzoom=clamp(camera.tzoom*factor,.70,3.15);holdStill=state.clock+4
}
$("play").addEventListener("click",togglePlay);
$("rebuild").addEventListener("click",rebuild);
$("previous").addEventListener("click",()=>browse(Math.max(0,state.selected-1)));
$("next").addEventListener("click",()=>browse(state.selected===11?0:state.selected+1));
$("cut").addEventListener("click",()=>setCut(!state.cut));
$("plus").addEventListener("click",()=>zoomBy(1.22));
$("minus").addEventListener("click",()=>zoomBy(1/1.22));
$("fit").addEventListener("click",fitView);
range.addEventListener("pointerdown",pauseBuild);
range.addEventListener("input",()=>{pauseBuild();if(state.focus)fitView();setStep(+range.value,true,false)});
function openGuide(){
guideResume=state.playing;pauseBuild();
if(typeof guide.showModal==="function")guide.showModal();else guide.setAttribute("open","");
[...guideGrid.children].forEach((btn,i)=>drawPlate(btn.firstElementChild,i));
$("closeGuide").focus({preventScroll:true})
}
function closedGuide(){
if(guideResume&&state.step<11){state.playing=true;state.nextAt=state.clock+2;showControls()}guideResume=false;
$("guideButton").focus({preventScroll:true})
}
function closeGuide(){if(typeof guide.close==="function")guide.close();else{guide.removeAttribute("open");closedGuide()}}
$("guideButton").addEventListener("click",openGuide);$("closeGuide").addEventListener("click",closeGuide);
guide.addEventListener("close",closedGuide);
guide.addEventListener("click",e=>{if(e.target!==guide)return;const b=guide.getBoundingClientRect();if(e.clientX<b.left||e.clientX>b.right||e.clientY<b.top||e.clientY>b.bottom)closeGuide()});
for(const eventName of ["pointerdown","touchstart","wheel","keydown"])window.addEventListener(eventName,stopDemo,{capture:true,passive:true});
function arrangeLabel(){
const q=project(pinWorld(state.active)),p=tag;
if(q.x<-4||q.x>W+4||q.y<4||q.y>H-4){p.style.visibility="hidden";$("leaders").style.visibility="hidden";return}
p.style.visibility="visible";$("leaders").style.visibility="visible";
let dir=q.x<W*.50?-1:1;
const separation=clamp(W*.095,30,98);
if(dir<0&&q.x-tagW<22&&W-q.x>tagW+32)dir=1;
if(dir>0&&W-q.x-tagW<22&&q.x>tagW+32)dir=-1;
const x=clamp(dir>0?q.x+separation:q.x-separation-tagW,12,W-tagW-12);
const below=q.y<H*.31||state.selected===7&&q.y>H*.61;
const y=clamp(q.y+(below?1:-1)*clamp(H*.114,30,63)-tagH*.5,58,H-tagH-57);
const lineX=dir>0?x:x+tagW,lineY=y+tagH*.5,elbow=lineX-dir*Math.min(18,Math.abs(lineX-q.x)*.38);
p.style.transform="translate("+x.toFixed(1)+"px,"+y.toFixed(1)+"px)";
$("leader").setAttribute("d","M"+q.x.toFixed(1)+" "+q.y.toFixed(1)+"L"+elbow.toFixed(1)+" "+lineY.toFixed(1)+"H"+lineX.toFixed(1));
for(const id of ["pinHalo","pinDot"]){$(id).setAttribute("cx",q.x.toFixed(1));$(id).setAttribute("cy",q.y.toFixed(1))}
}
function sizeWorld(){
const b=model.getBoundingClientRect();W=Math.max(1,b.width);H=Math.max(1,b.height);
dpr=gpu?Math.min(devicePixelRatio||1,1.65,1520/W,940/H)*resolutionFactor:Math.min(devicePixelRatio||1,1.35,740/W,475/H)*resolutionFactor;
const w=Math.max(1,Math.round(W*dpr)),h=Math.max(1,Math.round(H*dpr));
if(model.width!==w||model.height!==h){model.width=w;model.height=h}
rotation();tagW=tag.offsetWidth;tagH=tag.offsetHeight;drawPlate($("plate"),state.selected);
if(guide.open)[...guideGrid.children].forEach((btn,i)=>drawPlate(btn.firstElementChild,i))
}
function pointerPair(){
const p=[...pointers.values()];return p.length>=2?Math.hypot(p[0].x-p[1].x,p[0].y-p[1].y):0
}
function pickPart(x,y){
const id=(gpu||soft).pick(x,y);
if(id<0||id>state.step)return;
pauseBuild();const o=representative(id,x,y);selectPart(id,o,false);
if(o===membrane){
let best=Infinity;
for(const p of shellSamples){
const q=world(o,p);if(q[2]>sectionHeight())continue;const view=project(q);
const d=(view.x-x)**2+(view.y-y)**2-view.z*.12;
if(d<best){best=d;state.anchor=p}
}
}
if(o===cyt||o===smoothER){
let best=Infinity;
for(const path of o.paths)for(const p of path.points){
const q=world(o,p);if(q[2]>sectionHeight())continue;const pos=project(q),d=(pos.x-x)**2+(pos.y-y)**2;
if(d<best){best=d;state.anchor=p}
}
}
focusObject(o);showControls()
}
function attachModel(){
model.addEventListener("pointerdown",e=>{
if(e.button!==0&&e.pointerType!=="touch")return;
const p={x:e.clientX,y:e.clientY,sx:e.clientX,sy:e.clientY,moved:false,time:e.timeStamp,dx:0,dy:0};
pointers.set(e.pointerId,p);try{model.setPointerCapture(e.pointerId)}catch(_){}
if(pointers.size>1)for(const v of pointers.values())v.moved=true;
camera.spin=camera.tiltSpin=0;holdStill=state.clock+5;model.classList.add("dragging")
});
model.addEventListener("pointermove",e=>{
const p=pointers.get(e.pointerId);if(!p)return;
const prevDist=pointerPair(),dx=e.clientX-p.x,dy=e.clientY-p.y;
const moved=Math.hypot(e.clientX-p.sx,e.clientY-p.sy)>4;
if(pointers.size===1&&!p.moved&&!moved)return;
if(!p.moved&&moved)pauseBuild();p.moved=true;
const dt=clamp((e.timeStamp-p.time)/1000,.009,.09);
p.x=e.clientX;p.y=e.clientY;p.time=e.timeStamp;
if(pointers.size>1){
const d=pointerPair();if(prevDist>2&&d>2)zoomBy(d/prevDist);
p.dx=p.dy=0;pauseBuild()
}else{
const sensitivity=clamp(3.9/W,.0046,.010);
camera.tyaw+=dx*sensitivity;camera.tpitch=clamp(camera.tpitch+dy*sensitivity,-1.35,1.35);
p.dx=clamp(dx*sensitivity/dt,-2.1,2.1);p.dy=clamp(dy*sensitivity/dt,-1.6,1.6)
}
holdStill=state.clock+5
});
function finish(e,cancel){
const p=pointers.get(e.pointerId);if(!p)return;
pointers.delete(e.pointerId);
if(!cancel&&!p.moved){
const r=model.getBoundingClientRect();pickPart(e.clientX-r.left,e.clientY-r.top)
}else if(!cancel&&!pointers.size&&e.timeStamp-p.time<80&&!reduceMotion){camera.spin=p.dx*.43;camera.tiltSpin=p.dy*.36}
if(!pointers.size)model.classList.remove("dragging");
else for(const rest of pointers.values()){rest.moved=true;rest.dx=rest.dy=0}
}
model.addEventListener("pointerup",e=>finish(e,false));model.addEventListener("pointercancel",e=>finish(e,true));
model.addEventListener("lostpointercapture",e=>finish(e,true));
model.addEventListener("wheel",e=>{e.preventDefault();zoomBy(Math.exp(-clamp(e.deltaY*(e.deltaMode===1?16:1),-160,160)*.0018))},{passive:false});
model.addEventListener("keydown",e=>{
const k=e.key;if(!["ArrowLeft","ArrowRight","ArrowUp","ArrowDown","+","=","-","Home"].includes(k))return;
e.preventDefault();holdStill=state.clock+5;
if(k==="ArrowLeft")camera.tyaw-=.15;if(k==="ArrowRight")camera.tyaw+=.15;
if(k==="ArrowUp")camera.tpitch=clamp(camera.tpitch-.13,-1.35,1.35);if(k==="ArrowDown")camera.tpitch=clamp(camera.tpitch+.13,-1.35,1.35);
if(k==="+"||k==="=")zoomBy(1.2);if(k==="-")zoomBy(1/1.2);if(k==="Home")fitView()
})
}
let demoPhase=0;
function demoTick(dt){
const t=state.clock-state.demoStart;
if(t>=20.4){state.demoStart=state.clock;demoPhase=0;rebuild();return}
const step=clamp(Math.floor((t-1.05)/.84)+1,0,11);
if(step!==state.step)setStep(step);
if(t>2&&t<11.85&&!reduceMotion)camera.tyaw+=dt*.068;
if(t>=11.85&&demoPhase<1){demoPhase=1;setCut(true)}
if(t>=13.5&&demoPhase<2){demoPhase=2;selectPart(7,null,true)}
if(t>=16.45&&demoPhase<3){demoPhase=3;selectPart(1,null,true)}
if(t>=18.5&&demoPhase<4){demoPhase=4;setCut(false,false);fitView();selectPart(0)}
}
function tick(ms){
requestAnimationFrame(tick);
const elapsed=(ms-previousTime)/1000;previousTime=ms;const dt=clamp(elapsed,0,.12);
state.clock=ms/1000;motionT+=dt;
if(state.demo)demoTick(dt);
else if(state.playing&&state.step<11&&state.clock>=state.nextAt){
setStep(state.step+1);state.nextAt=state.clock+2.58
}
if(!pointers.size){
const drag=Math.exp(-dt*6);
camera.tyaw+=camera.spin*dt;camera.tpitch=clamp(camera.tpitch+camera.tiltSpin*dt,-1.35,1.35);
camera.spin*=drag;camera.tiltSpin*=drag;
if(!reduceMotion&&!state.demo&&!state.focus&&!state.cut&&state.clock>holdStill&&state.playing)camera.tyaw+=dt*.012
}
const ease=1-Math.exp(-dt*(pointers.size?22:5.8));
camera.yaw=mix(camera.yaw,camera.tyaw,ease);camera.pitch=mix(camera.pitch,camera.tpitch,ease);
camera.zoom=mix(camera.zoom,camera.tzoom,ease);camera.center=lerp3(camera.center,camera.goal,ease);
state.cutAmount=mix(state.cutAmount,state.cut?1:0,1-Math.exp(-dt*6.7));
if(Math.abs(state.cutAmount-(state.cut?1:0))<.001)state.cutAmount=state.cut?1:0;
rotation();
if(document.hidden)return;
if(elapsed>.067&&elapsed<.75)slowFrames++;else slowFrames=Math.max(0,slowFrames-.30);
if(slowFrames>13&&state.clock-lastResize>3&&resolutionFactor>.65){
resolutionFactor=Math.max(.64,resolutionFactor*.86);sizeWorld();lastResize=state.clock;slowFrames=0
}
if(!gpu&&ms-lastFrame<38)return;
(gpu||soft).render();lastFrame=ms;arrangeLabel()
}
function switchToSoftware(){
const next=model.cloneNode(false);model.replaceWith(next);model=next;gpu=null;soft=initSoftware(model)
}
try{gpu=initGPU(model)}catch(_){gpu=null}
if(!gpu)switchToSoftware();
else model.addEventListener("webglcontextlost",e=>{e.preventDefault();pointers.clear();switchToSoftware();attachModel();sizeWorld()},{once:true});
attachModel();showNote();showControls();sizeWorld();
if("ResizeObserver" in window){
const observer=new ResizeObserver(()=>sizeWorld());observer.observe(stage);
const paperObserver=new ResizeObserver(()=>drawPlate($("plate"),state.selected));paperObserver.observe($("plate").parentElement)
}else window.addEventListener("resize",sizeWorld);
document.addEventListener("visibilitychange",()=>{
if(document.hidden){lastHidden=performance.now()/1000;return}
if(lastHidden){const delta=performance.now()/1000-lastHidden;state.nextAt+=delta;state.demoStart+=delta;lastHidden=0;previousTime=performance.now()}
});
const started=performance.now();state.clock=started/1000;previousTime=started;state.demoStart=state.clock;state.nextAt=state.clock+1.30;
(gpu||soft).render();arrangeLabel();requestAnimationFrame(tick);
</script>
</body>
</html>
