Download brain_lab/static/brain-scene.js from Chungulus/brain-lab: direct link, hf CLI and curl.
- Browser
- Download file 22.8 kB
-
https://huggingface.co/spaces/Chungulus/brain-lab/resolve/main/brain_lab/static/brain-scene.js
- Command line
-
hf download hf://spaces/Chungulus/brain-lab/brain_lab/static/brain-scene.js
-
curl -L -o brain-scene.js https://huggingface.co/spaces/Chungulus/brain-lab/resolve/main/brain_lab/static/brain-scene.js
22.8 kB
| import {takeBrainFocus} from './brain-focus.js?v=brain-circuit-47'; | |
| import * as THREE from './vendor/three.module.js'; | |
| import {$,api,state,card,escape} from './common.js'; | |
| let meshPromise; | |
| export const brainMesh=()=>meshPromise??=fetch('/static/brain-model.json').then(r=>{if(!r.ok)throw Error('Brain geometry is unavailable.');return r.json()}); | |
| const palette={frontal:'#d6ae68',parietal:'#ad96cf',temporal:'#80b3ce',occipital:'#70b79d'}; | |
| const location={cortex:[-45,-20,45],frontal:[-42,40,20],parietal:[-40,-35,55],occipital:[-28,-84,17],temporal:[-55,-15,-5],motor:[-39,-10,55],sensory:[-42,-25,55],association:[-46,-42,32],broca:[-48,20,12],wernicke:[-50,-40,6],angular:[-42,-54,36],hippocampus:[-25,-27,-10],amygdala:[-23,3,-12],limbic:[-23,-17,-12],thalamus:[-9,-14,8],basal:[-19,1,12],callosum:[0,-9,29],cerebellum:[-23,-62,-30],brainstem:[0,-36,-44],medulla:[0,-41,-61],ras:[0,-37,-38],pons:[0,-32,-39],hypothalamus:[0,-3,-8],pituitary:[0,8,-28],pineal:[0,-30,9],chiasm:[0,12,-19],ventricles:[-7,-12,20]}; | |
| function point(p){return new THREE.Vector3(p[0]/90,(p[2]-8)/90,-(p[1]+20)/90)} | |
| export async function brainScene(canvas,{onSelect=()=>{},simple=false}={}){ | |
| const model=await brainMesh();if(!canvas.isConnected)return {destroy(){},mode(){},select(){},reset(){},labels(){}}; | |
| const renderer=new THREE.WebGLRenderer({canvas,antialias:true,alpha:false});renderer.setPixelRatio(Math.min(devicePixelRatio,2));renderer.setClearColor('#132a29');renderer.outputColorSpace=THREE.SRGBColorSpace;renderer.toneMapping=THREE.ACESFilmicToneMapping;renderer.toneMappingExposure=1.15; | |
| const scene=new THREE.Scene(),camera=new THREE.PerspectiveCamera(37,1,.1,100);camera.position.set(0,.15,4.8);camera.lookAt(0,0,0); | |
| scene.add(new THREE.HemisphereLight('#fff5dc','#345b5c',2.5));const lamp=new THREE.DirectionalLight('#fff4de',3.5);lamp.position.set(-3,4,5);scene.add(lamp);const rim=new THREE.DirectionalLight('#86b4d5',2);rim.position.set(4,1,-3);scene.add(rim); | |
| const brain=new THREE.Group();scene.add(brain);brain.rotation.set(.05,1.35,0); | |
| const pickable=[],hemispheres=[],deep=[],materials=[],geometries=[],sprites=[];let alive=true,mode='outside',selected='frontal',showLabels=false,raf,drag=null,autoorbit=false,cortexOpacity=1,spread=.8,isolated=false,route=null,routeDot=null; | |
| function material(color,opts={}){const m=new THREE.MeshStandardMaterial({color,roughness:.66,metalness:.05,...opts});materials.push(m);return m} | |
| function addMesh(id,geometry,color,isDeep=true){geometries.push(geometry);const mesh=new THREE.Mesh(geometry,material(color));mesh.userData={id,deep:isDeep};brain.add(mesh);pickable.push(mesh);if(isDeep)deep.push(mesh);return mesh} | |
| for(let side=0;side<2;side++){ | |
| const start=side*model.hemisphere_count,end=start+model.hemisphere_count,positions=new Float32Array(model.hemisphere_count*3),colors=new Float32Array(positions.length); | |
| for(let i=start;i<end;i++){const p=point(model.vertices[i]);p.toArray(positions,(i-start)*3);new THREE.Color(palette[model.regions[i]]).toArray(colors,(i-start)*3)} | |
| const indices=model.faces.filter(f=>f[0]>=start&&f[0]<end).flatMap(f=>f.map(v=>v-start)),g=new THREE.BufferGeometry();g.setAttribute('position',new THREE.BufferAttribute(positions,3));g.setAttribute('color',new THREE.BufferAttribute(colors,3));g.setIndex(indices);g.computeVertexNormals();geometries.push(g); | |
| const normals=g.getAttribute('normal'),sum=new Float32Array(positions.length),counts=new Uint16Array(model.hemisphere_count),shade=new Float32Array(model.hemisphere_count);for(let j=0;j<indices.length;j+=3){const tri=indices.slice(j,j+3);for(const a of tri)for(const b of tri)if(a!==b){counts[a]++;for(let k=0;k<3;k++)sum[a*3+k]+=positions[b*3+k]}}for(let j=0;j<shade.length;j++){let curvature=0;for(let k=0;k<3;k++)curvature+=(positions[j*3+k]-sum[j*3+k]/Math.max(1,counts[j]))*normals.array[j*3+k];shade[j]=Math.max(.48,Math.min(1.12,.88+curvature*11))}g.userData.shade=shade; | |
| const m=material('#ffffff',{vertexColors:true,transparent:true,opacity:1,side:THREE.DoubleSide}),mesh=new THREE.Mesh(g,m);mesh.userData={id:'cortex',deep:false,start};brain.add(mesh);hemispheres.push(mesh);pickable.push(mesh); | |
| } | |
| function ellipsoid(id,p,scale,color,ripple=false){const g=new THREE.SphereGeometry(1,48,32);if(ripple){const a=g.getAttribute('position');for(let i=0;i<a.count;i++){const x=a.getX(i),y=a.getY(i),z=a.getZ(i),factor=1+.045*Math.sin(Math.atan2(z,x)*27+y*22);a.setXYZ(i,x*factor,y*factor,z*factor)}g.computeVertexNormals()}const mesh=addMesh(id,g,color);mesh.position.copy(point(p));mesh.scale.set(scale[0]/90,scale[2]/90,scale[1]/90);return mesh} | |
| function tube(id,path,r,color){const curve=new THREE.CatmullRomCurve3(path.map(point));return addMesh(id,new THREE.TubeGeometry(curve,40,r/90,10,false),color)} | |
| for(const sign of [-1,1]){ | |
| ellipsoid('cerebellum',[sign*19,-64,-30],[24,25,17],'#bc98af',true); | |
| ellipsoid('thalamus',[sign*9,-14,8],[9,13,8],'#92b7cc');ellipsoid('basal',[sign*18,1,12],[9,15,12],'#b59ccf'); | |
| ellipsoid('amygdala',[sign*23,3,-12],[6,6,7],'#e4957c'); | |
| tube('hippocampus',[[sign*23,2,-12],[sign*28,-13,-16],[sign*28,-35,-11],[sign*24,-46,-3]],4.1,'#e7bd6c'); | |
| tube('ventricles',[[sign*7,25,16],[sign*7,8,23],[sign*9,-15,21],[sign*12,-37,14]],3.7,'#75c9dd'); | |
| // Both crossed and uncrossed strands illustrate partial optic-fiber crossing. | |
| tube('chiasm',[[sign*18,27,-20],[sign*7,15,-19],[-sign*13,0,-17]],1.5,'#77c4a5'); | |
| tube('chiasm',[[sign*18,27,-20],[sign*12,13,-19],[sign*13,0,-17]],1,'#9cd8b7'); | |
| } | |
| tube('callosum',[[0,31,10],[0,24,26],[0,0,31],[0,-31,27],[0,-41,13]],5,'#b5d3a2'); | |
| ellipsoid('hypothalamus',[0,-3,-8],[8,8,6],'#e5a88b');ellipsoid('pituitary',[0,8,-28],[5,5,5],'#d98fb1');tube('pituitary',[[0,-3,-10],[0,4,-19],[0,8,-24]],1.2,'#d98fb1');ellipsoid('pineal',[0,-30,9],[3,4,3],'#c1a2d7'); | |
| tube('brainstem',[[0,-20,-14],[0,-30,-32],[0,-40,-50],[0,-41,-73]],8,'#99b2a4');ellipsoid('pons',[0,-31,-37],[12,10,10],'#a6c6a4');tube('medulla',[[0,-40,-48],[0,-41,-65],[0,-40,-79]],5.6,'#86aaa0');tube('ras',[[0,-34,-23],[0,-35,-38],[0,-39,-55]],2,'#ddb768'); | |
| for(const p of state.anatomy){const c=document.createElement('canvas');c.width=c.height=96;const x=c.getContext('2d');x.fillStyle='#f8f5dd';x.beginPath();x.arc(48,48,37,0,Math.PI*2);x.fill();x.fillStyle='#234b43';x.font='bold 38px sans-serif';x.textAlign='center';x.fillText(p.number,48,61);const texture=new THREE.CanvasTexture(c),mat=new THREE.SpriteMaterial({map:texture,depthTest:false,transparent:true});const sprite=new THREE.Sprite(mat);sprite.position.copy(point(location[p.id]));sprite.scale.set(.12,.12,.12);sprite.userData={id:p.id,deep:p.view==='inner',marker:true};brain.add(sprite);sprites.push(sprite);pickable.push(sprite);} | |
| const raycaster=new THREE.Raycaster();const pointer=new THREE.Vector2(); | |
| function recolor(){const related={limbic:['hippocampus','amygdala','thalamus'],brainstem:['brainstem','pons','medulla','ras'],cortex:['cortex']}[selected]||[selected]; | |
| for(const mesh of deep){mesh.material.emissive.set(related.includes(mesh.userData.id)?'#634511':'#000000');mesh.material.emissiveIntensity=related.includes(mesh.userData.id)?.55:0;mesh.material.transparent=true;mesh.material.opacity=isolated&&!related.includes(mesh.userData.id)?.12:mode==='outside'&&cortexOpacity>.9&&!['cerebellum','brainstem','pons','medulla'].includes(mesh.userData.id)?.12:1} | |
| for(const mesh of hemispheres){mesh.visible=mode!=='half'||mesh.userData.start===0;mesh.position.x=mode==='split'?(mesh.userData.start?spread:-spread):0;mesh.material.opacity=(mode==='inside'?.11:isolated?.2:1)*cortexOpacity;mesh.material.depthWrite=mesh.material.opacity>.9;const colors=mesh.geometry.getAttribute('color');for(let i=0;i<model.hemisphere_count;i++){const r=model.regions[i+mesh.userData.start],color=new THREE.Color(palette[r]);const v=model.vertices[i+mesh.userData.start],loc=location[selected],near=loc&&Math.pow((v[0]-loc[0])/17,2)+Math.pow((v[1]-loc[1])/17,2)+Math.pow((v[2]-loc[2])/17,2)<1;if(selected==='cortex'||selected===r||near)color.lerp(new THREE.Color('#ffe2a0'),.55);color.multiplyScalar(mesh.geometry.userData.shade[i]);color.toArray(colors.array,i*3)}colors.needsUpdate=true} | |
| for(const sprite of sprites){sprite.position.copy(point(location[sprite.userData.id]));if(mode==='split'&&!sprite.userData.deep)sprite.position.x+=location[sprite.userData.id][0]<0?-spread:spread;sprite.visible=!simple&&(showLabels||sprite.userData.id===selected)&&(!sprite.userData.deep||mode!=='outside'||['cerebellum','brainstem','medulla','pons','ras'].includes(sprite.userData.id))} | |
| } | |
| function select(id,notify=true){selected=id;if(mode==='outside'&&state.anatomy.find(p=>p.id===id)?.view==='inner'&&!['cerebellum','brainstem','medulla','pons','ras'].includes(id))mode='inside';recolor();if(notify)onSelect(id)} | |
| const down=e=>{canvas.setPointerCapture(e.pointerId);drag={x:e.clientX,y:e.clientY,lastX:e.clientX,lastY:e.clientY,moved:false}}; | |
| const move=e=>{if(!drag)return;const dx=e.clientX-drag.lastX,dy=e.clientY-drag.lastY;brain.rotation.y+=dx*.007;brain.rotation.x=Math.max(-1.3,Math.min(1.3,brain.rotation.x+dy*.007));drag.moved ||=Math.hypot(e.clientX-drag.x,e.clientY-drag.y)>5;drag.lastX=e.clientX;drag.lastY=e.clientY}; | |
| const up=e=>{if(drag&&!drag.moved){const r=canvas.getBoundingClientRect();pointer.set((e.clientX-r.left)/r.width*2-1,-(e.clientY-r.top)/r.height*2+1);raycaster.setFromCamera(pointer,camera);const objects=pickable.filter(o=>o.visible&&(mode!=='inside'||o.userData.deep));const hit=raycaster.intersectObjects(objects,false)[0];if(hit){let id=hit.object.userData.id;if(id==='cortex'&&hit.face)id=model.regions[hit.object.userData.start+hit.face.a];select(id)}}drag=null}; | |
| const wheel=e=>{e.preventDefault();camera.position.z=Math.max(3,Math.min(8,camera.position.z+e.deltaY*.003))};canvas.addEventListener('pointerdown',down);canvas.addEventListener('pointermove',move);canvas.addEventListener('pointerup',up);canvas.addEventListener('pointercancel',()=>drag=null);canvas.addEventListener('wheel',wheel,{passive:false}); | |
| function reset(){brain.rotation.set(.05,1.35,0);camera.position.z=4.8;mode='outside';selected='frontal';cortexOpacity=1;isolated=false;autoorbit=false;recolor();onSelect(selected)} | |
| const key=e=>{if(e.key==='ArrowLeft')brain.rotation.y-=.15;else if(e.key==='ArrowRight')brain.rotation.y+=.15;else if(e.key==='ArrowUp')brain.rotation.x-=.1;else if(e.key==='ArrowDown')brain.rotation.x+=.1;else if(e.key==='+'||e.key==='=')camera.position.z=Math.max(3,camera.position.z-.3);else if(e.key==='-')camera.position.z=Math.min(8,camera.position.z+.3);else return;e.preventDefault()};canvas.addEventListener('keydown',key); | |
| function setRoute(ids,animate=true){if(route){brain.remove(route.group);route.group.children.forEach(o=>{o.geometry?.dispose();o.material?.dispose()})}route=null;routeDot=null;if(!ids?.length)return;const curve=new THREE.CatmullRomCurve3(ids.map(id=>point(location[id]))),group=new THREE.Group();const wire=new THREE.Mesh(new THREE.TubeGeometry(curve,80,.009,8,false),new THREE.MeshBasicMaterial({color:'#f2ca78',transparent:true,opacity:.7,depthTest:false}));group.add(wire);routeDot=new THREE.Mesh(new THREE.SphereGeometry(.035,16,12),new THREE.MeshBasicMaterial({color:'#fff4b5',depthTest:false}));group.add(routeDot);brain.add(group);routeDot.visible=animate;route={curve,group,animate};} | |
| let lastW=0,lastH=0,lastTime=performance.now();function render(t=performance.now()){const dt=Math.min(.05,(t-lastTime)/1000);lastTime=t;if(autoorbit&&!drag)brain.rotation.y+=dt*.28;if(route&&routeDot&&route.animate)routeDot.position.copy(route.curve.getPoint((t/3500)%1));if(!alive)return;const r=canvas.getBoundingClientRect();if(r.width!==lastW||r.height!==lastH){lastW=r.width;lastH=r.height;renderer.setSize(r.width,r.height,false);camera.aspect=r.width/r.height;camera.updateProjectionMatrix()}renderer.render(scene,camera);raf=requestAnimationFrame(render)}recolor();render(); | |
| return {getMode(){return mode},opacity(v){cortexOpacity=v;recolor()},spread(v){spread=v;recolor()},isolate(v){isolated=v;recolor()},orbit(v){autoorbit=v},route:setRoute,viewpoint(v){const poses={left:[.05,1.57,0],right:[.05,-1.57,0],front:[0,Math.PI,0],back:[0,0,0],top:[Math.PI/2,0,0]};brain.rotation.set(...poses[v]);},zoom(v){camera.position.z=Math.max(3,Math.min(8,camera.position.z+v))},select,mode(v){mode=v;if(v==='split')brain.rotation.set(.08,.1,0);if(v==='half')brain.rotation.set(.05,-1.4,0);recolor()},labels(v){showLabels=v;recolor()},reset,rotate(){brain.rotation.y+=.18},destroy(){setRoute(null);alive=false;cancelAnimationFrame(raf);canvas.removeEventListener('pointerdown',down);canvas.removeEventListener('pointermove',move);canvas.removeEventListener('pointerup',up);canvas.removeEventListener('wheel',wheel);canvas.removeEventListener('keydown',key);for(const g of geometries)g.dispose();for(const m of materials)m.dispose();for(const s of sprites){s.material.map.dispose();s.material.dispose()}renderer.dispose()}}; | |
| } | |
| const routes={ | |
| vision:{name:'See → decide → move',ids:['thalamus','occipital','association','frontal','motor'],notes:['Sensory information is relayed and processed.','Visual areas analyze the input.','Information is combined with context.','Goals and plans influence the response.','Motor systems help produce an action.']}, | |
| memory:{name:'See → form a memory',ids:['occipital','association','hippocampus','frontal'],notes:['A visual event is processed.','Features are linked with meaning and context.','The hippocampus helps form new explicit memories.','Goal-directed use and retrieval involve wider systems.']}, | |
| movement:{name:'Plan → select → coordinate',ids:['frontal','basal','motor','cerebellum','brainstem'],notes:['A goal shapes a movement plan.','Action-selection circuits contribute.','Motor cortex contributes to voluntary movement.','The cerebellum contributes to timing and coordination.','Brainstem pathways connect brain and body.']} | |
| }; | |
| export async function explorer(root){ | |
| root.innerHTML=card('A brain you can turn, open, and investigate.',`<p>Use the views to get your bearings, open the hemispheres to see deeper structures, or follow an illustrated route. Click a colored region or choose one of the 27 parts below.</p><div class="brain-stage upgraded-brain-stage"><canvas id="brain-3d" tabindex="0" aria-label="Interactive 3D brain. Drag to rotate, scroll to zoom, use arrow keys, or click a brain part."></canvas><span class="stage-hint">DRAG TO TURN · SCROLL TO ZOOM · CLICK TO IDENTIFY</span><span class="brain-surface-caption">ANATOMICAL CORTEX · SCHEMATIC INTERNAL STRUCTURES</span></div> | |
| <div class="world-controls"><button class="secondary selected" data-brain-mode="outside">Outside</button><button class="secondary" data-brain-mode="inside">Look inside</button><button class="secondary" data-brain-mode="half">Half brain</button><button class="secondary" data-brain-mode="split">Split apart</button><button class="secondary" id="brain-home">Reset view</button></div> | |
| <div class="brain-inspector-controls"><label>Viewpoint<select id="brain-viewpoint"><option value="left">Left side</option><option value="right">Right side</option><option value="front">Front</option><option value="back">Back</option><option value="top">Top</option></select></label><label>Cortex opacity <output id="brain-opacity-value">100%</output><input id="brain-opacity" type="range" min="10" max="100" value="100"></label><label>Hemisphere separation <output id="brain-spread-value">0.8</output><input id="brain-spread" type="range" min="0" max="1.6" step=".1" value=".8"></label><div class="button-row"><button class="secondary" id="brain-zoom-in" aria-label="Zoom into brain">+</button><button class="secondary" id="brain-zoom-out" aria-label="Zoom out of brain">−</button></div></div> | |
| <div class="world-controls"><label class="control-check"><input type="checkbox" id="brain-labels"> Show all numbered labels</label><label class="control-check"><input type="checkbox" id="brain-orbit"> Slow rotation</label><label class="control-check"><input type="checkbox" id="brain-isolate"> Emphasize selected structure</label></div> | |
| <div class="brain-explorer-detail" id="brain-3d-detail" role="status"></div> | |
| <div class="brain-discovery"><section><span class="eyebrow">FOLLOW A SIGNAL · ILLUSTRATED</span><h3>How might the parts work together?</h3><label>Choose a route<select id="brain-route">${Object.entries(routes).map(([id,r])=>`<option value="${id}">${escape(r.name)}</option>`).join('')}</select></label><div class="world-controls"><button class="primary" id="brain-route-start">Follow this route</button><button class="secondary" id="brain-route-next" disabled>Next step</button><button class="secondary" id="brain-route-clear">Clear route</button></div><p id="brain-route-note" class="message">The moving dot illustrates connections between teaching landmarks. It is not recorded activity or a complete neural pathway.</p></section><section><span class="eyebrow">FIND A PART</span><h3>Can you identify it from its role?</h3><p id="brain-quiz-question">Start a challenge, then click a structure or choose its name from the list.</p><div class="world-controls"><button class="primary" id="brain-quiz-start">New challenge</button><button class="secondary" id="brain-quiz-reveal" disabled>Reveal answer</button></div><p id="brain-quiz-feedback" class="message" role="status"></p></section></div> | |
| <div class="button-row"><input id="brain-part-search" type="search" placeholder="Find a structure or function…" aria-label="Find a structure or function"></div><div class="brain-parts" id="brain-parts">${state.anatomy.map(p=>`<button class="secondary" data-brain-part="${p.id}">${p.number}. ${escape(p.name)}</button>`).join('')}</div><p class="note">The folded cortex is the standard fsaverage5 anatomical surface. Sulcal shading follows the mesh curvature. Lobe boundaries, functional locations, internal shapes, and routes are schematic teaching guides. A region can support several functions, and broad systems overlap with individual parts.</p>`,'27 PARTS · GUIDED ROUTES · LOCATION CHALLENGES'); | |
| const $=s=>root.querySelector(s),canvas=$('#brain-3d'),detail=$('#brain-3d-detail');let alive=true,challenge=null,routeId=null,routeStep=0; | |
| function syncMode(){root.querySelectorAll('[data-brain-mode]').forEach(b=>b.classList.toggle('selected',b.dataset.brainMode===view.getMode()))} | |
| function describe(id){if(!alive)return;syncMode();const p=state.anatomy.find(p=>p.id===id);if(!p)return;detail.innerHTML=`<span class="eyebrow">PART ${p.number} OF 27 · ${p.view==='inner'?'DEEPER STRUCTURE / SYSTEM':'CORTICAL REGION'}</span><h3>${escape(p.name)}</h3><p><b>In a human brain:</b> ${escape(p.biology)}</p><p><b>In this lab’s software analogy:</b> ${escape(p.analogy)}</p><p class="note">The highlighted location is a teaching landmark. Complex functions involve wider networks.</p>`;root.querySelectorAll('[data-brain-part]').forEach(b=>b.classList.toggle('selected',b.dataset.brainPart===id));if(challenge){if(id===challenge.id){$('#brain-quiz-feedback').textContent='You found it: '+p.name+'. '+p.biology;challenge=null;$('#brain-quiz-reveal').disabled=true}else $('#brain-quiz-feedback').textContent=p.name+' has a different role. Read its explanation and try another structure.'}} | |
| const view=await brainScene(canvas,{onSelect:describe});if(!canvas.isConnected)return()=>view.destroy();describe('frontal'); | |
| root.querySelectorAll('[data-brain-mode]').forEach(b=>b.onclick=()=>{view.mode(b.dataset.brainMode);syncMode()});root.querySelectorAll('[data-brain-part]').forEach(b=>b.onclick=()=>view.select(b.dataset.brainPart)); | |
| $('#brain-home').onclick=()=>{view.reset();$('#brain-opacity').value=100;$('#brain-opacity-value').textContent='100%';$('#brain-isolate').checked=$('#brain-orbit').checked=false;$('#brain-viewpoint').value='left';view.route(null);routeId=null;$('#brain-route-next').disabled=true}; | |
| $('#brain-labels').onchange=e=>view.labels(e.target.checked);$('#brain-orbit').onchange=e=>view.orbit(e.target.checked);$('#brain-isolate').onchange=e=>view.isolate(e.target.checked);$('#brain-viewpoint').onchange=e=>view.viewpoint(e.target.value);$('#brain-opacity').oninput=e=>{$('#brain-opacity-value').textContent=e.target.value+'%';view.opacity(Number(e.target.value)/100)};$('#brain-spread').oninput=e=>{$('#brain-spread-value').textContent=e.target.value;view.spread(Number(e.target.value));view.mode('split');syncMode()};$('#brain-zoom-in').onclick=()=>view.zoom(-.35);$('#brain-zoom-out').onclick=()=>view.zoom(.35); | |
| function routeShow(){const r=routes[routeId];view.route(r.ids);view.mode('inside');view.select(r.ids[routeStep]);$('#brain-route-note').textContent=`Step ${routeStep+1} / ${r.ids.length}: ${state.anatomy.find(p=>p.id===r.ids[routeStep]).name}. ${r.notes[routeStep]} This route is an illustration.`;$('#brain-route-next').textContent=routeStep===r.ids.length-1?'Start route again':'Next step';$('#brain-route-next').disabled=false} | |
| $('#brain-route-start').onclick=()=>{challenge=null;routeId=$('#brain-route').value;routeStep=0;routeShow()};$('#brain-route-next').onclick=()=>{if(!routeId)return;routeStep=(routeStep+1)%routes[routeId].ids.length;routeShow()};$('#brain-route-clear').onclick=()=>{view.route(null);routeId=null;$('#brain-route-next').disabled=true;$('#brain-route-note').textContent='Route cleared. The dots represent an illustrated route, not recorded brain activity.'}; | |
| $('#brain-quiz-start').onclick=()=>{view.route(null);routeId=null;$('#brain-route-next').disabled=true;const choices=state.anatomy.filter(p=>['frontal','occipital','parietal','temporal','hippocampus','amygdala','thalamus','callosum','cerebellum','pons','hypothalamus','ventricles'].includes(p.id));challenge=choices[Math.floor(Math.random()*choices.length)];$('#brain-quiz-question').textContent='Find the structure with this role: '+challenge.biology;$('#brain-quiz-feedback').textContent='Select a region on the model or a name below. You can open the brain and rotate it.';$('#brain-quiz-reveal').disabled=false;$('#brain-labels').checked=false;view.labels(false)}; | |
| $('#brain-quiz-reveal').onclick=()=>{if(!challenge)return;const id=challenge.id;challenge=null;view.select(id);$('#brain-quiz-feedback').textContent='Answer: '+state.anatomy.find(p=>p.id===id).name+'. Try a new challenge when ready.';$('#brain-quiz-reveal').disabled=true};$('#brain-part-search').oninput=e=>{const q=e.target.value.toLowerCase();for(const p of state.anatomy)root.querySelector(`[data-brain-part="${p.id}"]`).hidden=!(p.name+' '+p.biology).toLowerCase().includes(q)}; | |
| const requestedPart=takeBrainFocus();if(requestedPart&&location[requestedPart]){view.mode('inside');view.select(requestedPart);syncMode();} | |
| return()=>{alive=false;view.destroy()}; | |
| } | |