Simulation · project 13 of 19
Gravity Well 3D.
The real solar system with real physics. Then break it.
How to use it
- It opens on the real solar system at today's positions. Use the speed slider to run time faster.
- Drag to look around and pinch or scroll to zoom. Tap a planet to follow it.
- Press Launch to throw in a new body, or Two suns to break the system.
- Press Today to put everything back.
Where it helps most
- Showing a child or a class why orbits are stable, and how little it takes to change that.
- A base for any physics simulation that must use real units and conserve energy.
- Playing on a phone or tablet.
The idea
I wanted a gravity toy that is not a toy: the real solar system following exact Newtonian physics, starting from today's planet positions, that I can drag, pinch and fly through on my phone and iPad, then break by adding a second sun or launching new bodies.
The build
Claude wrote an N-body leapfrog integrator in real units (AU, days, solar masses), rendered it with three.js, added touch controls (drag the Sun to move everything, pinch to zoom, tap to follow a body), a time-speed slider, Launch and Two suns modes. It first lived as an artifact; Claude then moved it onto sghadimi.com with three.js hosted locally.
Free to take
Build your own.
Copy the skill, paste it into your own AI, and say what you want different. How to use a skill, step by step ›
Get the skillThe instructions your AI follows. Works in Claude, ChatGPT, Gemini or any other
You are a physicist and a three.js developer. Build a single-page, phone-friendly 3D simulation of the real solar system.
Physics (non-negotiable):
- Newtonian point-mass gravity between every pair of bodies, real masses, no softening.
- Units: AU, days, solar masses, G from the Gaussian constant (k = 0.01720209895, G = k²).
- Leapfrog (kick-drift-kick) integrator with sub-steps; cap the step size and report energy drift.
- Start from today's date: compute planet positions from published orbital elements (J2000 + rates).
Scene and controls:
- three.js bundled into the page (no CDN). Log-scaled visual radii so planets are visible; labels that follow bodies.
- Touch: drag empty space to rotate, pinch to zoom, tap a body to fly to and follow it, drag the Sun to move the whole system. Mouse equivalents on desktop.
- Bottom bar: pause, a time-speed slider (simulated time per real second), 'Launch' to fire a new body, 'Two suns' to add a second star. A 'Today' button resets.
- 48 px touch targets, safe-area insets, works on iPhone and iPad.
Deliver one HTML file. Expose the physics as a separate module so it can run in a test, and include a short test that checks Earth's orbital period ≈ 365.25 days.
Get the code5 files, exactly as they run on this site
three.js r160 is loaded from the site's own /animations/vendor/ folder and is not repeated here.
index.html37 lines
<!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>Gravity Well 3D | Shahrouz Ghadimi</title>
<meta name="description" content="Gravity Well 3D: the real solar system with true masses, distances and today's positions, running on real physics in your browser. Then break it.">
<link rel="icon" href="../../favicon.svg" type="image/svg+xml">
<link rel="stylesheet" href="./gravity.css">
</head><body>
<div id="stage"></div>
<div id="labels"></div>
<div id="err"></div>
<script src="./errors.js"></script>
<div id="top">
<div id="left">
<div id="date"></div>
<div id="sci"></div>
<button id="chip" hidden aria-label="Stop following"><span>Following <b id="chipname"></b><span class="x" aria-hidden="true">×</span></span><span id="chipinfo"></span></button>
</div>
<button id="reset">Today</button>
</div>
<div id="hint">The real solar system today. The blue sheet is space-time, bent by each body's real mass.<br>Drag to rotate · pinch to zoom · tap a body for its physics</div>
<div id="toast" role="status"></div>
<div id="bar">
<button id="pause" aria-label="Pause" aria-pressed="false"><svg id="icoPause" viewBox="0 0 18 18"><rect x="3" y="2" width="4.5" height="14" rx="1"/><rect x="10.5" y="2" width="4.5" height="14" rx="1"/></svg><svg id="icoPlay" viewBox="0 0 18 18" hidden><path d="M4 2.2v13.6a.8.8 0 0 0 1.2.7l11-6.8a.8.8 0 0 0 0-1.4l-11-6.8A.8.8 0 0 0 4 2.2z"/></svg></button>
<label id="timewrap"><span>Now</span><input id="timeline" type="range" min="0" max="1" step="0.0005" value="0" aria-label="Time from today to the white dwarf"><span>+9 Gyr</span></label>
<label id="speedwrap"><span>Speed</span><input id="speed" type="range" min="0" max="1" step="0.005" value="0.56" aria-label="Simulated time per second"><span id="speedval"></span></label>
<button id="launch" aria-pressed="false"><svg viewBox="0 0 18 18"><path d="M8 2h2v6h6v2h-6v6H8v-6H2V8h6z"/></svg>Launch</button>
<button id="binary" aria-pressed="false"><svg viewBox="0 0 18 18"><circle cx="6" cy="9" r="4.2"/><circle cx="13.5" cy="9" r="2.8"/></svg>Two suns</button>
<button id="future" aria-pressed="false"><svg viewBox="0 0 18 18"><path d="M9 1.5a7.5 7.5 0 1 0 7.5 7.5h-2A5.5 5.5 0 1 1 9 3.5V6l4-3.3L9 0z"/><path d="M8.2 5.5h1.6v3.8l2.6 1.6-.8 1.3-3.4-2.1z"/></svg>Future</button>
<button id="gridbtn"><svg viewBox="0 0 18 18"><path d="M1 4h16v1.6H1zM1 8.2h16v1.6H1zM1 12.4h16V14H1zM4 1h1.6v16H4zM8.2 1h1.6v16H8.2zM12.4 1H14v16h-1.6z"/></svg><span id="gridname">Sheet</span></button>
</div>
<script src="../vendor/three-r160.min.js"></script>
<script src="./sim.js"></script>
<script src="./gravity.js"></script>
</body></html>
sim.js (physics)197 lines
// ---- Physics: the real solar system. Newtonian point-mass gravity between every pair, real masses,
// ---- no softening, leapfrog integrator. Units: AU, days, solar masses. Runs headless in tests too.
const Sim=(function(){
const K_GAUSS=0.01720209895, G=K_GAUSS*K_GAUSS; // AU^3 / (solar mass * day^2)
const AU_KM=149597870.7, DEG=Math.PI/180, MAX_STEP=.2, MIN_SUB=8;
// JPL "Approximate Positions of the Planets", Table 1 (1800-2050), J2000 ecliptic:
// [a AU, e, I deg, L deg, long.peri deg, long.node deg] and their rates per Julian century
const EL={
Mercury:[[0.38709927,0.20563593,7.00497902,252.25032350,77.45779628,48.33076593],[0.00000037,0.00001906,-0.00594749,149472.67411175,0.16047689,-0.12534081]],
Venus:[[0.72333566,0.00677672,3.39467605,181.97909950,131.60246718,76.67984255],[0.00000390,-0.00004107,-0.00078890,58517.81538729,0.00268329,-0.27769418]],
EMB:[[1.00000261,0.01671123,-0.00001531,100.46457166,102.93768193,0.0],[0.00000562,-0.00004392,-0.01294668,35999.37244981,0.32327364,0.0]],
Mars:[[1.52371034,0.09339410,1.84969142,-4.55343205,-23.94362959,49.55953891],[0.00001847,0.00007882,-0.00813131,19140.30268499,0.44441088,-0.29257343]],
Jupiter:[[5.20288700,0.04838624,1.30439695,34.39644051,14.72847983,100.47390909],[-0.00011607,-0.00013253,-0.00183714,3034.74612775,0.21252668,0.20469106]],
Saturn:[[9.53667594,0.05386179,2.48599187,49.95424423,92.59887831,113.66242448],[-0.00125060,-0.00050991,0.00193609,1222.49362201,-0.41897216,-0.28867794]],
Uranus:[[19.18916464,0.04725744,0.77263783,313.23810451,170.95427630,74.01692503],[-0.00196176,-0.00004397,-0.00242939,428.48202785,0.40805281,0.04240589]],
Neptune:[[30.06992276,0.00859048,1.77004347,-55.12002969,44.96476227,131.78422574],[0.00026291,0.00005105,0.00035372,218.45945325,-0.32241464,-0.00508664]]
};
// mass in solar masses, mean radius in km, orbital period in days (used only to pace the trails)
const DEFS=[
{name:'Sun', kind:'star', m:1, R:695700,color:0xffcc33,P:4332.6},
{name:'Mercury',kind:'planet',m:1.6601e-7, R:2439.7,color:0xb0a8a0,P:87.969, el:'Mercury'},
{name:'Venus', kind:'planet',m:2.4478e-6, R:6051.8,color:0xf0d090,P:224.701,el:'Venus'},
{name:'Earth', kind:'planet',m:3.0035e-6, R:6371.0,color:0x4fa3ff,P:365.256},
{name:'Moon', kind:'moon', m:3.6943e-8, R:1737.4,color:0xcfcfcf,P:27.3217,parent:'Earth'},
{name:'Mars', kind:'planet',m:3.2272e-7, R:3389.5,color:0xff6b4a,P:686.98, el:'Mars'},
{name:'Jupiter',kind:'planet',m:9.5479e-4, R:69911, color:0xe8b98a,P:4332.6, el:'Jupiter'},
{name:'Saturn', kind:'planet',m:2.8589e-4, R:58232, color:0xe9d9a6,P:10759.2,el:'Saturn'},
{name:'Uranus', kind:'planet',m:4.3662e-5, R:25362, color:0x9fe3e8,P:30688.5,el:'Uranus'},
{name:'Neptune',kind:'planet',m:5.1514e-5, R:24622, color:0x5b7cff,P:60182, el:'Neptune'}
];
const MOON_FRAC=3.6943e-8/(3.6943e-8+3.0035e-6);
function planetEcl(name,jd){ // heliocentric J2000 ecliptic position, AU
const T=(jd-2451545)/36525,[e0,r]=EL[name];
const a=e0[0]+r[0]*T,e=e0[1]+r[1]*T,I=(e0[2]+r[2]*T)*DEG,L=e0[3]+r[3]*T,wb=e0[4]+r[4]*T,Om=(e0[5]+r[5]*T)*DEG;
let M=(((L-wb)%360)+540)%360-180; M*=DEG;
let E=M+e*Math.sin(M); for(let i=0;i<10;i++) E-=(E-e*Math.sin(E)-M)/(1-e*Math.cos(E));
const xp=a*(Math.cos(E)-e),yp=a*Math.sqrt(1-e*e)*Math.sin(E);
const w=wb*DEG-Om,cw=Math.cos(w),sw=Math.sin(w),cO=Math.cos(Om),sO=Math.sin(Om),cI=Math.cos(I),sI=Math.sin(I);
return [(cw*cO-sw*sO*cI)*xp+(-sw*cO-cw*sO*cI)*yp,(cw*sO+sw*cO*cI)*xp+(-sw*sO+cw*cO*cI)*yp,sw*sI*xp+cw*sI*yp];
}
function moonEcl(jd){ // Moon relative to Earth, J2000 ecliptic, AU (truncated lunar series, main periodic terms)
const d=jd-2451545,T=d/36525,s=x=>Math.sin(x*DEG),c=x=>Math.cos(x*DEG);
const Lp=218.3164477+13.17639648*d, D=297.8501921+12.19074912*d, M=357.5291092+0.98560028*d, Mp=134.9633964+13.06499295*d, F=93.2720950+13.22935024*d;
const lon=Lp+6.288774*s(Mp)+1.274027*s(2*D-Mp)+.658314*s(2*D)+.213618*s(2*Mp)-.185116*s(M)-.114332*s(2*F)+.058793*s(2*D-2*Mp)+.057066*s(2*D-M-Mp)+.053322*s(2*D+Mp)+.045758*s(2*D-M)-.040923*s(M-Mp)-.034720*s(D)-.030383*s(M+Mp)
-1.396971*T; // precess from the ecliptic of date back to J2000
const lat=5.128122*s(F)+.280602*s(Mp+F)+.277693*s(Mp-F)+.173237*s(2*D-F)+.055413*s(2*D-Mp+F)+.046271*s(2*D-Mp-F)+.032573*s(2*D+F);
const r=(385000.56-20905.355*c(Mp)-3699.111*c(2*D-Mp)-2955.968*c(2*D)-569.925*c(2*Mp)+48.888*c(M)-3.149*c(2*F)+246.158*c(2*D-2*Mp)-152.138*c(2*D-M-Mp)-170.733*c(2*D+Mp)-204.586*c(2*D-M)-129.620*c(M-Mp)+108.743*c(D)+104.755*c(M+Mp))/AU_KM;
return [r*c(lat)*c(lon),r*c(lat)*s(lon),r*s(lat)];
}
// heliocentric ecliptic position of a named body from the formulas above (no N-body): used for start-up and for checking
function formula(name,jd){
if(name==='Sun') return [0,0,0];
if(name==='Earth'||name==='Moon'){ const e=planetEcl('EMB',jd),m=moonEcl(jd),k=name==='Earth'?-MOON_FRAC:1-MOON_FRAC; return [e[0]+k*m[0],e[1]+k*m[1],e[2]+k*m[2]]; }
return planetEcl(name,jd);
}
let nextId=1;
function body(o){ return Object.assign({id:nextId++,x:0,y:0,z:0,vx:0,vy:0,vz:0,ax:0,ay:0,az:0,launched:false},o); }
// scene axes: ecliptic x -> x, ecliptic north -> y (up), ecliptic y -> -z
const ax3=p=>[p[0],p[2],-p[1]];
function make(jd,mode){
const bodies=[];
for(const d of DEFS){
const h=d.kind==='moon'?.002:.02, p=formula(d.name,jd),a=formula(d.name,jd-h),b=formula(d.name,jd+h); // velocity = time derivative of the ephemeris
const P=ax3(p),V=ax3([(b[0]-a[0])/(2*h),(b[1]-a[1])/(2*h),(b[2]-a[2])/(2*h)]);
bodies.push(body({name:d.name,kind:d.kind,m:d.m,R:d.R,Rau:d.R/AU_KM,color:d.color,P:d.P,parent:d.parent,x:P[0],y:P[1],z:P[2],vx:V[0],vy:V[1],vz:V[2]}));
}
if(mode==='binary'){ // what-if: the Sun's mass split into two stars 0.08 AU apart
const S=bodies[0],sep=.08,mA=.6,mB=.4,vr=Math.sqrt(G*(mA+mB)/sep);
const A=body({name:'Sun A',kind:'star',m:mA,R:695700*.62,Rau:695700*.62/AU_KM,color:0xffcc33,P:4332.6,x:S.x-sep*mB,y:S.y,z:S.z,vx:S.vx,vy:S.vy,vz:S.vz+vr*mB});
const B=body({name:'Sun B',kind:'star',m:mB,R:695700*.42,Rau:695700*.42/AU_KM,color:0xff8a4a,P:4332.6,x:S.x+sep*mA,y:S.y,z:S.z,vx:S.vx,vy:S.vy,vz:S.vz-vr*mA});
bodies.splice(0,1,A,B);
}
// work in the frame of the system's centre of mass
let px=0,py=0,pz=0,cx=0,cy=0,cz=0,T=0;
for(const b of bodies){ px+=b.vx*b.m;py+=b.vy*b.m;pz+=b.vz*b.m; cx+=b.x*b.m;cy+=b.y*b.m;cz+=b.z*b.m; T+=b.m; }
for(const b of bodies){ b.vx-=px/T;b.vy-=py/T;b.vz-=pz/T; b.x-=cx/T;b.y-=cy/T;b.z-=cz/T; }
return {mode:mode==='binary'?'binary':'single',bodies,jd,jd0:jd};
}
function add(world,o){ const b=body(o); world.bodies.push(b); return b; }
function accel(bs){
const n=bs.length;
for(let i=0;i<n;i++){ const b=bs[i]; b.ax=b.ay=b.az=0; }
for(let i=0;i<n;i++){ const A=bs[i];
for(let j=i+1;j<n;j++){ const B=bs[j];
const dx=B.x-A.x,dy=B.y-A.y,dz=B.z-A.z,d2=dx*dx+dy*dy+dz*dz,inv=G/(d2*Math.sqrt(d2)),ia=inv*B.m,ib=inv*A.m; // F = G m1 m2 / r^2, exactly
A.ax+=dx*ia;A.ay+=dy*ia;A.az+=dz*ia; B.ax-=dx*ib;B.ay-=dy*ib;B.az-=dz*ib;
} }
}
function starCentre(bs){ let x=0,y=0,z=0,vx=0,vy=0,vz=0,M=0; for(const b of bs) if(b.kind==='star'){ x+=b.x*b.m;y+=b.y*b.m;z+=b.z*b.m;vx+=b.vx*b.m;vy+=b.vy*b.m;vz+=b.vz*b.m;M+=b.m; } return {x:x/M,y:y/M,z:z/M,vx:vx/M,vy:vy/M,vz:vz/M,m:M}; }
// one rendered frame covering `days` of simulated time: leapfrog (kick-drift-kick), at least 8 substeps,
// more when time runs fast so a substep never exceeds 0.2 day (0.05 day with two suns)
function advance(world,days,onSub){
const bs=world.bodies, cap=world.mode==='binary'?.05:MAX_STEP, n=Math.max(MIN_SUB,Math.ceil(Math.abs(days)/cap)), h=days/n, hh=h/2; let b;
accel(bs);
for(let k=0;k<n;k++){
const m=bs.length;
for(let i=0;i<m;i++){ b=bs[i]; b.vx+=b.ax*hh;b.vy+=b.ay*hh;b.vz+=b.az*hh; b.x+=b.vx*h;b.y+=b.vy*h;b.z+=b.vz*h; }
accel(bs);
for(let i=0;i<m;i++){ b=bs[i]; b.vx+=b.ax*hh;b.vy+=b.ay*hh;b.vz+=b.az*hh; }
world.jd+=h; if(onSub) onSub(world);
}
const ev=[], c=starCentre(bs);
for(let i=bs.length-1;i>=0;i--){ b=bs[i]; if(b.kind==='star') continue;
let gone=null;
for(const s of bs){ if(s.kind!=='star') continue; const dx=b.x-s.x,dy=b.y-s.y,dz=b.z-s.z; if(dx*dx+dy*dy+dz*dz<s.Rau*s.Rau){ gone='absorbed'; break; } }
if(!gone){ const dx=b.x-c.x,dy=b.y-c.y,dz=b.z-c.z; if(dx*dx+dy*dy+dz*dz>500*500) gone='escaped'; }
if(gone){ bs.splice(i,1); ev.push({type:gone,body:b}); }
}
return ev;
}
function energy(bs){ let E=0; for(let i=0;i<bs.length;i++){ const A=bs[i]; E+=.5*A.m*(A.vx*A.vx+A.vy*A.vy+A.vz*A.vz);
for(let j=i+1;j<bs.length;j++){ const B=bs[j]; E-=G*A.m*B.m/Math.hypot(B.x-A.x,B.y-A.y,B.z-A.z); } } return E; }
// ---- Derived physics for any body, from its true mass and radius and its present state. SI constants (CODATA / IAU). ----
const C_KMS=299792.458, G_SI=6.6743e-11, MSUN_KG=1.98847e30, RSUN_AU=695700/AU_KM, DAY=86400;
function facts(b,world){
const GM=G_SI*b.m*MSUN_KG, Rm=b.R*1000, c=C_KMS*1000, o={};
o.g=GM/(Rm*Rm); // surface gravity, m/s^2
o.vesc=Math.sqrt(2*GM/Rm)/1000; // escape speed at the surface, km/s
o.rs=2*GM/(c*c); // Schwarzschild radius, m
o.dilation=GM/(Rm*c*c); // clocks at the surface run slow by this fraction (weak field)
o.bend=4*GM/(c*c*Rm)*206264.806; // deflection of light grazing the limb, arcseconds
if(b.kind==='star'||!world) return o;
const S=starCentre(world.bodies), mu=G*(S.m+b.m);
const rx=b.x-S.x,ry=b.y-S.y,rz=b.z-S.z, vx=b.vx-S.vx,vy=b.vy-S.vy,vz=b.vz-S.vz, r=Math.hypot(rx,ry,rz), v2=vx*vx+vy*vy+vz*vz;
const a=1/(2/r-v2/mu), hx=ry*vz-rz*vy,hy=rz*vx-rx*vz,hz=rx*vy-ry*vx, h2=hx*hx+hy*hy+hz*hz, e=Math.sqrt(Math.max(0,1-h2/(mu*a)));
o.r=r; o.a=a; o.e=e; o.speed=Math.sqrt(v2)*AU_KM/DAY; // km/s relative to the Sun
if(a>0){ o.period=2*Math.PI*Math.sqrt(a*a*a/mu); // days
o.hill=a*(1-e)*Math.cbrt(b.m/(3*S.m)); // Hill radius, AU: inside it the body's own gravity wins
const GMs=G_SI*S.m*MSUN_KG, am=a*AU_KM*1000;
o.gr=6*Math.PI*GMs/(c*c*am*(1-e*e))*206264.806*(36525/o.period); // general-relativistic perihelion advance, arcsec per century
o.sunDilation=GMs/(am*c*c)+v2*Math.pow(AU_KM*1000/DAY,2)/(2*c*c); } // clock rate lost to the Sun's potential plus orbital speed
return o;
}
// gravitational potential per unit mass at a point, in solar masses per AU (multiply by G for AU^2/day^2). Inside a body it stays at the surface value.
function potential(bs,x,y,z){ let p=0; for(const b of bs){ const d=Math.hypot(b.x-x,b.y-y,b.z-z); p+=b.m/Math.max(d,b.Rau); } return p; }
// ---- The Sun's future, after Schroder & Smith (2008, MNRAS 386, 155), Table 1. t = billions of years from now.
// Rows marked P are the paper's own models; the others are smooth joins between them (and a standard white-dwarf cooling track),
// there only so the picture does not jump. Columns: t, radius (present Sun = 1), surface temperature K, mass, stage.
const SUN=[
[0, 1, 5774, 1, 'Main sequence (today)','P'],
[2.55, 1.11, 5820, 1, 'Main sequence, at its hottest','P'],
[5.42, 1.37, 5751, 1, 'End of the main sequence','P'],
[7.00, 2.3, 4950, 0.998, 'Subgiant'],
[7.42, 9.5, 4540, 0.985, 'Red giant'],
[7.555, 70, 3450, 0.91, 'Red giant'],
[7.585, 180, 2850, 0.74, 'Red giant'],
[7.59, 256, 2602, 0.668, 'Tip of the red giant branch','P'],
[7.5903, 11.2, 4667, 0.668, 'Helium ignites: the Sun shrinks','P'],
[7.69, 16, 4500, 0.664, 'Burning helium'],
[7.714, 90, 3500, 0.61, 'Second ascent (asymptotic giant)'],
[7.72, 149, 3200, 0.546, 'Tip of the asymptotic giant branch','P'],
[7.7201, 179, 3467, 0.544, 'Final thermal pulse','P'],
[7.7212, 1.2, 30000, 0.5405, 'Envelope gone: the hot core is exposed'],
[7.723, 0.03, 100000,0.5405, 'New white dwarf'],
[7.80, 0.0135, 28000, 0.5405, 'White dwarf, cooling'],
[8.70, 0.0128, 9500, 0.5405, 'White dwarf, cooling'],
[12, 0.0126, 5000, 0.5405, 'White dwarf, cooling']
];
const T_END=SUN[SUN.length-1][0], T_TIP=7.59, T_EARTH=7.5895; // Earth is drawn in by tides just before the tip (the paper's result)
function sunAt(t){
t=Math.min(T_END,Math.max(0,t)); let i=0; while(i<SUN.length-2&&t>SUN[i+1][0]) i++;
const A=SUN[i],B=SUN[i+1],k=(t-A[0])/(B[0]-A[0]), R=Math.exp(Math.log(A[1])+(Math.log(B[1])-Math.log(A[1]))*k), T=Math.exp(Math.log(A[2])+(Math.log(B[2])-Math.log(A[2]))*k);
const M=A[3]+(B[3]-A[3])*k, L=R*R*Math.pow(T/5774,4); // luminosity from radius and temperature (Stefan-Boltzmann)
return {t,R,Rau:R*RSUN_AU,T,M,L,stage:k<.5?A[4]:B[4],modelled:(k<.02&&A[5]==='P')||(k>.98&&B[5]==='P'),hz:[.95*Math.sqrt(L),1.37*Math.sqrt(L)]};
}
// Planets in the far future. While the Sun loses mass slowly the orbits widen as a = a0 / M (angular momentum is conserved);
// a planet is lost when the Sun's surface reaches its closest approach. Planets that start inside 1.15 AU are also dragged in
// by tides near the tip of the red giant branch (Schroder & Smith's limit), which is what takes Earth.
const FUTURE=DEFS.filter(d=>d.kind==='planet').map(d=>{ const el=EL[d.el||'EMB'][0]; return {d,a0:el[0],e:el[1],I:el[2]*DEG,wb:el[4]*DEG,Om:el[5]*DEG,L0:el[3]*DEG,lost:null,why:''}; });
for(const p of FUTURE){ for(let t=0;t<=T_END;t+=t<7.3?.01:t<7.8?.00002:.01){ const s=sunAt(t); if(s.Rau>=p.a0/s.M*(1-p.e)){ p.lost=t; p.why='swallowed as the Sun swells'; break; } }
if((p.lost===null||p.lost>T_EARTH)&&p.a0<1.15){ p.lost=T_EARTH; p.why='dragged in by tides at the red giant tip'; } }
function future(t){ const s=sunAt(t); return {sun:s,planets:FUTURE.map(p=>({name:p.d.name,a0:p.a0,a:p.a0/s.M,e:p.e,lost:p.lost,why:p.why,alive:p.lost===null||t<p.lost,
teq:254.6*Math.pow(s.L,.25)/Math.sqrt(p.a0/s.M)}))}; } // equilibrium temperature for an Earth-like reflectivity of 0.3, kelvin
// a world frozen at time t: the Sun with its mass and size then, each surviving planet on its widened orbit. `clock` (days) only
// moves the planets round for display; real orbital positions that far ahead cannot be known.
function makeFuture(t,clock){
const s=sunAt(t), bodies=[body({name:'Sun',kind:'star',m:s.M,R:s.R*695700,Rau:s.Rau,color:0xffcc33,P:4332.6})];
for(const p of FUTURE){ if(p.lost!==null&&t>=p.lost) continue; bodies.push(body({name:p.d.name,kind:'planet',m:p.d.m,R:p.d.R,Rau:p.d.R/AU_KM,color:p.d.color,P:p.d.P})); }
const w={mode:'future',bodies,jd:clock,jd0:0,t}; placeFuture(w,t,clock); return w;
}
function placeFuture(w,t,clock){
const s=sunAt(t), S=w.bodies[0]; S.m=s.M; S.R=s.R*695700; S.Rau=s.Rau; S.x=S.y=S.z=S.vx=S.vy=S.vz=0; w.t=t; w.jd=clock;
for(let i=w.bodies.length-1;i>0;i--){ const b=w.bodies[i], p=FUTURE.find(q=>q.d.name===b.name);
if(p.lost!==null&&t>=p.lost){ w.bodies.splice(i,1); continue; }
const a=p.a0/s.M, n=K_GAUSS*Math.sqrt(s.M)/Math.pow(a,1.5); b.P=2*Math.PI/n;
let M=p.L0-p.wb+n*clock, E=M+p.e*Math.sin(M); for(let k=0;k<8;k++) E-=(E-p.e*Math.sin(E)-M)/(1-p.e*Math.cos(E));
const pos=u=>{ const xp=a*(Math.cos(u)-p.e),yp=a*Math.sqrt(1-p.e*p.e)*Math.sin(u), w2=p.wb-p.Om,cw=Math.cos(w2),sw=Math.sin(w2),cO=Math.cos(p.Om),sO=Math.sin(p.Om),cI=Math.cos(p.I),sI=Math.sin(p.I);
return ax3([(cw*cO-sw*sO*cI)*xp+(-sw*cO-cw*sO*cI)*yp,(cw*sO+sw*cO*cI)*xp+(-sw*sO+cw*cO*cI)*yp,sw*sI*xp+cw*sI*yp]); };
const P0=pos(E), P1=pos(E+1e-4), dt=1e-4*(1-p.e*Math.cos(E))/n; b.x=P0[0];b.y=P0[1];b.z=P0[2]; b.vx=(P1[0]-P0[0])/dt;b.vy=(P1[1]-P0[1])/dt;b.vz=(P1[2]-P0[2])/dt; }
return w;
}
return {G,AU_KM,DEFS,make,add,accel,advance,starCentre,energy,formula,ax3,facts,potential,sunAt,future,makeFuture,placeFuture,SUN,T_END,RSUN_AU};
})();
if(typeof module!=='undefined') module.exports=Sim;
gravity.js (scene + controls)380 lines
(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;i<n;i++){ const u=rnd()*2-1,t=rnd()*6.283,q=Math.sqrt(1-u*u); a[i*3]=q*Math.cos(t);a[i*3+1]=u;a[i*3+2]=q*Math.sin(t); }
const g=new THREE.BufferGeometry(); g.setAttribute('position',new THREE.BufferAttribute(a,3));
const p=new THREE.Points(g,new THREE.PointsMaterial({color:0x8fa6c4,size:1.6,sizeAttenuation:false,transparent:true,opacity:.7,depthWrite:false})); p.frustumCulled=false; sky.add(p); }
// ---------- 3D grid: a cube of lines along x, y and z, re-sized to the zoom level ----------
const NL=13,SEG=48,HC=(NL-1)/2, nV=3*NL*NL*(SEG+1);
const unit=new Float32Array(nV*3), gpos=new Float32Array(nV*3), gcol=new Float32Array(nV*3), gidx=new Uint32Array(3*NL*NL*SEG*2);
{ let v=0,k2=0;
for(let ax=0;ax<3;ax++) for(let i=0;i<NL;i++) for(let j=0;j<NL;j++){
const a=i-HC,b=j-HC;
for(let k=0;k<=SEG;k++){ const t=-HC+2*HC*k/SEG,o=v*3;
if(ax===0){unit[o]=t;unit[o+1]=a;unit[o+2]=b;} else if(ax===1){unit[o]=a;unit[o+1]=t;unit[o+2]=b;} else {unit[o]=a;unit[o+1]=b;unit[o+2]=t;}
if(k<SEG){ gidx[k2++]=v; gidx[k2++]=v+1; } v++; }
} }
const ggeo=new THREE.BufferGeometry();
ggeo.setAttribute('position',new THREE.BufferAttribute(gpos,3)); ggeo.setAttribute('color',new THREE.BufferAttribute(gcol,3)); ggeo.setIndex(new THREE.BufferAttribute(gidx,1));
const grid=new THREE.LineSegments(ggeo,new THREE.LineBasicMaterial({vertexColors:true,transparent:true,blending:THREE.AdditiveBlending,depthWrite:false}));
grid.frustumCulled=false; sc.add(grid);
const MAXB=64, bX=new Float64Array(MAXB),bY=new Float64Array(MAXB),bZ=new Float64Array(MAXB),bKM=new Float64Array(MAXB),bC2=new Float64Array(MAXB);
const PULL=.85, GR=.16,GG=.42,GB=.95;
let logK=null;
// Each grid point is displaced along the real gravitational acceleration at that point, sum of G*m/r^2 toward every body
// with the true masses. Real space-time curvature here is about one part in 100 million, so the size is multiplied by a
// zoom-dependent factor K to make it visible; the relative strength of every body is untouched. When following a body the
// grid is drawn in that body's free-fall frame (the uniform pull of everything else at its centre is subtracted), so what
// is left is its own well plus the tides.
function bendGrid(dt){
const bs=world.bodies,n=Math.min(bs.length,MAXB);
let mdom=1;
if(follow&&follow.kind!=='star'){ mdom=follow.m; for(const o of bs){ if(o===follow) continue; const d=Math.hypot(o.x-follow.x,o.y-follow.y,o.z-follow.z); mdom+=2*o.m*Math.pow(radius/d,3); } if(mdom>1) 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;b<n;b++){ const B=bs[b]; bX[b]=B.x-tgt.x;bY[b]=B.y-tgt.y;bZ[b]=B.z-tgt.z; bKM[b]=PULL*K*B.m; bC2[b]=Math.pow(K*B.m,2/3); }
if(follow){ const fi=bs.indexOf(follow), wt=Math.max(0,1-Math.hypot(off.x,off.y,off.z)/(.5*radius));
for(let b=0;b<n;b++){ if(b===fi) continue; const ex=bX[fi]-bX[b],ey=bY[fi]-bY[b],ez=bZ[fi]-bZ[b],r2=ex*ex+ey*ey+ez*ez+bC2[b],f=bKM[b]/(r2*Math.sqrt(r2))*wt; sx-=ex*f;sy-=ey*f;sz-=ez*f; } }
// lattice spacing is a power of two in AU; the cube is snapped to that lattice around the target
const s=Math.pow(2,Math.round(Math.log2(.16*radius))), ox=Math.round(tgt.x/s)*s-tgt.x, oy=Math.round(tgt.y/s)*s-tgt.y, oz=Math.round(tgt.z/s)*s-tgt.z;
const cx=cam.position.x,cy=cam.position.y,cz=cam.position.z, fr=1/(.66*radius*.66*radius), ig=1/(.1*radius), i13=1/(1.3*radius), i04=1/(.4*radius);
for(let o=0;o<nV*3;o+=3){
const px=ox+unit[o]*s,py=oy+unit[o+1]*s,pz=oz+unit[o+2]*s; let dx=-sx,dy=-sy,dz=-sz;
for(let b=0;b<n;b++){ const ex=px-bX[b],ey=py-bY[b],ez=pz-bZ[b],r2=ex*ex+ey*ey+ez*ez+bC2[b],f=bKM[b]/(r2*Math.sqrt(r2)); dx-=ex*f;dy-=ey*f;dz-=ez*f; }
const x=px+dx,y=py+dy,z=pz+dz; gpos[o]=x;gpos[o+1]=y;gpos[o+2]=z;
// brightness: lines glow where they are bent, fade toward the edge of the cube and with distance from the camera
let e=1-(px*px+py*py+pz*pz)*fr; if(e<=0){ gcol[o]=gcol[o+1]=gcol[o+2]=0; continue; }
const cd=Math.sqrt((x-cx)*(x-cx)+(y-cy)*(y-cy)+(z-cz)*(z-cz));
let f=1-(cd-.5*radius)*i13; f=f<0?0:f>1?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;i<SN;i++){ const a=(i-(SN-1)/2)/((SN-1)/2);
for(let k=0;k<=SS;k++){ const t=-1+2*k/SS; sU[v*2]=ax?a:t; sU[v*2+1]=ax?t:a; if(k<SS){ sidx[k2++]=v; sidx[k2++]=v+1; } v++; } } }
const sgeo=new THREE.BufferGeometry(); sgeo.setAttribute('position',new THREE.BufferAttribute(spos,3)); sgeo.setAttribute('color',new THREE.BufferAttribute(scol,3)); sgeo.setIndex(new THREE.BufferAttribute(sidx,1));
const sheet=new THREE.LineSegments(sgeo,new THREE.LineBasicMaterial({vertexColors:true,transparent:true,blending:THREE.AdditiveBlending,depthWrite:false})); sheet.frustumCulled=false; sc.add(sheet);
let gridMode='sheet', sheetK=null;
function bendSheet(dt){
const bs=world.bodies,n=Math.min(bs.length,MAXB), half=1.25*radius, soft=.014*radius;
let mdom=1, p0=0,gx=0,gz=0, fi=-1;
if(follow&&follow.kind!=='star'){ fi=bs.indexOf(follow); mdom=follow.m;
const wt=Math.max(0,1-Math.hypot(off.x,off.y,off.z)/(.5*radius));
for(let b=0;b<n;b++){ if(b===fi) continue; const o=bs[b], ex=follow.x-o.x,ey=follow.y-o.y,ez=follow.z-o.z,d=Math.hypot(ex,ey,ez); p0+=o.m/d*wt; gx-=o.m*ex/(d*d*d)*wt; gz-=o.m*ez/(d*d*d)*wt;
mdom+=o.m*Math.pow(radius/d,3); } // what is left of the others is their tide
if(mdom>1) 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<n;b++){ const B=bs[b]; bX[b]=B.x-tgt.x;bY[b]=B.y-tgt.y;bZ[b]=B.z-tgt.z; bC2[b]=Math.max(B.Rau,soft); bC2[b]*=bC2[b]; }
const inv=1/half, depth=.105*radius;
for(let v=0,o=0;v<sV;v++,o+=3){
const px=sU[v*2]*half, pz=sU[v*2+1]*half; let p=-p0-(gx*(px-fx)+gz*(pz-fz));
for(let b=0;b<n;b++){ const ex=px-bX[b],ey=bY[b],ez=pz-bZ[b]; p+=bs[b].m/Math.sqrt(ex*ex+ey*ey+ez*ez+bC2[b]); }
const q=Math.max(0,p*K), d=Math.log(1+2.4*q), y=-depth*d;
spos[o]=px; spos[o+1]=y; spos[o+2]=pz;
let e=1-(px*px+pz*pz)*inv*inv; e=e<0?0:e; const g=Math.min(1,d/4.2), br=e*e*(.16+.84*g);
scol[o]=(.14+.86*g*g*g)*br; scol[o+1]=(.42+.5*g*g)*br; scol[o+2]=.95*br;
}
sgeo.attributes.position.needsUpdate=true; sgeo.attributes.color.needsUpdate=true;
}
// the habitable zone: where sunlight would keep water liquid on an Earth-like planet, 0.95 to 1.37 AU times the square root of the Sun's brightness
const hz=new THREE.Mesh(new THREE.RingGeometry(.95,1.37,160).rotateX(-Math.PI/2),new THREE.MeshBasicMaterial({color:0x3fe08a,transparent:true,opacity:.1,side:THREE.DoubleSide,depthWrite:false}));
sc.add(hz); const hillGeo=(()=>{ 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(i<S.length-2&&T>S[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<TR;i++){ const f=Math.pow(1-i/TR,1.5)*.95; col[i*3]=c.r*f;col[i*3+1]=c.g*f;col[i*3+2]=c.b*f; } // newest point bright, tail fades to nothing
const g=new THREE.BufferGeometry(); g.setAttribute('position',new THREE.BufferAttribute(arr,3)); g.setAttribute('color',new THREE.BufferAttribute(col,3)); g.setDrawRange(0,0);
const trail=new THREE.Line(g,new THREE.LineBasicMaterial({vertexColors:true,transparent:true,blending:THREE.AdditiveBlending,depthWrite:false})); trail.frustumCulled=false; sc.add(trail);
let hill=null; if(!star&&!b.launched&&b.kind==='planet'){ hill=new THREE.Line(hillGeo,new THREE.LineBasicMaterial({color:b.color,transparent:true,opacity:.5,depthWrite:false})); hill.frustumCulled=false; hill.visible=false; sc.add(hill); }
vis.set(b.id,{mesh,lbl,trail,arr,rel:new Float64Array(TR*3),n:0,last:-1e99,rad:b.Rau,sx:0,sy:0,rpx:0,on:false,hill,hillR:0,glow:star?mesh.children[0]:null});
}
function dropVis(id){ const v=vis.get(id); if(!v) return; if(v.hill){ sc.remove(v.hill); v.hill.material.dispose(); } sc.remove(v.mesh); v.mesh.material.dispose(); sc.remove(v.trail); v.trail.geometry.dispose(); v.trail.material.dispose(); v.lbl.remove(); vis.delete(id); }
function clearTrails(){ for(const v of vis.values()){ v.n=0; v.last=-1e99; } }
function build(mode){
for(const id of [...vis.keys()]) dropVis(id);
world=mode==='future'?Sim.makeFuture(fut.t,fut.clock):Sim.make(jdNow(),mode); for(const b of world.bodies) addVis(b);
follow=null; setFollow(null); launchN=0; logK=null; sheetK=null; E0=null;
}
// ---------- the far future: the Sun's life from today to a cooling white dwarf ----------
const fut={on:false,t:0,x:0,clock:0,play:false};
const FX=[0,.4,.66,.74,.9,1], FT=[0,7.0,7.585,7.5905,7.7215,9.0]; // the slider stretches the fast parts of the story
const futT=x=>{ let i=0; while(i<FX.length-2&&x>FX[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(radius<need) radius+= (need-radius)*Math.min(1,dt*3); }
sampleTrails(world);
}
// Trails are recorded in the frame of the body being followed (or the system's centre of mass when following nothing),
// each body sampled 240 times per orbit, so following Earth shows the Moon's loop around it.
function sampleTrails(w){
const fx=follow?follow.x:0, fy=follow?follow.y:0, fz=follow?follow.z:0;
for(const b of w.bodies){ const v=vis.get(b.id); if(!v) continue;
if(Math.abs(w.jd-v.last)<b.P/240) continue; v.last=w.jd;
const a=v.rel; if(v.n<TR) v.n++; a.copyWithin(3,0,(TR-1)*3); a[0]=b.x-fx;a[1]=b.y-fy;a[2]=b.z-fz; }
}
function shiftSystem(dx,dy,dz){ // Galilean shift of everything at once: no orbit changes
for(const b of world.bodies){ b.x+=dx;b.y+=dy;b.z+=dz; }
if(!follow) for(const v of vis.values()){ const a=v.rel; for(let i=0;i<v.n*3;i+=3){ a[i]+=dx;a[i+1]+=dy;a[i+2]+=dz; } }
}
const PX={star:7,planet:4,moon:3};
function syncBodies(){
const fx=(follow?follow.x:0)-tgt.x, fy=(follow?follow.y:0)-tgt.y, fz=(follow?follow.z:0)-tgt.z;
const pxw=2*Math.tan(cam.fov*Math.PI/360)/H; let li=0;
for(const b of world.bodies){ const v=vis.get(b.id), x=b.x-tgt.x,y=b.y-tgt.y,z=b.z-tgt.z;
const dist=Math.hypot(x-cam.position.x,y-cam.position.y,z-cam.position.z);
// true radius, but never smaller than a few pixels so the body stays visible
v.rad=Math.max(b.Rau,(b.launched?3:PX[b.kind])*pxw*dist); v.rpx=v.rad/(pxw*dist);
v.mesh.position.set(x,y,z); v.mesh.scale.setScalar(v.rad);
if(v.hill){ v.hill.visible=v.hillR>0; 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<m;i+=3){ a[i]=r[i]+fx;a[i+1]=r[i+1]+fy;a[i+2]=r[i+2]+fz; } a[0]=x;a[1]=y;a[2]=z;
v.trail.geometry.attributes.position.needsUpdate=true; v.trail.geometry.setDrawRange(0,v.n); }
}
for(;li<2;li++) lights[li].intensity=0;
// labels: hide one when a heavier body sits almost on top of it on screen
for(const b of world.bodies){ const v=vis.get(b.id); let show=v.on&&v.sx>-40&&v.sx<W+40&&v.sy>0&&v.sy<H;
if(show&&b!==follow) for(const o of world.bodies){ if(o===b||(o.m<=b.m&&o!==follow)) continue; const u=vis.get(o.id); if(u.on&&Math.hypot(u.sx-v.sx,u.sy-v.sy)<16){ show=false; break; } }
v.lbl.style.display=show?'block':'none'; if(show) v.lbl.style.transform='translate('+v.sx.toFixed(1)+'px,'+(v.sy-v.rpx-6).toFixed(1)+'px) translate(-50%,-100%)'; }
}
// ---------- camera: on a sphere around a target (the centre of mass, or the body being followed) ----------
let theta=.5, phi=1.0, radius=4, fit=4, follow=null, radiusGoal=null, radiusBack=null;
const PHI_MIN=.05, PHI_MAX=Math.PI-.05, R_MAX=160;
const tgt={x:0,y:0,z:0}, off={x:0,y:0,z:0};
const rMin=()=>follow?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=W<H?1.5:1; return (b.name==='Earth'?.009:b.name==='Moon'?.0012:b.Rau*45)*k; }
function setFollow(b){
const gx=b?b.x:0, gy=b?b.y:0, gz=b?b.z:0; off.x=tgt.x-gx; off.y=tgt.y-gy; off.z=tgt.z-gz;
if(b){ if(radiusBack===null) radiusBack=radius; const z=zoomFor(b); radiusGoal=z===null?radiusBack:Math.min(radiusBack,z); }
else { if(radiusBack!==null) radiusGoal=radiusBack; radiusBack=null; }
if(b!==follow){ follow=b; clearTrails(); }
$('chip').hidden=!b; if(b){ $('chipname').textContent=b.name; infoT=0; }
}
function updateCam(dt){
if(follow&&world.bodies.indexOf(follow)<0) setFollow(null);
const k=Math.exp(-dt*5); off.x*=k;off.y*=k;off.z*=k;
tgt.x=(follow?follow.x:0)+off.x; tgt.y=(follow?follow.y:0)+off.y; tgt.z=(follow?follow.z:0)+off.z;
if(radiusGoal!==null){ const l=Math.log(radius)+(Math.log(radiusGoal)-Math.log(radius))*(1-Math.exp(-dt*3.5)); radius=Math.exp(l); if(Math.abs(radius/radiusGoal-1)<.002){ radius=radiusGoal; radiusGoal=null; } }
placeCam();
}
function resize(){
const w=stage.clientWidth||innerWidth, h=stage.clientHeight||innerHeight; if(w===W&&h===H) return;
W=w;H=h; R.setPixelRatio(Math.min(window.devicePixelRatio||1,2)); R.setSize(W,H,false);
cam.aspect=W/H; cam.fov=W<H?70:60; cam.updateProjectionMatrix();
const nf=2.3/(Math.tan(cam.fov*Math.PI/360)*Math.min(cam.aspect,1)), s=nf/fit; fit=nf; // keep the same framing in portrait and landscape
radius=Math.min(R_MAX,radius*s); if(radiusGoal!==null) radiusGoal*=s; if(radiusBack!==null) radiusBack*=s;
}
addEventListener('resize',resize); addEventListener('orientationchange',()=>setTimeout(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<Math.max(34,s.rpx*1.15)&&d<bd){ bd=d;best=b; } } return best; }
function pick(x,y){ // nearest body under the finger; tapping again where bodies overlap steps to the next one (Earth -> 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=>'<tr><td>'+p.name+'</td><td>'+(p.alive?num(p.a,2)+' AU':'gone')+'</td><td>'+(p.alive?(p.a>=s.hz[0]&&p.a<=s.hz[1]?'in the liquid-water zone':num(p.teq,0)+' K'):p.why)+'</td></tr>').join('');
sci.innerHTML='<b>'+s.stage+'</b><span>Sun: '+num(s.M,3)+' of today\'s mass · '+sig(s.R)+' × radius ('+fmtDist(s.Rau)+') · '+sig(s.L)+' × brightness · '+num(s.T,0)+' K</span><span>Liquid-water zone '+sig(s.hz[0])+' to '+sig(s.hz[1])+' AU (green band)</span><table>'+rows+'</table><i>'+(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.</i>';
} 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='<span>Newtonian gravity between every pair, true masses · leapfrog steps ≤ '+(world.mode==='binary'?'1.2':'4.8')+' h</span><span>Energy drift since start: '+((E-E0.E)/Math.abs(E0.E)).toExponential(1)+'</span>';
}
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=>'<span>'+l+'</span>').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;i<sec*60;i++) ev.push(...Sim.advance(world,dps/60).map(e=>e.type+':'+e.body.name)); return ev; }};
requestAnimationFrame(frame);
})();
gravity.css65 lines
:root{--ink:#cfe6ff;--dim:#7f9bb8;--line:#27425f;--panel:rgba(8,17,30,.78);--accent:#7fc4ff;--on:#ffd27a}
*{box-sizing:border-box;-webkit-tap-highlight-color:transparent}
[hidden]{display:none!important}
html,body{margin:0;height:100%;background:#02050a;overflow:hidden;touch-action:none;-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;font:15px/1.2 system-ui,-apple-system,"Segoe UI",sans-serif;color:var(--ink)}
#stage{position:fixed;inset:0}
canvas{display:block;width:100%;height:100%;touch-action:none}
#labels{position:fixed;inset:0;pointer-events:none;overflow:hidden}
.lbl{position:absolute;left:0;top:0;font-size:12px;color:#dde8f5;text-shadow:0 0 4px #000,0 0 2px #000;white-space:nowrap;will-change:transform}
button{font:inherit;color:var(--ink);background:var(--panel);border:1px solid var(--line);border-radius:12px;min-height:48px;min-width:48px;padding:0 16px;display:inline-flex;align-items:center;justify-content:center;gap:8px;touch-action:manipulation;cursor:pointer;-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);white-space:nowrap}
button:active{background:rgba(30,55,85,.9)}
button[aria-pressed=true]{border-color:var(--on);color:var(--on);background:rgba(60,44,12,.82)}
button svg{width:18px;height:18px;fill:currentColor;flex:none}
#top{position:fixed;top:0;left:0;right:0;display:flex;justify-content:space-between;align-items:flex-start;gap:10px;pointer-events:none;
padding:calc(10px + env(safe-area-inset-top)) calc(12px + env(safe-area-inset-right)) 0 calc(12px + env(safe-area-inset-left))}
#left{display:flex;flex-direction:column;align-items:flex-start;gap:8px;min-width:0}
#date{font-size:17px;font-weight:600;color:#fff;text-shadow:0 0 5px #000;font-variant-numeric:tabular-nums;padding:4px 2px 0}
#chip{pointer-events:auto;border-color:var(--accent);color:var(--accent);padding:6px 14px;flex-direction:column;align-items:flex-start;gap:3px;white-space:normal;text-align:left}
#chip b{color:#fff;font-weight:600}
#chip .x{opacity:.75;font-size:18px;line-height:1;margin-left:6px}
#chipinfo{font-size:12.5px;color:var(--dim);font-variant-numeric:tabular-nums}
#reset{pointer-events:auto;margin-left:auto;flex:none}
#bar{position:fixed;left:0;right:0;bottom:0;display:flex;flex-wrap:wrap;align-items:center;gap:10px;
padding:10px calc(12px + env(safe-area-inset-right)) calc(10px + env(safe-area-inset-bottom)) calc(12px + env(safe-area-inset-left));
background:linear-gradient(to top,rgba(2,5,10,.9),rgba(2,5,10,0));touch-action:none}
#speedwrap{flex:1 1 220px;min-width:0;display:flex;align-items:center;gap:12px;min-height:48px;padding:0 14px;background:var(--panel);border:1px solid var(--line);border-radius:12px;-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px)}
#speedwrap span{color:var(--dim);font-size:13px}
#speedval{min-width:5.6em;text-align:right;color:var(--ink)!important;font-size:15px!important;font-variant-numeric:tabular-nums}
#speed{flex:1;min-width:60px;height:48px;margin:0;background:transparent;-webkit-appearance:none;appearance:none;touch-action:none}
#speed::-webkit-slider-runnable-track{height:6px;border-radius:3px;background:#27425f}
#speed::-moz-range-track{height:6px;border-radius:3px;background:#27425f}
#speed::-webkit-slider-thumb{-webkit-appearance:none;width:30px;height:30px;margin-top:-12px;border-radius:50%;background:var(--accent);border:3px solid #06101c}
#speed::-moz-range-thumb{width:26px;height:26px;border-radius:50%;background:var(--accent);border:3px solid #06101c}
@media (max-width:620px){#speedwrap{flex-basis:100%;order:-1}#bar button{flex:1 1 0;padding:0 8px}}
@media (max-height:460px){button,#speedwrap{min-height:44px}#bar{gap:8px;padding-top:6px}}
#hint,#toast{position:fixed;left:16px;right:16px;text-align:center;pointer-events:none;transition:opacity .8s;text-shadow:0 0 4px #000}
#hint{bottom:calc(140px + env(safe-area-inset-bottom));color:var(--dim);font-size:13px;line-height:1.5}
@media (min-width:621px){#hint{bottom:calc(84px + env(safe-area-inset-bottom))}}
#toast{top:calc(96px + env(safe-area-inset-top));color:var(--on);font-size:14px;opacity:0}
#err{display:none;position:fixed;inset:20px;color:#f88;font:14px system-ui;z-index:9;pointer-events:none}
/* science read-outs and the far-future timeline (2026-11-18) */
#sci{max-width:min(420px,calc(100vw - 110px));padding:2px 2px 0;font-size:11.5px;line-height:1.35;color:var(--dim);text-shadow:0 0 4px #000,0 0 2px #000;font-variant-numeric:tabular-nums;display:flex;flex-direction:column;gap:2px}
#sci b{color:var(--on);font-size:13.5px;font-weight:600}
#sci i{font-style:normal;opacity:.8;font-size:10.5px}
#sci table{border-collapse:collapse;margin:2px 0}
#sci td{padding:0 10px 0 0;white-space:nowrap}
#sci td:first-child{color:var(--ink)}
#sci td:last-child{white-space:normal}
#chipinfo{display:flex;flex-direction:column;gap:2px}
#timewrap{display:none;flex:1 1 220px;min-width:0;align-items:center;gap:12px;min-height:48px;padding:0 14px;background:var(--panel);border:1px solid var(--on);border-radius:12px;-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px)}
#timewrap span{color:var(--dim);font-size:13px;white-space:nowrap}
#timeline{flex:1;min-width:60px;height:48px;margin:0;background:transparent;-webkit-appearance:none;appearance:none;touch-action:none}
#timeline::-webkit-slider-runnable-track{height:6px;border-radius:3px;background:linear-gradient(90deg,#ffe9a8,#ffb060 60%,#ff5a2a 74%,#9fc0ff)}
#timeline::-moz-range-track{height:6px;border-radius:3px;background:linear-gradient(90deg,#ffe9a8,#ffb060 60%,#ff5a2a 74%,#9fc0ff)}
#timeline::-webkit-slider-thumb{-webkit-appearance:none;width:30px;height:30px;margin-top:-12px;border-radius:50%;background:var(--on);border:3px solid #06101c}
#timeline::-moz-range-thumb{width:26px;height:26px;border-radius:50%;background:var(--on);border:3px solid #06101c}
body.future #timewrap{display:flex}
body.future #speedwrap,body.future #launch,body.future #binary{display:none}
@media (max-width:620px){#timewrap{flex-basis:100%;order:-1}#bar button{font-size:13px;gap:5px}#sci table{font-size:11px}}
#toast{top:auto!important;bottom:calc(150px + env(safe-area-inset-bottom))}
@media (min-width:621px){#toast{bottom:calc(92px + env(safe-area-inset-bottom))}}
#hint{bottom:calc(190px + env(safe-area-inset-bottom))}
@media (min-width:621px){#hint{bottom:calc(128px + env(safe-area-inset-bottom))}}
@media (max-width:620px){#launch svg,#binary svg,#future svg,#gridbtn svg{display:none}#sci i{display:none}#sci{max-width:calc(100vw - 100px)}}
errors.js2 lines
addEventListener('error',e=>{const d=document.getElementById('err');d.style.display='block';d.textContent='Error: '+e.message;});
Have an idea of your own?
Look around your day, find the thing that wastes your time, and build the fix. Everything here is free to help you start. If you would rather I built it, or you just want to talk an idea through, write to me.