Back to the app
The code
Build a Cell, Part by Part by Claude Sonnet 5.5
Exactly as the AI wrote it. Shown as text, so nothing runs on this page.
index.html
works · auto-checked (Checked by an automated pass. Not hand-played yet.)<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover">
<title>Build an Animal Cell</title>
<style>
*{box-sizing:border-box;-webkit-tap-highlight-color:transparent}
html,body{margin:0;height:100%;overflow:hidden;background:#05071a;color:#eaf2ff;font-family:system-ui,-apple-system,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;-webkit-user-select:none;user-select:none}
#app{position:fixed;top:0;left:0;right:0;bottom:0;background:radial-gradient(120% 85% at 50% 42%,#22377a 0%,#0e1438 55%,#04050f 100%)}
#stage{position:absolute;top:0;left:0;right:0;bottom:0}
#stage canvas{display:block;width:100%;height:100%;touch-action:none;cursor:grab}
.ov{position:absolute;pointer-events:none}
#top{top:0;left:0;right:0;padding:max(10px,env(safe-area-inset-top)) 12px 0;display:flex;justify-content:center}
#card{width:100%;max-width:580px;display:flex;gap:12px;align-items:flex-start;background:rgba(12,18,50,.74);-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);border:1px solid rgba(160,190,255,.28);border-radius:18px;padding:12px 14px;box-shadow:0 10px 30px rgba(0,0,0,.35)}
#dot{flex:0 0 auto;width:14px;height:14px;border-radius:50%;margin-top:6px;box-shadow:0 0 14px 2px currentColor}
#card .b{flex:1;min-width:0}
#nm{font-weight:800;font-size:18px}
#st{margin-left:8px;font-size:12px;opacity:.65;text-transform:uppercase;letter-spacing:.08em;white-space:nowrap}
#tx{margin:4px 0 0;font-size:16px;line-height:1.4;color:#dfe9ff}
#x{display:none;pointer-events:auto;flex:0 0 auto;width:44px;height:44px;margin:-8px -8px -8px 0;border:0;border-radius:50%;background:rgba(255,255,255,.14);color:#fff;font-size:20px;align-items:center;justify-content:center}
#tag{left:0;top:0;white-space:nowrap;padding:5px 11px;border-radius:12px;background:rgba(8,12,36,.88);border:2px solid #fff;font-weight:700;font-size:14px;opacity:0;transition:opacity .25s;will-change:transform}
#tag::after{content:"";position:absolute;left:50%;bottom:-9px;margin-left:-7px;border:7px solid transparent;border-top-color:rgba(8,12,36,.88)}
#bot{left:0;right:0;bottom:0;padding:0 12px max(12px,env(safe-area-inset-bottom));display:flex;flex-direction:column;align-items:center;gap:8px}
#hint,#demo{display:none;padding:7px 14px;border-radius:16px;background:rgba(12,18,50,.82);border:1px solid rgba(160,190,255,.3);font-size:14px;font-weight:600;text-align:center}
#demo{border-color:#ffd166;color:#ffd166}
body.demo #demo{display:block}
#chips{pointer-events:auto;display:flex;gap:8px;max-width:100%;overflow-x:auto;touch-action:pan-x;scrollbar-width:none;padding:2px}
#chips::-webkit-scrollbar{display:none}
.chip{flex:0 0 auto;min-height:42px;padding:0 14px;border-radius:21px;border:1px solid rgba(160,190,255,.3);background:rgba(12,18,50,.78);color:#eaf2ff;font:600 14px system-ui,sans-serif;display:flex;align-items:center;gap:8px}
.chip i{width:11px;height:11px;border-radius:50%}
.chip:disabled{opacity:.3}
.chip.sel{background:#2a3a86;border-color:#fff}
#panel{pointer-events:auto;width:100%;max-width:640px;background:rgba(12,18,50,.8);-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);border:1px solid rgba(160,190,255,.28);border-radius:20px;padding:8px 12px 12px}
#row{display:flex;align-items:center;gap:12px}
#sn{min-width:58px;text-align:right;font-weight:700;font-size:14px;opacity:.85}
#sl{flex:1;min-width:0;height:44px;margin:0;background:transparent;-webkit-appearance:none;appearance:none}
#sl::-webkit-slider-runnable-track{height:8px;border-radius:4px;background:linear-gradient(90deg,#5ee7c4,#7aa7ff)}
#sl::-webkit-slider-thumb{-webkit-appearance:none;width:30px;height:30px;margin-top:-11px;border-radius:50%;background:#fff;border:3px solid #7aa7ff;box-shadow:0 2px 8px rgba(0,0,0,.4)}
#sl::-moz-range-track{height:8px;border-radius:4px;background:linear-gradient(90deg,#5ee7c4,#7aa7ff)}
#sl::-moz-range-thumb{width:24px;height:24px;border-radius:50%;background:#fff;border:3px solid #7aa7ff}
#btns{display:grid;grid-template-columns:1fr 1fr 1.5fr;gap:8px;margin-top:4px}
.btn{min-height:50px;border-radius:14px;border:1px solid rgba(160,190,255,.4);background:linear-gradient(#35448f,#222c66);color:#fff;font:700 16px system-ui,sans-serif;display:flex;align-items:center;justify-content:center;gap:10px;padding:0 10px}
.btn:active{transform:scale(.97)}
#re{background:linear-gradient(#ffa24d,#ff6e3a);border-color:#ffd0a0}
.sw .k{position:relative;width:48px;height:28px;border-radius:14px;background:#46508a;transition:background .25s;flex:0 0 auto}
.sw .k::after{content:"";position:absolute;left:3px;top:3px;width:22px;height:22px;border-radius:50%;background:#fff;transition:transform .25s}
.sw[aria-checked=true] .k{background:#2fd3a3}
.sw[aria-checked=true] .k::after{transform:translateX(20px)}
#err{display:none;position:absolute;top:0;left:0;right:0;bottom:0;align-items:center;justify-content:center;text-align:center;padding:30px;font-size:18px;background:#05071a}
@media (max-height:520px){#chips{display:none}#tx{font-size:14px}#card{padding:8px 12px}}
</style>
</head>
<body>
<div id="app">
<div id="stage"></div>
<div class="ov" id="top"><div id="card"><i id="dot"></i><div class="b"><span id="nm"></span><span id="st"></span><p id="tx"></p></div><button id="x" aria-label="Show the whole cell">✕</button></div></div>
<div class="ov" id="tag"></div>
<div class="ov" id="bot">
<div id="demo">DEMO · touch anywhere to explore</div>
<div id="hint">Drag to turn · Pinch to zoom · Tap any part</div>
<div id="chips"></div>
<div id="panel">
<div id="row"><input id="sl" type="range" min="0" max="1000" value="0" aria-label="Scrub through the build"><span id="sn"></span></div>
<div id="btns">
<button class="btn" id="play">Pause</button>
<button class="btn" id="re">Rebuild</button>
<button class="btn sw" id="cut" role="switch" aria-checked="false"><span class="k"></span>Cut open</button>
</div>
</div>
</div>
<div id="err"></div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script>if(!window.THREE){document.write('<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/three.min.js"><\/script>');}</script>
<script>
(function(){
const $=id=>document.getElementById(id);
const fail=m=>{const e=$('err');e.textContent=m;e.style.display='flex';};
if(!window.THREE){fail('The 3D library could not load. Please check your connection and reload.');return;}
const T=THREE,clamp=(x,a,b)=>Math.min(b,Math.max(a,x)),V=(x,y,z)=>new T.Vector3(x,y,z);
let renderer;
try{renderer=new T.WebGLRenderer({antialias:true,alpha:true});}catch(e){fail('Your browser could not start 3D graphics (WebGL).');return;}
renderer.setPixelRatio(Math.min(window.devicePixelRatio||1,2));
renderer.outputEncoding=T.sRGBEncoding;
renderer.localClippingEnabled=true;
$('stage').appendChild(renderer.domElement);
const scene=new T.Scene(),camera=new T.PerspectiveCamera(42,1,.1,120);
scene.add(new T.HemisphereLight(0xdcecff,0x2b1a55,.8));
const dl=new T.DirectionalLight(0xffffff,.85);dl.position.set(4,7,9);scene.add(dl);
const pl=new T.PointLight(0xff8fd0,.8,60);pl.position.set(-7,-3,5);scene.add(pl);
const root=new T.Group();scene.add(root);
const plane=new T.Plane(V(0,0,-1),10);
/* ---------- helpers ---------- */
const N=11,CELL=V(3.3,2.7,2.9);
let seed=20260611;
const R=()=>{seed|=0;seed=seed+0x6D2B79F5|0;let t=Math.imul(seed^seed>>>15,1|seed);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296;};
const rr=(a,b)=>a+(b-a)*R();
const inEll=(x,y,z,k)=>(x/CELL.x)**2+(y/CELL.y)**2+(z/CELL.z)**2<k;
const pop=x=>{x=clamp(x,0,1);if(x<=0)return 0;const c=2,t=x-1;return 1+(c+1)*t*t*t+c*t*t;};
function rndIn(k,minD,c){for(let n=0;n<300;n++){const x=rr(-1,1)*CELL.x,y=rr(-1,1)*CELL.y,z=rr(-1,1)*CELL.z;if(inEll(x,y,z,k)&&(!c||V(x,y,z).distanceTo(c)>minD))return V(x,y,z);}return V(-2,-1,-1);}
function param(fn,nu,nv){const pos=[],idx=[],v=V(0,0,0);
for(let j=0;j<=nv;j++)for(let i=0;i<=nu;i++){fn(i/nu,j/nv,v);pos.push(v.x,v.y,v.z);}
const w=nu+1;
for(let j=0;j<nv;j++)for(let i=0;i<nu;i++){const a=j*w+i,b=a+1,c=a+w,d=c+1;idx.push(a,c,b,b,c,d);}
const geo=new T.BufferGeometry();geo.setAttribute('position',new T.Float32BufferAttribute(pos,3));geo.setIndex(idx);geo.computeVertexNormals();return geo;}
const sph=(r,a,b)=>new T.SphereGeometry(r,a||20,b||14);
/* ---------- parts registry ---------- */
const parts=[];
function addPart(id,name,short,color,dist,text,follow){
const p={id,name,short,color,dist,text,follow:follow||null,grp:new T.Group(),items:[],mats:[],pick:[],extra:[],prog:0,idx:parts.length,fo:null,custom:null,on:null,chip:null,step:parts.length?('Part '+parts.length+' of '+N):'Start'};
p.grp.visible=false;root.add(p.grp);parts.push(p);return p;}
function M(p,color,o){const m=new T.MeshStandardMaterial(Object.assign({color:color,emissive:color,emissiveIntensity:.14,roughness:.5,metalness:.05,side:T.DoubleSide,clippingPlanes:[plane]},o||{}));m.userData.e=m.emissiveIntensity;p.mats.push(m);return m;}
function mesh(p,geo,mat,parent){const m=new T.Mesh(geo,mat);m.userData.part=p;p.pick.push(m);(parent||p.grp).add(m);return m;}
function item(p,pos,o){o=o||{};const g=new T.Group();g.position.copy(pos);g.userData={b:pos.clone(),ph:R()*6.283,amp:o.amp==null?.09:o.amp,rot:o.rot||0,s:o.s||1,off:V(0,0,0)};p.items.push(g);p.grp.add(g);return g;}
const GL={transparent:true,depthWrite:false};
/* ---------- 0 membrane (see-through shell) ---------- */
const mem=addPart('membrane','Cell membrane','Cell membrane','#7fe6ff',0,'The cell membrane is a thin, stretchy skin that holds the jelly-like cytoplasm inside and decides what gets in and out.');
mem.fo=new T.Object3D();root.add(mem.fo);
const memU={uT:{value:0},uCut:{value:10},uS:{value:CELL},uC1:{value:new T.Color('#7fe6ff')},uC2:{value:new T.Color('#ff9ff3')}};
const memMesh=new T.Mesh(new T.SphereGeometry(1,72,48),new T.ShaderMaterial({transparent:true,depthWrite:false,side:T.DoubleSide,uniforms:memU,
vertexShader:'uniform float uT;uniform vec3 uS;varying vec3 vN;varying vec3 vW;varying vec3 vQ;void main(){vec3 q=position;float w=sin(q.x*2.1+uT*.8)*sin(q.y*1.8-uT*.7)*sin(q.z*2.4+uT*.9);q*=1.0+.05*w+.012*sin(uT*1.2);vec3 pw=q*uS;vec4 wp=modelMatrix*vec4(pw,1.0);vW=wp.xyz;vQ=q;vN=normalize(q/uS);gl_Position=projectionMatrix*viewMatrix*wp;}',
fragmentShader:'uniform vec3 uC1;uniform vec3 uC2;uniform float uCut;uniform float uT;varying vec3 vN;varying vec3 vW;varying vec3 vQ;void main(){if(vW.z>uCut)discard;vec3 n=normalize(vN);vec3 v=normalize(cameraPosition-vW);float f=pow(max(1.0-abs(dot(n,v)),0.0),2.2);float h=.5+.5*sin(vQ.x*10.0+uT*.8)*sin(vQ.y*10.0-uT*.6)*sin(vQ.z*10.0+uT*.5);vec3 c=mix(uC1,uC2,clamp(f*.6+.25*h*f,0.0,1.0));gl_FragColor=vec4(c,.05+.6*f+.12*h*f);}'}));
memMesh.renderOrder=10;memMesh.frustumCulled=false;root.add(memMesh);
const cyto=new T.Mesh(new T.SphereGeometry(1,40,28),new T.MeshBasicMaterial({color:'#4aa3ff',transparent:true,opacity:.07,depthWrite:false,side:T.BackSide,clippingPlanes:[plane]}));
cyto.scale.copy(CELL).multiplyScalar(.97);cyto.renderOrder=-1;root.add(cyto);
const memPick=new T.Mesh(new T.SphereGeometry(1,24,16),new T.MeshBasicMaterial({visible:false}));memPick.scale.copy(CELL);root.add(memPick);
const cap=new T.Group();cap.visible=false;root.add(cap);
cap.add(new T.Mesh(new T.CircleGeometry(1,72),new T.MeshBasicMaterial({color:'#8fd8ff',transparent:true,opacity:.07,depthWrite:false,side:T.DoubleSide})));
cap.add(new T.Mesh(new T.RingGeometry(.975,1,96),new T.MeshBasicMaterial({color:'#d4f6ff',transparent:true,opacity:.75,depthWrite:false,side:T.DoubleSide})));
/* ---------- 1 nucleus ---------- */
const NB=V(.2,.2,-.1);
const nuc=addPart('nucleus','Nucleus','Nucleus','#8a78ff',4.6,"The nucleus is the cell's control room: it stores the DNA, the instruction book for building and running the whole cell.");
let it=item(nuc,NB,{amp:.07,rot:.04});
mesh(nuc,new T.SphereGeometry(1,40,28),M(nuc,'#7b6cff',Object.assign({opacity:.36,roughness:.25},GL)),it);
const chm=M(nuc,'#ff7fd6',{roughness:.55,emissiveIntensity:.3});
mesh(nuc,new T.TorusKnotGeometry(.42,.07,150,8,2,3),chm,it);
const kn=mesh(nuc,new T.TorusKnotGeometry(.3,.055,120,8,3,5),chm,it);kn.rotation.set(1,.6,.2);
{const pm=M(nuc,'#d9d3ff',{emissiveIntensity:.3}),pg=sph(.05,10,8);
for(let i=0;i<18;i++){const y=1-2*(i+.5)/18,rad=Math.sqrt(1-y*y),a=i*2.4,s=mesh(nuc,pg,pm,it);s.position.set(Math.cos(a)*rad,y,Math.sin(a)*rad);}}
/* ---------- 2 nucleolus ---------- */
const nlo=addPart('nucleolus','Nucleolus','Nucleolus','#ff5c8a',2.8,'The nucleolus is a busy workshop inside the nucleus that builds the pieces needed to make ribosomes.',nuc);
it=item(nlo,V(NB.x-.3,NB.y+.12,NB.z-.3),{amp:.05});
{const nm=M(nlo,'#ff4f87',{roughness:.35,emissiveIntensity:.3});
mesh(nlo,sph(.3,28,20),nm,it);
for(let i=0;i<5;i++){const s=mesh(nlo,sph(.085,12,8),nm,it),a=i*1.26;s.position.set(Math.cos(a)*.3,Math.sin(a*1.7)*.22,Math.sin(a)*.3);}}
/* ---------- 3 rough ER ---------- */
const SH=[[1.22,2.0,4.1,.6,2.3,.07,3],[1.35,1.9,4.3,.5,2.4,.08,2.4],[1.48,2.2,4.2,.7,2.2,.07,3.4],[1.61,2.0,4.0,.6,2.3,.09,2.8],[1.74,2.1,4.1,.8,2.1,.08,3.1]];
function sheetPos(s,u,v,o){const ph=s[1]+(s[2]-s[1])*u,th=s[3]+(s[4]-s[3])*v,r=s[0]+s[5]*Math.sin(u*s[6]*6.283)*Math.sin(v*5.2+u*3);return o.set(r*Math.sin(th)*Math.cos(ph),r*Math.cos(th),r*Math.sin(th)*Math.sin(ph));}
const rer=addPart('rer','Rough endoplasmic reticulum','Rough ER','#1fb8aa',3.4,'The rough ER is a maze of folded sheets covered in ribosomes, where new proteins are built and checked.',nuc);
it=item(rer,NB,{amp:.05});
{const rm=M(rer,'#19b3a6',{roughness:.45,emissiveIntensity:.18});
SH.forEach(s=>mesh(rer,param((u,v,o)=>sheetPos(s,u,v,o),36,20),rm,it));
const fo=new T.Object3D();fo.position.copy(sheetPos(SH[2],.5,.5,V(0,0,0)));it.add(fo);rer.fo=fo;}
/* ---------- 4 smooth ER ---------- */
const ser=addPart('ser','Smooth endoplasmic reticulum','Smooth ER','#86e3a8',3.6,'The smooth ER is a network of bare tubes that makes fats for the cell and helps clear out harmful stuff.');
it=item(ser,V(1.7,-.3,-.7),{amp:.1,rot:.03});
{const sm=M(ser,'#86e3a8',{roughness:.45,emissiveIntensity:.2}),starts=[V(0,0,0)];
for(let k=0;k<9;k++){const pts=[starts[Math.floor(R()*starts.length)].clone()],d=V(R()-.5,R()-.5,R()-.5).normalize();
for(let j=0;j<6;j++){d.add(V(R()-.5,R()-.5,R()-.5).multiplyScalar(1.1)).normalize();const n=pts[pts.length-1].clone().addScaledVector(d,.4);if(n.length()>1.05)n.multiplyScalar(.85);pts.push(n);}
starts.push(pts[2].clone(),pts[4].clone());
mesh(ser,new T.TubeGeometry(new T.CatmullRomCurve3(pts),50,.07,8,false),sm,it);}}
/* ---------- 5 ribosomes (instanced) ---------- */
const rib=addPart('ribosomes','Ribosomes','Ribosomes','#ffc9a8',2.4,'Ribosomes are tiny protein factories that read the' + " cell's instructions and join building blocks into proteins.");
const NR=170,RB=[],RS=[],RP=[];
for(let i=0;i<NR;i++){let v;
if(i<105){const s=SH[Math.floor(R()*5)];v=sheetPos(s,rr(.04,.96),rr(.05,.95),V(0,0,0));v.addScaledVector(v.clone().normalize(),.05);}
else v=rndIn(.6,1.9,NB).sub(NB);
RB.push(v);RS.push(R()*.6);RP.push(R()*6.283);}
const rim=new T.InstancedMesh(sph(.055,8,6),M(rib,'#ffc9a8',{roughness:.5,emissiveIntensity:.22}),NR);
rim.frustumCulled=false;rim.instanceMatrix.setUsage(T.DynamicDrawUsage);rim.userData.part=rib;rib.pick.push(rim);rib.grp.add(rim);
{const fo=new T.Object3D();fo.position.copy(RB[0]);rib.grp.add(fo);rib.fo=fo;}
RB.forEach((v,i)=>{if(i%3===0)rib.extra.push(v);});
const DUM=new T.Object3D();
rib.custom=t=>{rib.grp.position.copy(rer.items[0].position);
for(let i=0;i<NR;i++){const b=RB[i],ip=clamp((rib.prog-RS[i])/.4,0,1),w=i<105?.012:.09,a=t*.8+RP[i];
DUM.position.set(b.x+Math.sin(a)*w,b.y+Math.sin(a*1.3+1)*w,b.z+Math.sin(a*.9+2)*w);
DUM.scale.setScalar(Math.max(1e-4,pop(ip)*(1+.2*Math.sin(t*3+RP[i]*3))));DUM.updateMatrix();rim.setMatrixAt(i,DUM.matrix);}
rim.instanceMatrix.needsUpdate=true;};
/* ---------- 6 Golgi ---------- */
const gol=addPart('golgi','Golgi apparatus','Golgi','#ffb347',3,"The Golgi apparatus is the cell's post office: it sorts, packs and labels proteins, then ships them out in little bubbles.");
it=item(gol,V(-1.8,-1.25,-.9),{amp:.08});it.rotation.set(.4,.3,.5);
{const gm=M(gol,'#ffb347',{roughness:.4,emissiveIntensity:.2});
for(let k=0;k<6;k++){const w=1-Math.abs(k-2.5)*.1,s=mesh(gol,sph(1,28,14),gm,it),c=k-2.5;s.scale.set(.68*w,.08,.44*w);s.position.set(.04*c*c,c*.2,0);s.rotation.z=c*.05;}
const bm=M(gol,'#ffd98a',{emissiveIntensity:.25});
[[.78,.4,.1],[-.78,-.35,-.1],[.7,-.5,.2]].forEach(a=>{const s=mesh(gol,sph(.08,12,8),bm,it);s.position.set(a[0],a[1],a[2]);});}
/* ---------- 7 mitochondria ---------- */
const mit=addPart('mito','Mitochondria','Mitochondria','#ff6b5e',2.7,'Mitochondria are the cell\'s power plants, turning food into the energy it needs to do everything.');
{const mo=M(mit,'#ff6b5e',Object.assign({opacity:.62,roughness:.3},GL)),mi=M(mit,'#ffc9a8',{roughness:.5,emissiveIntensity:.3}),mg=sph(1,28,18);
const zig=new T.CatmullRomCurve3(Array.from({length:9},(_,j)=>V(-.56+j*.14,j%2?.15:-.15,(j%3-1)*.06))),cg=new T.TubeGeometry(zig,60,.035,6,false);
[[1.2,-1.55,-.5,.3],[-.3,-2.0,-.6,1.1],[-2.2,1.0,-.6,2.0],[.9,-.3,-1.7,.6],[2.2,1.1,.6,2.6]].forEach(a=>{
const g=item(mit,V(a[0],a[1],a[2]),{amp:.12,rot:.1});g.rotation.set(a[3],a[3]*1.7,a[3]*.6);
const o=mesh(mit,mg,mo,g);o.scale.set(.72,.32,.32);mesh(mit,cg,mi,g);});}
/* ---------- 8 lysosomes ---------- */
const lys=addPart('lyso','Lysosomes','Lysosomes','#d8ef3f',2.7,'Lysosomes are the recycling crew: they hold strong chemicals that break down old parts and unwanted stuff.');
{const lo=M(lys,'#d8ef3f',Object.assign({opacity:.8,roughness:.3},GL)),ld=M(lys,'#7f9410',{roughness:.6,emissiveIntensity:.1}),lg=sph(.22,20,14),dg=sph(.05,8,6);
[[1.5,.2,-1.8],[-2.4,-.3,.6],[.6,1.9,-1.0],[-1.0,-.2,-1.9],[1.7,-1.5,.9]].forEach(a=>{
const g=item(lys,V(a[0],a[1],a[2]),{amp:.12});mesh(lys,lg,lo,g);
for(let i=0;i<4;i++){const s=mesh(lys,dg,ld,g),b=i*1.57;s.position.set(Math.cos(b)*.09,Math.sin(b*1.3)*.08,Math.sin(b)*.09);}});}
/* ---------- 9 vesicles ---------- */
const ves=addPart('vesicles','Vesicles','Vesicles','#8fd0ff',3.2,'Vesicles are tiny delivery bubbles that carry cargo around the cell and out through the membrane.');
{const vo=M(ves,'#8fd0ff',Object.assign({opacity:.5,roughness:.15},GL)),vc=M(ves,'#ffffff',{emissiveIntensity:.5}),vp=[[-1.0,-.9,-.3],[-2.7,-.8,-.5],[-2.3,-1.4,-.3],[-1.2,-2.0,-1.3]];
while(vp.length<14){const p=rndIn(.6,2.0,NB);vp.push([p.x,p.y,p.z]);}
vp.forEach(a=>{const g=item(ves,V(a[0],a[1],a[2]),{amp:.22,s:rr(.8,1.25)});mesh(ves,sph(.13,16,12),vo,g);mesh(ves,sph(.045,8,6),vc,g);});}
/* ---------- 10 centrioles ---------- */
const CB=V(1.5,1,-.6);
const cen=addPart('centriole','Centrioles','Centrioles','#b48cff',1.8,'Centrioles are a pair of tiny barrels that help organize the cell\'s skeleton and pull chromosomes apart when a cell divides.');
it=item(cen,CB,{amp:.06,rot:.2,s:1.8});
{const cm=M(cen,'#b48cff',{roughness:.4,emissiveIntensity:.3}),rod=new T.CylinderGeometry(.022,.022,.46,6),ring=new T.TorusGeometry(.105,.014,6,20);
const barrel=()=>{const b=new T.Group();
for(let k=0;k<9;k++){const a=k/9*6.2832,r=mesh(cen,rod,cm,b);r.position.set(Math.cos(a)*.1,0,Math.sin(a)*.1);}
[-.23,.23].forEach(y=>{const r=mesh(cen,ring,cm,b);r.rotation.x=Math.PI/2;r.position.y=y;});return b;};
it.add(barrel());const b2=barrel();b2.rotation.x=Math.PI/2;b2.position.set(0,-.12,.36);it.add(b2);}
/* ---------- 11 cytoskeleton (instanced filaments) ---------- */
const cyt=addPart('cyto','Cytoskeleton','Cytoskeleton','#a5d2ff',6.2,'The cytoskeleton is a web of thin threads and tubes that gives the cell its shape and works like roads for moving cargo.',cen);
it=item(cyt,CB,{amp:.03});
{const SEG=14,NF=56,sm=new T.InstancedMesh(new T.CylinderGeometry(.02,.02,1,5,1),M(cyt,'#a5d2ff',{roughness:.4,emissiveIntensity:.4}),NF*SEG),D=new T.Object3D(),rad=[CELL.x*.9,CELL.y*.9,CELL.z*.9];
sm.frustumCulled=false;it.add(sm);sm.userData.part=cyt;cyt.pick.push(sm);let n=0;
cyt.extra.push(CB.clone());
for(let f=0;f<NF;f++){const d=V(R()-.5,R()-.5,R()-.5).normalize(),dd=[d.x,d.y,d.z],cc=[CB.x,CB.y,CB.z];let a=0,b=0,c=-1;
for(let k=0;k<3;k++){const r2=rad[k]*rad[k];a+=dd[k]*dd[k]/r2;b+=2*cc[k]*dd[k]/r2;c+=cc[k]*cc[k]/r2;}
const tt=(-b+Math.sqrt(Math.max(0,b*b-4*a*c)))/(2*a),E=d.clone().multiplyScalar(tt*rr(.7,1)),pr=V(R()-.5,R()-.5,R()-.5).multiplyScalar(rr(.4,1));
const cv=new T.CatmullRomCurve3([V(0,0,0),E.clone().multiplyScalar(.33).add(pr),E.clone().multiplyScalar(.66).addScaledVector(pr,-.6),E]),pts=cv.getPoints(SEG);
if(f%4===0)cyt.extra.push(CB.clone().add(pts[7]));
for(let j=0;j<SEG;j++){const A=pts[j],B=pts[j+1],dir=B.clone().sub(A),len=dir.length(),w=1.5-j/SEG*.8;
D.position.copy(A).add(B).multiplyScalar(.5);D.quaternion.setFromUnitVectors(V(0,1,0),dir.normalize());D.scale.set(w,len*1.02,w);D.updateMatrix();sm.setMatrixAt(n++,D.matrix);}}}
parts.forEach(p=>{if(!p.fo&&p.items.length)p.fo=p.items[0];});
scene.updateMatrixWorld(true);
const byId=id=>parts.find(p=>p.id===id);
/* ---------- camera + state ---------- */
const cam={th:.5,ph:.22,r:11,x:0,y:0,z:0},goal={th:.5,ph:.22,r:11,x:0,y:0,z:0};
let homeR=11,minR=1.5;
let build=0,playing=true,hold=1.4,speed=1/3.4,sel=null,selObj=null,cut=false,cutC=10,cutGoal=10,lastInput=-1e9,hintOn=true,demo=null,doneAt=0,wasDone=false;
const DONE={name:'Your cell is alive!',short:'',color:'#ffffff',text:'Drag to spin it, pinch to zoom, and tap any part to fly to it.',step:'Complete',idx:-1};
const tag=$('tag'),hint=$('hint'),ptrs=new Map(),tp=V(0,0,0);
function resize(){const w=window.innerWidth,h=window.innerHeight;renderer.setSize(w,h);camera.aspect=w/h;camera.updateProjectionMatrix();
const tn=Math.tan(camera.fov*Math.PI/360);homeR=Math.max(4/tn,3.7/(tn*camera.aspect));if(!sel&&!cut)goal.r=homeR;}
resize();cam.r=goal.r=homeR;
window.addEventListener('resize',resize);
const wrap=a=>a-Math.PI*2*Math.round(a/(Math.PI*2));
function selectPart(p,o){if(p.idx>0&&p.prog<.5)return;sel=p;selObj=o||p.fo;goal.r=p.idx?p.dist:homeR*.72;playing=false;hintOn=false;lastInput=performance.now();}
function clearSel(){sel=null;selObj=null;goal.r=homeR;}
function cutSet(v){cut=v;cutGoal=v?0:10;$('cut').setAttribute('aria-checked',v?'true':'false');
if(v){sel=null;selObj=null;goal.th=cam.th+wrap(.35-cam.th);goal.ph=.2;goal.r=homeR*.95;}}
function rebuild(){build=0;playing=true;hold=1;sel=null;selObj=null;cutSet(false);goal.r=homeR;hintOn=true;speed=1/3.4;}
function curPart(){if(sel)return sel;if(build<=0)return parts[0];
if(build>=N-1e-4)return(performance.now()-doneAt>6000)?DONE:parts[N];return parts[clamp(Math.ceil(build),1,N)];}
/* ---------- input ---------- */
const cv=renderer.domElement;let tapInfo=null,pinchD=0;
const dist2=()=>{const a=[...ptrs.values()];return a.length<2?0:Math.hypot(a[0].x-a[1].x,a[0].y-a[1].y);};
cv.addEventListener('contextmenu',e=>e.preventDefault());
cv.addEventListener('pointerdown',e=>{try{cv.setPointerCapture(e.pointerId);}catch(_){}
ptrs.set(e.pointerId,{x:e.clientX,y:e.clientY});lastInput=performance.now();
if(ptrs.size===1)tapInfo={t:performance.now(),moved:0};else{tapInfo=null;pinchD=dist2();}});
cv.addEventListener('pointermove',e=>{const p=ptrs.get(e.pointerId);if(!p)return;
const dx=e.clientX-p.x,dy=e.clientY-p.y;p.x=e.clientX;p.y=e.clientY;lastInput=performance.now();
if(ptrs.size===1){if(tapInfo)tapInfo.moved+=Math.abs(dx)+Math.abs(dy);goal.th-=dx*.0065;goal.ph=clamp(goal.ph+dy*.0065,-1.35,1.35);if(tapInfo&&tapInfo.moved>10)hintOn=false;}
else if(ptrs.size===2){const d=dist2();if(pinchD>0&&d>0)goal.r=clamp(goal.r*pinchD/d,minR,homeR*1.5);pinchD=d;hintOn=false;}});
const up=e=>{if(!ptrs.has(e.pointerId))return;ptrs.delete(e.pointerId);if(ptrs.size<2)pinchD=0;
if(tapInfo&&e.type==='pointerup'&&tapInfo.moved<10&&performance.now()-tapInfo.t<500)doPick(e.clientX,e.clientY);
if(ptrs.size===0)tapInfo=null;};
cv.addEventListener('pointerup',up);cv.addEventListener('pointercancel',up);
cv.addEventListener('wheel',e=>{e.preventDefault();goal.r=clamp(goal.r*Math.exp(e.deltaY*.0012),minR,homeR*1.5);lastInput=performance.now();hintOn=false;},{passive:false});
const ray=new T.Raycaster(),nd=new T.Vector2();
const shownObj=o=>{while(o){if(!o.visible)return false;o=o.parent;}return true;};
const itemOf=(o,p)=>{while(o.parent&&o.parent!==p.grp)o=o.parent;return o;};
function doPick(cx,cy){
const rc=cv.getBoundingClientRect();nd.set((cx-rc.left)/rc.width*2-1,-((cy-rc.top)/rc.height)*2+1);ray.setFromCamera(nd,camera);
const list=[];for(let i=1;i<=N;i++)if(parts[i].prog>.5)for(const m of parts[i].pick)list.push(m);
const hits=ray.intersectObjects(list,false);
for(const h of hits){if(h.point.z>cutC||!shownObj(h.object))continue;const p=h.object.userData.part;selectPart(p,h.object.isInstancedMesh?p.fo:itemOf(h.object,p));return;}
let best=null,bd=1e9;
for(let i=1;i<=N;i++){const p=parts[i];if(p.prog<=.5)continue;
const cand=p.items.filter(o=>o.visible).map(o=>[o,o.position]).concat(p.extra.map(v=>[p.fo,v]));
for(const c of cand){tp.copy(c[1]);p.grp.localToWorld(tp);if(tp.z>cutC)continue;tp.project(camera);
const sx=(tp.x*.5+.5)*rc.width+rc.left,sy=(-tp.y*.5+.5)*rc.height+rc.top,d=Math.hypot(sx-cx,sy-cy);if(d<bd){bd=d;best=[p,c[0]];}}}
if(best&&bd<38){selectPart(best[0],best[1]);return;}
const mh=ray.intersectObject(memPick,false).find(h=>h.point.z<=cutC);
if(mh){selectPart(parts[0]);return;}
clearSel();
}
/* ---------- UI wiring ---------- */
const chips=$('chips');
parts.forEach(p=>{const b=document.createElement('button');b.className='chip';b.disabled=true;
const i=document.createElement('i');i.style.background=p.color;b.appendChild(i);b.appendChild(document.createTextNode(p.short));
b.onclick=()=>selectPart(p);chips.appendChild(b);p.chip=b;});
$('x').onclick=()=>clearSel();
$('re').onclick=()=>rebuild();
$('cut').onclick=()=>cutSet(!cut);
$('play').onclick=()=>{if(playing)playing=false;else if(build>=N-1e-4)rebuild();else{playing=true;hold=0;sel=null;selObj=null;goal.r=homeR;}};
$('sl').addEventListener('input',()=>{build=$('sl').value/1000*N;playing=false;hold=0;sel=null;selObj=null;goal.r=homeR;hintOn=false;lastInput=performance.now();});
let cardP=null,xVis=null,hintVis=null,pbTxt='';
function ui(shown){
if(shown!==cardP){cardP=shown;$('dot').style.background=shown.color;$('dot').style.color=shown.color;$('nm').textContent=shown.name;$('st').textContent=shown.step;$('tx').textContent=shown.text;tag.textContent=shown.short||'';tag.style.borderColor=shown.color;}
const xv=!!sel;if(xv!==xVis){xVis=xv;$('x').style.display=xv?'flex':'none';}
const hv=hintOn&&build>=N-1e-4&&!sel&&!demo;if(hv!==hintVis){hintVis=hv;hint.style.display=hv?'block':'none';}
const pb=playing?'Pause':(build>=N-1e-4?'Replay':'Play');if(pb!==pbTxt){pbTxt=pb;$('play').textContent=pb;}
$('sl').value=Math.round(build/N*1000);
$('sn').textContent=build<=0?'Empty':Math.min(N,Math.ceil(build-1e-6))+' / '+N;
for(const p of parts){const on=p.idx===0||p.prog>.5;if(p.on!==on){p.on=on;p.chip.disabled=!on;}p.chip.classList.toggle('sel',p===sel);}
if(shown.idx>0&&shown.fo){const o=(shown===sel&&selObj)?selObj:shown.fo;o.getWorldPosition(tp);const hid=tp.z>cutC+.05||shown.prog<.05;tp.project(camera);
const x=clamp((tp.x*.5+.5)*window.innerWidth,60,window.innerWidth-60),y=clamp((-tp.y*.5+.5)*window.innerHeight,90,window.innerHeight-90);
tag.style.opacity=hid?0:1;tag.style.transform='translate('+x.toFixed(1)+'px,'+y.toFixed(1)+'px) translate(-50%,-130%)';}
else tag.style.opacity=0;
}
/* ---------- demo (#demo) ---------- */
function runDemo(dt){const d=demo;d.t+=dt;const at=(s,f)=>{if(d.t>=s&&!d.f[s]){d.f[s]=1;f();}};
at(0,()=>{rebuild();hold=.3;speed=1.3;});
at(9.3,()=>selectPart(byId('mito')));
at(12.6,()=>selectPart(byId('nucleus')));
at(15.8,()=>{clearSel();cutSet(true);});
at(19.2,()=>cutSet(false));
if(d.t>19.4&&d.t<20.8){build=N*(1-(d.t-19.4)/1.4);playing=false;hold=0;}
if(d.t>=21){d.t=0;d.f={};}}
function endDemo(){if(!demo)return;demo=null;document.body.classList.remove('demo');speed=1/3.4;sel=null;selObj=null;cutSet(false);goal.r=homeR;build=N;playing=false;hold=0;hintOn=true;lastInput=performance.now();}
['pointerdown','touchstart','mousedown','wheel','keydown'].forEach(ev=>window.addEventListener(ev,endDemo,{capture:true,passive:true}));
if(/#demo$/.test(window.location.href)){demo={t:0,f:{}};document.body.classList.add('demo');}
/* ---------- main loop ---------- */
let lastT=performance.now();
function frame(now){
requestAnimationFrame(frame);
const dt=Math.min(.05,Math.max(0,(now-lastT)/1000));lastT=now;const t=now/1000;
if(demo)runDemo(dt);
if(playing){if(hold>0)hold-=dt;else{build=Math.min(N,build+dt*speed);if(build>=N)playing=false;}}
const comp=build>=N-1e-4;if(comp&&!wasDone)doneAt=performance.now();wasDone=comp;
cutC+=(cutGoal-cutC)*(1-Math.exp(-dt*3.4));if(Math.abs(cutC-cutGoal)<.003)cutC=cutGoal;
plane.constant=cutC;memU.uCut.value=cutC;memU.uT.value=t;
cap.visible=cutC<CELL.z*.98;
if(cap.visible){const k=Math.sqrt(Math.max(0,1-(cutC/CELL.z)**2));cap.position.z=cutC;cap.scale.set(CELL.x*k,CELL.y*k,1);}
const shown=curPart();
for(let pi=1;pi<=N;pi++){const p=parts[pi];p.prog=clamp(build-(pi-1),0,1);
const k=p.items.length,fol=p.follow?p.follow.items[0].userData.off:null;
for(let i=0;i<k;i++){const m=p.items[i],u=m.userData,st=k>1?i/k*.6:0,du=k>1?.4:1,ip=clamp((p.prog-st)/du,0,1);
m.visible=ip>0;if(!m.visible)continue;
const a=t*.55+u.ph;u.off.set(Math.sin(a)*u.amp,Math.sin(a*.83+1.7)*u.amp,Math.sin(a*.67+3.1)*u.amp);
m.position.copy(u.b).add(u.off);if(fol)m.position.add(fol);
m.rotation.y+=dt*u.rot;
m.scale.setScalar(Math.max(1e-4,u.s*pop(ip)*(1+.04*Math.sin(t*1.9+u.ph*2))));}
p.grp.visible=p.prog>0;
if(p.custom)p.custom(t);
const glow=(p===shown)?.3+.2*Math.sin(t*4):0;
for(const m of p.mats)m.emissiveIntensity=m.userData.e*(1+.5*Math.sin(t*1.5+pi))+glow;}
if(sel&&sel.idx>0){(selObj||sel.fo).getWorldPosition(tp);goal.x=tp.x;goal.y=tp.y;goal.z=tp.z;}
else if(!sel&&playing&&hold<=0&&!cut&&now-lastInput>3000&&shown.idx>0&&shown.fo){shown.fo.getWorldPosition(tp);goal.x=tp.x*.35;goal.y=tp.y*.35;goal.z=tp.z*.35;}
else{goal.x=goal.y=goal.z=0;}
if(!sel&&!cut&&ptrs.size===0&&now-lastInput>2500)goal.th+=dt*.12;
const kk=1-Math.exp(-dt*4.2);
cam.th+=(goal.th-cam.th)*kk;cam.ph+=(goal.ph-cam.ph)*kk;cam.r+=(goal.r-cam.r)*kk;cam.x+=(goal.x-cam.x)*kk;cam.y+=(goal.y-cam.y)*kk;cam.z+=(goal.z-cam.z)*kk;
camera.position.set(cam.x+cam.r*Math.sin(cam.th)*Math.cos(cam.ph),cam.y+cam.r*Math.sin(cam.ph),cam.z+cam.r*Math.cos(cam.th)*Math.cos(cam.ph));
camera.lookAt(cam.x,cam.y,cam.z);
renderer.render(scene,camera);
ui(shown);
}
requestAnimationFrame(frame);
})();
</script>
</body>
</html>
