(function(){ 'use strict'; const $=id=>document.getElementById(id); const stage=$('stage'), AU_KM=Sim.AU_KM, G=Sim.G; const sc=new THREE.Scene(), cam=new THREE.PerspectiveCamera(60,1,.001,100); const R=new THREE.WebGLRenderer({antialias:true,powerPreference:'high-performance'}); R.setPixelRatio(Math.min(window.devicePixelRatio||1,2)); R.setClearColor(0x02050a); const cv=R.domElement; stage.appendChild(cv); let W=1,H=1; // Everything is drawn relative to the camera target (tgt), in AU, so zooming from Neptune's orbit down to the Moon keeps full precision. // ---------- distant background stars ---------- const sky=new THREE.Group(); sc.add(sky); { const n=500,a=new Float32Array(n*3); let s=7; const rnd=()=>(s=(s*16807)%2147483647)/2147483647; for(let i=0;i1) mdom=1; } const lk=3*Math.log(.22*radius)-Math.log(mdom); logK=logK===null?lk:logK+(lk-logK)*Math.min(1,dt*6); const K=Math.exp(logK); let sx=0,sy=0,sz=0; for(let b=0;b1?1:f; let nf=(cd-.1*radius)*i04; nf=nf<0?0:nf>1?1:nf; let g=Math.sqrt(dx*dx+dy*dy+dz*dz)*ig; if(g>1)g=1; const k=e*e*f*f*nf, br=(.11+.89*g*g)*k; gcol[o]=GR*br+g*g*g*.25*k; gcol[o+1]=GG*br+g*g*g*.2*k; gcol[o+2]=GB*br; } ggeo.attributes.position.needsUpdate=true; ggeo.attributes.color.needsUpdate=true; } // ---------- the space-time sheet: the ecliptic plane as a rubber sheet whose depth is the gravitational potential ---------- // Depth at each point is the true Newtonian potential, the sum of G*m/r over every body with its real mass (which, divided by // c squared, is also how much clocks slow there). The depth scale is logarithmic so the Sun's well and the far field fit on one // screen; nothing else is adjusted, which is why the planets barely dent it from far away. Following a planet switches to that // planet's free-fall frame: the steady slope of everything else is removed (it cannot be felt in free fall) and its own well shows. const SN=65, SS=80, sV=2*SN*(SS+1), spos=new Float32Array(sV*3), scol=new Float32Array(sV*3), sidx=new Uint32Array(2*SN*SS*2), sU=new Float32Array(sV*2); { let v=0,k2=0; for(let ax=0;ax<2;ax++) for(let i=0;i1) mdom=1; } const lk=Math.log(radius/mdom); sheetK=sheetK===null?lk:sheetK+(lk-sheetK)*Math.min(1,dt*6); const K=Math.exp(sheetK); const fx=follow?follow.x-tgt.x:0, fz=follow?follow.z-tgt.z:0; for(let b=0;b{ const a=new Float32Array(97*3); for(let i=0;i<=96;i++){ a[i*3]=Math.cos(i/96*6.2832); a[i*3+2]=Math.sin(i/96*6.2832); } const g=new THREE.BufferGeometry(); g.setAttribute('position',new THREE.BufferAttribute(a,3)); return g; })(); // colour of a star's surface from its temperature (black-body tint) function tempColor(T,out){ const S=[[2400,1,.36,.12],[3200,1,.5,.22],[4500,1,.72,.46],[5800,1,.93,.8],[7500,.93,.94,1],[12000,.72,.8,1],[40000,.6,.7,1]]; let i=0; while(iS[i+1][0]) i++; const a=S[i],b=S[i+1],k=Math.min(1,Math.max(0,(T-a[0])/(b[0]-a[0]))); return out.setRGB(a[1]+(b[1]-a[1])*k,a[2]+(b[2]-a[2])*k,a[3]+(b[3]-a[3])*k); } // ---------- bodies ---------- sc.add(new THREE.AmbientLight(0xffffff,.28)); const lights=[new THREE.PointLight(0xfff4e0,3.4,0,0),new THREE.PointLight(0xffc9a0,0,0,0)]; lights.forEach(l=>sc.add(l)); const glowTex=(()=>{ const c=document.createElement('canvas'); c.width=c.height=128; const x=c.getContext('2d'),g=x.createRadialGradient(64,64,0,64,64,64); g.addColorStop(0,'rgba(255,255,255,1)');g.addColorStop(.25,'rgba(255,255,255,.55)');g.addColorStop(.6,'rgba(255,255,255,.12)');g.addColorStop(1,'rgba(255,255,255,0)'); x.fillStyle=g;x.fillRect(0,0,128,128); return new THREE.CanvasTexture(c); })(); const jdNow=()=>Date.now()/86400000+2440587.5; let world=Sim.make(jdNow(),'single'); const vis=new Map(), TR=220; // body id -> {mesh, lbl, trail, rel, n, last} const sphereHi=new THREE.SphereGeometry(1,48,32), sphereLo=new THREE.SphereGeometry(1,28,20); function addVis(b){ const star=b.kind==='star'; const mesh=new THREE.Mesh(star?sphereHi:sphereLo, star?new THREE.MeshBasicMaterial({color:b.color}):new THREE.MeshLambertMaterial({color:b.color,emissive:b.color,emissiveIntensity:.12})); if(star){ const sp=new THREE.Sprite(new THREE.SpriteMaterial({map:glowTex,color:b.color,blending:THREE.AdditiveBlending,transparent:true,depthWrite:false})); sp.scale.set(7,7,1); mesh.add(sp); } sc.add(mesh); const lbl=document.createElement('div'); lbl.className='lbl'; lbl.textContent=b.name; $('labels').appendChild(lbl); const arr=new Float32Array(TR*3), col=new Float32Array(TR*3), c=new THREE.Color(b.color); for(let i=0;i{ let i=0; while(iFX[i+1]) i++; return FT[i]+(FT[i+1]-FT[i])*(x-FX[i])/(FX[i+1]-FX[i]); }; function setFuture(on){ fut.on=on; fut.play=false; fut.x=0; fut.t=0; fut.clock=0; $('timeline').value=0; document.body.classList.toggle('future',on); $('future').setAttribute('aria-pressed',on); $('binary').setAttribute('aria-pressed',false); if(launchOn){ launchOn=false; $('launch').setAttribute('aria-pressed',false); } build(on?'future':'single'); setPaused(on?true:false); radiusGoal=on?fit*1.0:null; if(!on) radius=fit; if(on) toast('The Sun\'s future: press play or drag the timeline. Orbits widen as the Sun loses mass.'); } function stepFuture(dt){ if(fut.play){ fut.x=Math.min(1,fut.x+dt/55); $('timeline').value=fut.x; if(fut.x>=1){ fut.play=false; setPaused(true); } } const t=futT(fut.x), fwd=t>fut.t; fut.t=t; fut.clock+=dt*38; const f=Sim.future(t), alive=f.planets.filter(p=>p.alive).map(p=>p.name); const have=world.bodies.filter(b=>b.kind==='planet').map(b=>b.name); if(alive.length!==have.length){ if(fwd) for(const nme of have) if(!alive.includes(nme)){ const p=f.planets.find(q=>q.name===nme); toast(nme+': '+p.why); } const keep=follow&&alive.includes(follow.name)?follow.name:(follow&&follow.kind==='star'?'Sun':null), r0=radius; for(const id of [...vis.keys()]) dropVis(id); world=Sim.makeFuture(t,fut.clock); for(const b of world.bodies) addVis(b); follow=null; setFollow(keep?world.bodies.find(b=>b.name===keep):null); radius=r0; radiusGoal=null; } else Sim.placeFuture(world,t,fut.clock); const s=f.sun, S=world.bodies[0], v=vis.get(S.id); tempColor(s.T,v.mesh.material.color); if(v.glow){ v.glow.material.color.copy(v.mesh.material.color); v.glow.scale.setScalar(s.R>30?2.6:7); } // keep the swollen Sun in view: pull the camera back as it grows if(!follow){ const need=Math.max(fit,s.Rau*3.4); if(radius0; if(v.hillR>0){ v.hill.position.set(x,y,z); v.hill.scale.setScalar(v.hillR); } } if(b.kind==='star'&&li<2){ lights[li].position.set(x,y,z); lights[li].intensity=world.mode==='binary'?(li?1.4:2.2):3.4; li++; } tv.set(x,y,z).project(cam); v.on=tv.z<1&&tv.z>-1; v.sx=(tv.x+1)/2*W; v.sy=(1-tv.y)/2*H; const show=b!==follow&&v.n>1; v.trail.visible=show; if(show){ const a=v.arr,r=v.rel,m=v.n*3; for(let i=0;i-40&&v.sx0&&v.syfollow?Math.max(follow.Rau*2.6,2e-5):.02; function placeCam(){ const sp=Math.sin(phi); cam.position.set(radius*sp*Math.sin(theta),radius*Math.cos(phi),radius*sp*Math.cos(theta)); cam.near=radius*1e-3; cam.far=radius*4e3; cam.updateProjectionMatrix(); cam.lookAt(0,0,0); cam.updateMatrixWorld(); sky.scale.setScalar(radius*2e3); } function zoomFor(b){ if(b.kind==='star'||b.launched) return null; const k=WsetTimeout(resize,250)); if(window.ResizeObserver) new ResizeObserver(resize).observe(stage); // ---------- picking helpers ---------- const tv=new THREE.Vector3(), ray=new THREE.Raycaster(), ndc=new THREE.Vector2(), plane=new THREE.Plane(), fwd=new THREE.Vector3(), zero=new THREE.Vector3(); function screenOf(b){ const v=vis.get(b.id); return v&&v.on?{x:v.sx,y:v.sy,rpx:v.rpx}:null; } // a sun is grabbed only when the touch lands on it function starAt(x,y){ let best=null,bd=1e9; for(const b of world.bodies){ if(b.kind!=='star') continue; const s=screenOf(b); if(!s) continue; const d=Math.hypot(x-s.x,y-s.y); if(d Moon) const c=[]; for(const b of world.bodies){ const s=screenOf(b); if(!s) continue; const q=Math.hypot(x-s.x,y-s.y)/Math.max(26,s.rpx+12); if(q<1) c.push([q,b]); } if(!c.length) return null; c.sort((a,b)=>a[0]-b[0]); const i=c.findIndex(e=>e[1]===follow); return c[(i+1)%c.length][1]; } function planePoint(x,y,out){ cam.getWorldDirection(fwd); plane.setFromNormalAndCoplanarPoint(fwd,zero); ndc.set(x/W*2-1,-(y/H)*2+1); ray.setFromCamera(ndc,cam); return ray.ray.intersectPlane(plane,out); } // ---------- launching a test body ---------- let launchOn=false, launchN=0; const L0=new THREE.Vector3(), L1=new THREE.Vector3(); const LCOL=[0xffb3d1,0x9ff0ff,0xfff08a,0xb6ff9a,0xffa36b,0xc4b5ff]; const aimGeo=new THREE.BufferGeometry(); aimGeo.setAttribute('position',new THREE.BufferAttribute(new Float32Array(6),3)); const aimLine=new THREE.Line(aimGeo,new THREE.LineBasicMaterial({color:0xffffff,transparent:true,opacity:.8,depthTest:false})); aimLine.frustumCulled=false; aimLine.visible=false; sc.add(aimLine); function aimUpdate(){ const a=aimGeo.attributes.position.array; a[0]=L0.x;a[1]=L0.y;a[2]=L0.z;a[3]=L1.x;a[4]=L1.y;a[5]=L1.z; aimGeo.attributes.position.needsUpdate=true; } function doLaunch(){ const x=tgt.x+L0.x,y=tgt.y+L0.y,z=tgt.z+L0.z; // the body pulling hardest at the launch point sets the scale: a swipe 30% of the view radius long = that body's circular orbital speed let prim=null,best=0,pr=1; for(const o of world.bodies){ const d=Math.hypot(o.x-x,o.y-y,o.z-z),a=o.m/(d*d); if(a>best){ best=a;prim=o;pr=d; } } const vc=Math.sqrt(G*prim.m/pr); let k=1/(.3*radius), len=L0.distanceTo(L1)*k; if(len>2.5) k*=2.5/len; const old=world.bodies.filter(b=>b.launched); if(old.length>=8){ const o=old[0]; world.bodies.splice(world.bodies.indexOf(o),1); dropVis(o.id); } const a=Math.max(pr,1e-6), P=2*Math.PI*Math.sqrt(a*a*a/(G*prim.m)); const b=Sim.add(world,{name:'Probe '+(++launchN),kind:'planet',m:1e-12,R:500,Rau:500/AU_KM,color:LCOL[launchN%LCOL.length],P,launched:true,x,y,z, vx:prim.vx+(L1.x-L0.x)*k*vc, vy:prim.vy+(L1.y-L0.y)*k*vc, vz:prim.vz+(L1.z-L0.z)*k*vc}); addVis(b); toast(b.name+' launched at '+(Math.hypot(b.vx-prim.vx,b.vy-prim.vy,b.vz-prim.vz)*AU_KM/86400).toFixed(1)+' km/s relative to '+prim.name); return b; } // ---------- touch / pointer ---------- const pts=new Map(); let mode='none', last=null, down=null; function gestureInfo(){ const [a,b]=[...pts.values()]; return {mx:(a.x+b.x)/2,my:(a.y+b.y)/2,d:Math.hypot(a.x-b.x,a.y-b.y)}; } function rotateBy(dx,dy){ theta-=dx*.008; phi=Math.min(PHI_MAX,Math.max(PHI_MIN,phi-dy*.008)); } function zoomBy(k){ radiusGoal=null; radius=Math.min(R_MAX,Math.max(rMin(),radius*k)); if(!follow) radiusBack=null; } function xy(e){ const r=cv.getBoundingClientRect(); return {x:e.clientX-r.left,y:e.clientY-r.top}; } cv.addEventListener('contextmenu',e=>e.preventDefault()); cv.addEventListener('pointerdown',e=>{ try{ cv.setPointerCapture(e.pointerId); }catch(_){} $('hint').style.opacity=0; const p=xy(e); pts.set(e.pointerId,p); if(pts.size===1){ down={x:p.x,y:p.y,moved:false}; last={x:p.x,y:p.y}; const alt=e.pointerType==='mouse'&&(e.button===2||e.shiftKey); const star=alt||fut.on?null:starAt(p.x,p.y); if(star){ mode='drag'; down.star=star; } else if(launchOn&&!alt&&planePoint(p.x,p.y,L0)){ mode='launch'; L1.copy(L0); } else mode='rotate'; } else if(pts.size===2){ aimLine.visible=false; down=null; mode='gesture'; last=gestureInfo(); } }); cv.addEventListener('pointermove',e=>{ if(!pts.has(e.pointerId)) return; const p=xy(e); pts.set(e.pointerId,p); if(mode==='gesture'){ if(pts.size===2){ const g=gestureInfo(); rotateBy(g.mx-last.mx,g.my-last.my); if(last.d>0&&g.d>0) zoomBy(last.d/g.d); last=g; } return; } if(!down) return; if(!down.moved){ if(Math.hypot(p.x-down.x,p.y-down.y)<8) return; down.moved=true; last={x:p.x,y:p.y}; if(mode==='launch') aimLine.visible=true; } const dx=p.x-last.x, dy=p.y-last.y; last={x:p.x,y:p.y}; if(mode==='rotate') rotateBy(dx,dy); else if(mode==='drag'){ // slide the whole system in the plane facing the camera, so the sun stays under the finger const s=down.star; tv.set(s.x-tgt.x,s.y-tgt.y,s.z-tgt.z).sub(cam.position); cam.getWorldDirection(fwd); const k=2*tv.dot(fwd)*Math.tan(cam.fov*Math.PI/360)/H, m=cam.matrixWorld.elements; shiftSystem((m[0]*dx-m[4]*dy)*k,(m[1]*dx-m[5]*dy)*k,(m[2]*dx-m[6]*dy)*k); } else if(mode==='launch'){ if(planePoint(p.x,p.y,L1)) aimUpdate(); } }); function up(e){ if(!pts.has(e.pointerId)) return; const p=pts.get(e.pointerId); pts.delete(e.pointerId); if(down&&mode!=='gesture'&&mode!=='hold'&&e.type==='pointerup'){ if(!down.moved) setFollow(pick(p.x,p.y)); // tap: follow a body, or stop on empty space else if(mode==='launch') doLaunch(); } aimLine.visible=false; if(pts.size===0){ mode='none'; down=null; } else if(mode==='gesture') mode='hold'; } cv.addEventListener('pointerup',up); cv.addEventListener('pointercancel',up); cv.addEventListener('wheel',e=>{ e.preventDefault(); zoomBy(Math.exp(e.deltaY*.001)); },{passive:false}); // ---------- controls ---------- let paused=false, dps=10, toastT=0, infoT=0; // dps = simulated days per real second function toast(t){ const el=$('toast'); el.textContent=t; el.style.opacity=1; clearTimeout(toastT); toastT=setTimeout(()=>el.style.opacity=0,3200); } function setPaused(v){ paused=v; $('pause').setAttribute('aria-pressed',v); $('pause').setAttribute('aria-label',v?'Play':'Pause'); $('icoPause').toggleAttribute('hidden',v); $('icoPlay').toggleAttribute('hidden',!v); } function fmtSpeed(d){ return d<1?(d*24).toFixed(d*24<10?1:0)+' hours/s':d<30?d.toFixed(d<10?1:0)+' days/s':d<365?(d/30.44).toFixed(1)+' months/s':(d/365.25).toFixed(2)+' years/s'; } function setSpeed(x){ dps=Math.pow(10,-1.38+x*4.2437); if(Math.abs(dps-10)<.6) dps=10; $('speedval').textContent=fmtSpeed(dps); } // 1 hour/s ... 2 years/s $('pause').onclick=()=>{ if(fut.on){ fut.play=!fut.play; if(fut.play&&fut.x>=1){ fut.x=0; } setPaused(!fut.play); } else setPaused(!paused); }; $('timeline').oninput=e=>{ fut.x=+e.target.value; fut.play=false; setPaused(true); }; $('future').onclick=()=>{ $('hint').style.opacity=0; setFuture(!fut.on); }; $('gridbtn').onclick=()=>{ gridMode=gridMode==='sheet'?'lattice':gridMode==='lattice'?'off':'sheet'; $('gridname').textContent=gridMode==='sheet'?'Sheet':gridMode==='lattice'?'Lattice':'No grid'; toast(gridMode==='sheet'?'Space-time sheet: depth is the gravitational potential (log scale)':gridMode==='lattice'?'3D lattice: each point is pulled along the true gravitational acceleration':'Grid off'); }; $('speed').oninput=e=>setSpeed(+e.target.value); setSpeed(+$('speed').value); $('launch').onclick=()=>{ if(fut.on) return; launchOn=!launchOn; $('launch').setAttribute('aria-pressed',launchOn); toast(launchOn?'Launch on: swipe from empty space to throw a probe. Two fingers still rotate and zoom.':'Launch off: drag to rotate'); }; $('binary').onclick=()=>{ if(fut.on) return; const m=world.mode==='binary'?'single':'binary'; build(m); $('binary').setAttribute('aria-pressed',m==='binary'); if(m==='binary') toast('What if: the Sun split into two stars (0.6 + 0.4 solar masses, 0.08 AU apart)'); }; $('reset').onclick=()=>{ if(fut.on) setFuture(false); else build(world.mode); }; $('chip').onclick=()=>setFollow(null); function fmtDist(au){ const km=au*AU_KM; return au>=.05?au.toFixed(3)+' AU':km>=1e6?(km/1e6).toFixed(2)+' million km':Math.round(km).toLocaleString('en-US')+' km'; } const num=(x,d)=>x.toLocaleString('en-US',{maximumFractionDigits:d,minimumFractionDigits:d}); const sig=x=>x===0?'0':Math.abs(x)>=1e4||Math.abs(x)<1e-2?x.toExponential(2).replace('e',' × 10^').replace('^+','^'):x>=100?num(x,0):x>=10?num(x,1):num(x,2); function factLines(b){ const f=Sim.facts(b,world), L=[]; if(b.kind==='star'){ if(fut.on){ const s=Sim.sunAt(fut.t); L.push('Mass '+num(s.M,3)+' of today · radius '+sig(s.R)+' × today ('+fmtDist(s.Rau)+')','Surface '+num(s.T,0)+' K · brightness '+sig(s.L)+' × today'); } else L.push(b.m.toFixed(b.m===1?0:1)+' solar mass'+(b.m===1?'':'es')+' · radius '+num(b.R,0)+' km'); L.push('Surface gravity '+sig(f.g)+' m/s² · escape speed '+sig(f.vesc)+' km/s','Starlight grazing it bends by '+sig(f.bend)+' arcsec','Clocks at its surface lose '+sig(f.dilation*86400*365.25)+' s per year','It would be a black hole if squeezed inside '+sig(f.rs/1000)+' km'); return L; } if(b.launched){ L.push(fmtDist(f.r)+' from the Sun · '+num(f.speed,2)+' km/s'); if(f.a>0) L.push('Orbit: '+num(f.a,3)+' AU, eccentricity '+num(f.e,3)+', period '+sig(f.period/365.25)+' years'); else L.push('Escaping: this path never closes'); return L; } let o=b.parent&&world.bodies.find(x=>x.name===b.parent); if(o) L.push(fmtDist(Math.hypot(b.x-o.x,b.y-o.y,b.z-o.z))+' from '+o.name+' · '+(Math.hypot(b.vx-o.vx,b.vy-o.vy,b.vz-o.vz)*AU_KM/86400).toFixed(2)+' km/s'); else L.push(fmtDist(f.r)+' from the Sun · '+num(f.speed,2)+' km/s','Orbit: '+num(f.a,3)+' AU, eccentricity '+num(f.e,3)+', period '+sig(f.period/365.25)+' years'); L.push('Surface gravity '+sig(f.g)+' m/s² · escape speed '+sig(f.vesc)+' km/s'); if(!o&&f.hill) L.push('Its gravity beats the Sun\'s inside '+fmtDist(f.hill)+' (ring)','Einstein\'s extra orbit twist: '+sig(f.gr)+' arcsec per century'); L.push('Clocks on its surface lose '+sig((f.dilation+(f.sunDilation||0))*86400*365.25*1000)+' ms per year'); if(fut.on){ const p=Sim.future(fut.t).planets.find(q=>q.name===b.name); if(p) L.push('Sunlight alone would hold it at '+num(p.teq,0)+' K ('+num(p.teq-273.15,0)+' °C)'); } return L; } let E0=null; function updateInfo(){ const sci=$('sci'); if(fut.on){ const f=Sim.future(fut.t), s=f.sun, yrs=fut.t; $('date').textContent=yrs<=0?'Today':'+'+(yrs>=.001?num(yrs,yrs>7?3:2)+' billion years':num(yrs*1000,2)+' million years'); const rows=f.planets.map(p=>''+p.name+''+(p.alive?num(p.a,2)+' AU':'gone')+''+(p.alive?(p.a>=s.hz[0]&&p.a<=s.hz[1]?'in the liquid-water zone':num(p.teq,0)+' K'):p.why)+'').join(''); sci.innerHTML=''+s.stage+'Sun: '+num(s.M,3)+' of today\'s mass · '+sig(s.R)+' × radius ('+fmtDist(s.Rau)+') · '+sig(s.L)+' × brightness · '+num(s.T,0)+' KLiquid-water zone '+sig(s.hz[0])+' to '+sig(s.hz[1])+' AU (green band)'+rows+'
'+(s.modelled?'This moment is a model from Schröder & Smith (2008).':'Between the published models; values are joined smoothly.')+' Orbit sizes are real physics (a = a₀ ÷ mass); where each planet is on its orbit is not knowable.'; } else { const d=new Date((world.jd-2440587.5)*86400000); $('date').textContent=isNaN(d)?'':d.toISOString().slice(0,10)+(world.mode==='binary'?' · what-if: two suns':''); const E=Sim.energy(world.bodies); if(E0===null||world.bodies.length!==E0.n) E0={E,n:world.bodies.length}; sci.innerHTML='Newtonian gravity between every pair, true masses · leapfrog steps ≤ '+(world.mode==='binary'?'1.2':'4.8')+' hEnergy drift since start: '+((E-E0.E)/Math.abs(E0.E)).toExponential(1)+''; } for(const b of world.bodies){ const v=vis.get(b.id); if(v&&v.hill){ const f=Sim.facts(b,world); v.hillR=f.hill>0&&isFinite(f.hill)?f.hill:0; } } hz.visible=world.mode!=='binary'; if(hz.visible){ const c=Sim.starCentre(world.bodies), L=fut.on?Sim.sunAt(fut.t).L:1; hz.position.set(c.x-tgt.x,c.y-tgt.y,c.z-tgt.z); hz.scale.setScalar(Math.sqrt(L)); } if(!follow) return; $('chipinfo').innerHTML=factLines(follow).map(l=>''+l+'').join(''); } // ---------- main loop ---------- let prev=performance.now(); function tick(dt){ if(fut.on) stepFuture(dt); else if(!paused&&dt>0){ const ev=Sim.advance(world,dt*dps,sampleTrails); // leapfrog, 8 or more substeps for(const e of ev){ dropVis(e.body.id); toast(e.body.name+(e.type==='absorbed'?' fell into the Sun':' left the solar system')); } } updateCam(dt); syncBodies(); grid.visible=gridMode==='lattice'; sheet.visible=gridMode==='sheet'; if(grid.visible) bendGrid(dt); else if(sheet.visible) bendSheet(dt); if(hz.visible){ const c=Sim.starCentre(world.bodies); hz.position.set(c.x-tgt.x,c.y-tgt.y,c.z-tgt.z); } infoT-=dt; if(infoT<=0){ infoT=.2; updateInfo(); } } function frame(now){ requestAnimationFrame(frame); const dt=Math.min(.05,(now-prev)/1000); prev=now; resize(); tick(dt); R.render(sc,cam); } for(const b of world.bodies) addVis(b); resize(); placeCam(); window.__gw={Sim,fut,setFuture,get world(){return world;},screenOf,view:()=>({theta,phi,radius,follow:follow&&follow.name,mode,paused,dps,W,H}),tick, fast(sec){ const ev=[]; for(let i=0;ie.type+':'+e.body.name)); return ev; }}; requestAnimationFrame(frame); })();