Taos Explorer does not stop at the top of the atmosphere. You can climb out of a city street to orbit, ride the International Space Station, fly a rocket to the Moon and stand in a lunar crater, fly on to Mars, or go into orbit over Jupiter's clouds and through Saturn's rings, without a loading screen. That puts a set of problems in front of the renderer that a ground-bound sky never has: the stars have to be the real stars, in the right place for your latitude and the clock; the Moon has to be in its real place with its real phase, and its shadow has to fall on the right town at the right minute; the planets, their moons, the asteroids and the comets have to be where they really are, visible from hundreds of millions of kilometers away without wrecking the depth buffer of the ground you are standing on; Earth seen from orbit has to look like Earth even where no terrain tiles have loaded; and the sixteen thousand objects that really orbit Earth have to move across the sky at the right speed without costing a frame. The answer is a mix of baked data (a star catalog, satellite element sets, NASA imagery, the brightest 150,000 asteroids), published ephemerides, and a family of cheap full-screen passes that paint onto sky pixels only, so that real geometry always wins the depth contest without ever entering it.
One universe, many bodies
explorer/main.ts (Body, earthBody / moonBody / marsBody, pickActiveBody, moonCenterAt, marsCenterAt) · explorer/lib/space/space_frame.ts · explorer/lib/space/body_tiles.ts · src/geo/live/planets.ts (planetGeocentric, j2000ToEcef) · src/geo/geo_sky.ts (CelestialBodyView, CurvedHorizonSky)
Everything in Explorer lives in a single coordinate system in meters, with Earth's center at
the origin. Near the Earth its axes are the Earth's own: Earth-centered, Earth-fixed (ECEF), the
frame the tiles, roads and places are baked in. The Moon and Mars are not separate scenes you
load into; they are bodies placed somewhere in that same space, each with its own 3D Tiles
terrain offset to its center. By default that terrain is Explorer's own tilesets, baked from
NASA's LRO (LOLA, LROC), MOLA, ESA's HRSC, Viking and HiRISE data and USGS mosaics; Cesium's Moon
Terrain and Mars assets are the fallback. The other planets and moons are in the same space
too, drawn but never tiled (below). The engine never renders in ECEF
directly. A floating-origin
GeoFrame re-anchors under the camera every 10 km (REANCHOR_DIST),
and maps ECEF to a local world frame whose axes are the anchor's east, up and minus-north, so
all GPU positions stay small enough for 32-bit floats. The frame
deep dive covers that machinery; this page is about what lives far from the origin.
Each body is a small record:
interface Body {
name: 'Earth' | 'Moon' | 'Mars';
centerEcef: Vec3d; // its center in the shared universe
radius: number;
hasAtmosphere: boolean;
groundAlbedo: [number, number, number]; // the painted globe's fill color
groundRadiusAtEcef(ec: Vec3d): number; // WGS84 / sphere / biaxial spheroid
atmosphere?: CelestialBodyAtmosphere; // per-body scattering tint
}
| Body | Center | Ground radius | Air | Painted fill |
|---|---|---|---|---|
| Earth | origin | WGS84 ellipsoid at the camera (geodetic height subtracted) | Rayleigh 5.5/13.0/22.4 ×10⁻⁶, Mie 12×10⁻⁶ (EARTH_AIR) | procedural continents, or NASA imagery |
| Moon | real direction from the lunar ephemeris, at the MOON DIST setting (default 60 Earth radii ≈ 382,688 km) scaled by the real distance over 384,400 km | sphere, 1,737,400 m | none | gray 0.16 |
| Mars | real direction and distance from the planetary ephemeris (55–400 million km), held still while you head for it or are there | biaxial spheroid 3,396,190 / 3,376,200 m | red-dominant Rayleigh 21/12/6 ×10⁻⁶, Mie 9×10⁻⁶, 80 km shell | rust 0.30 / 0.13 / 0.06 |
Two consequences of this layout are worth spelling out. First, the Moon really orbits: each
frame moonCenterAt(clock.utcMs, moonDistance) recomputes its ECEF position from
the ephemeris, so it rises and sets and goes through its phases with the simulation clock. The
distance is the only liberty taken (the MOON DIST slider can pull it in to 3 Earth radii so the
trip is shorter), and even then the perigee–apogee variation survives because the setting is
scaled by m.distanceKm / 384,400. Second, Mars is where the real one is:
marsCenterAt(clock.utcMs) takes its geocentric position from JPL's approximate
planetary elements (the engine's planets.ts, under a twentieth of a degree from
JPL Horizons over 2000–2050), precesses it to the date and turns it into Earth-fixed axes, at
its true distance. The light at Mars is the Sun seen from there (marsSunEcefDir), up to about 45°
from the Earth's. From the Earth its disc is a few arcseconds, under a pixel, so the
distant-body pass draws it as a point of light as bright as its magnitude (below).
Three frames
Earth-fixed axes turn once a day. In them Mars, hundreds of millions of kilometers off, would
sweep round the Earth at thousands of km/s, and the Sun and the stars would wheel past a ship
in deep space. So the universe's axes change with where you are (space_frame.ts):
- earth. Earth-fixed, within a few Moon distances of the Earth.
- space. Centered on the Earth with its axes held still, out between the worlds: nothing turns, the planets move only as fast as they really do, and the Earth turns under it.
- mars. Mars' own IAU axes (its pole, its prime meridian), about Mars held where it was on arrival. Its tiles are baked in those axes, so they stand still, and the Sun, the stars and the Earth go round its sky once a sol.
Every position is computed from the Earth's center in the J2000 equator and mapped in as X = c + Rot·(g − o), where c is the frame's center in the universe, o its center's J2000 place and Rot the J2000-to-frame rotation. Changing frame is a rigid move of the whole universe, made out in space where only spheres are drawn.
The active body
One body at a time is active: the one whose surface is nearest the camera. The active body drives everything that depends on "the planet below": the atmosphere dome's center and ground radius, aerial perspective, the star fade, the near and far planes, fly speed, shadow range, which tileset is drawn as geometry. Choosing it is a nearest-surface test with a hysteresis margin, because the two bodies on either side of the switch are very differently scaled and the camera can sit at the crossover for a long time on a slow approach:
const MARGIN = 0.1; // challenger must be 10% closer to steal "active"
let best = candidates.includes(activeBody) ? activeBody : earthBody;
let bestD = surfaceDist(best, ec);
for (const b of candidates) {
if (b === best) { continue; }
const d = surfaceDist(b, ec);
if (d < bestD * (1 - MARGIN)) { best = b; bestD = d; }
}
The switch has side effects that are easy to underestimate. A body's tiles only render while it
is active (the others become painted spheres, see below), so on a
flight to the Moon the lunar terrain only starts streaming at the crossover, roughly halfway.
And the active body only flips once its tiles exist (liveExtraBodies() requires a
built tileset), so right after arriving at a lunar preset the camera can be on the Moon while
Earth is still "active". The code closes that window explicitly: the lunar
orbit freezes on place.moon || activeBody === moonBody || committedToMoon, where
"committed" means the Moon's surface is already nearer than Earth's, so the ground never slides
out from under a freshly landed camera.
Frames and the clock
src/geo/live/frames.ts (julianDate, gmst, temeToEcef, sunEciUnit, isSunlit) · src/geo/live/sun.ts (greenwichSiderealRad, equatorialToEcef) · src/geo/geo_sky.ts (earthCelestialMatrix) · explorer/main.ts (the sidereal freeze)
Every celestial object in Explorer starts in an inertial frame and ends up as a direction in the floating-origin world. There are three sources, and they do not use the same path:
Two sidereal angles
The angle the Earth has turned under the stars, Greenwich mean sidereal time, appears twice
in the code base, deliberately. The satellite layer uses the IAU-82 polynomial in
frames.ts, because that is the gstime the SGP4 propagator itself uses,
and the rotation from TEME to ECEF must agree with the propagator to the meter. The sky uses the
linear almanac form in sun.ts:
- ddays since J2000.0 (2000-01-01 12:00 UTC), from the clock's UTC milliseconds
- TJulian centuries since J2000.0, from a Vallado
jdayJulian date with the sub-day fraction kept in full
The two agree to far better than a star map needs; they differ only in the tiny higher-order terms. Both take UT1 ≈ UTC and ignore polar motion and the equation of the equinoxes, which the source says outright: "well below this layer's needs".
Placing the catalog sky
The star map is baked once in equatorial coordinates. To put it in the sky the stars pass needs a 3×3 matrix that takes a world-space view ray to the shader's equatorial frame (Y toward the north celestial pole, right ascension 0 along −X, 90° along −Z). Explorer builds it every frame from the floating frame's tangent basis and the sidereal angle:
export function earthCelestialMatrix(east, north, up, gmstRad, out: Float32Array) {
const c = Math.cos(gmstRad), s = Math.sin(gmstRad);
// World basis vectors expressed in ECEF: X = east, Y = up, Z = −north.
const cols = [east, up, { x: -north.x, y: -north.y, z: -north.z }];
for (let k = 0; k < 3; k++) {
const v = cols[k];
const ex = c * v.x + s * v.y; // rotate about the pole by the sidereal angle
const ey = -s * v.x + c * v.y;
const ez = v.z;
// Shader equatorial frame: s = (−e.x, e.z, −e.y)
out[k * 3] = -ex; out[k * 3 + 1] = ez; out[k * 3 + 2] = -ey;
}
return out;
}
Because the matrix is built from the current frame's east/north/up, it stays right across every re-anchor: the world axes turn as the anchor moves around the globe, and the matrix turns with them. The final swizzle is a reflection (its determinant is −1), which the source describes as the correction for the equirect's handedness when it is viewed from inside the sphere. The pole lands at an altitude equal to your latitude automatically, since the up vector of a mid-latitude anchor is tilted from the ECEF Z axis by exactly the colatitude.
Freezing the sky in space
The simulation clock can run at hundreds of times real speed. On the ground that is the point: you watch the sky wheel overhead through a night. In space it looks wrong, a starfield visibly spinning around the camera, so Explorer holds the sky still above the atmosphere. The applied angle follows the live one by (1 − spaceT) of the difference per frame, where spaceT ramps from 0 at 20 km to 1 at 45 km over Earth and is 1 everywhere off Earth:
const gmst = greenwichSiderealRad(issRide ? Date.now() : clock.utcMs);
const spaceT = activeBody === earthBody
? Math.max(0, Math.min(1, (starsFeature.altitude - 20000) / 25000))
: 1;
// shortest signed angle from the applied sky to the live one
const delta = ((gmst - starsGmst) % twoPi + 3 * Math.PI) % twoPi - Math.PI;
starsGmst += delta * (1 - spaceT);
starsFeature.celestialMatrix = earthCelestialMatrix(geoFrame.east, geoFrame.north, geoFrame.up, starsGmst, starsCelestial);
The ISS ride uses the wall clock (Date.now()) rather than the simulation clock,
because the station itself is propagated at real UTC. On descent the applied angle eases back
to the live one instead of snapping.
Nine thousand stars in a texture
scripts/build_star_catalog.mjs · src/assets/star_catalog_data.ts · src/assets/star_catalog.ts (bakeStarCatalogTexture) · src/shaders/modules/postfx_stars.wgsl · src/renderer/render_graph/passes/stars_pass.ts
The stars are the Yale Bright Star Catalog, 5th revised edition (BSC5): every star visible to
the naked eye. A build script reads a public-domain JSON copy of it, parses right ascension
(hours/minutes/seconds) and declination (degrees/arcminutes/arcseconds) into radians, takes the
visual magnitude V and the color temperature K, and writes four 32-bit floats per star into a
base64 string inside a TypeScript module. 9,096 stars survive parsing. The module is about
190 KB and is only pulled in by a dynamic import() when catalog stars are
actually wanted. Records without a usable temperature default to a sun-like 5,800 K, and every
temperature is clamped to 1,500–40,000 K.
From magnitude and temperature to an HDR texel
Astronomical magnitude is logarithmic and backward: five magnitudes is a factor of 100 in flux, and smaller is brighter. The bake converts it to linear flux relative to a magnitude-0 star, and turns the temperature into a hue whose luminance is exactly 1, so the two never fight: flux decides how bright, temperature only decides the color.
- mvisual magnitude; stars fainter than 6.5 are skipped (the catalog's own limit is about there)
- rgb(K)Tanner Helland's piecewise blackbody fit in sRGB 0–255, clamped, de-gammaed to linear
- YRec. 709 luminance 0.2126 R + 0.7152 G + 0.0722 B, floored at 10⁻⁴
Each star is then splatted additively into a float32 accumulation buffer as a small Gaussian centered on its exact sub-texel position. The width grows slightly with brightness, so the brightest stars seed a hint of a disc for bloom to pick up:
const u = ra / TWO_PI; // 0..1
const v = 0.5 - dec / Math.PI; // Dec +90 → 0 (top)
// Tight gaussian so stars stay near point-like; only the very brightest get
// a slightly wider splat (disc / bloom seed).
const sigma = starSize * (1 + 0.6 * Math.min(flux, 4) / 4);
const radius = Math.max(1, Math.ceil(sigma * 2));
…
// Wrap longitude (equirect is periodic in u).
let px = (cx + dx) % W; if (px < 0) { px += W; }
const w = Math.exp(-(ddx * ddx + ddy * ddy) * inv2s2);
accum[idx] += cr * w; accum[idx + 1] += cg * w; accum[idx + 2] += cb * w;
With the default starSize of 0.5 texel, σ runs from just over 0.5 for the faintest
stars to 0.79 for Sirius (magnitude −1.46, the only star with flux near the cap of 4). Since σ is
always a little above 0.5, the footprint radius ceil(2σ) is 2 for every star: a
5×5-texel kernel. The accumulated floats are converted by hand to IEEE half floats (with
subnormals flushed to zero, which is harmless for stars) and uploaded as an
rgba16float texture. Explorer asks for a 4096-wide equirect on desktop and 2048 on
phones; the comment at the call site gives the reason, "the 4096 bake is 64 MB of GPU memory"
(4096 × 2048 texels × 8 bytes). The half-float scratch arrays are module-level on purpose: the
conversion runs once per channel per texel, some 33 million times for the 4096 bake.
One texel of the 4096 map spans 360°/4096 ≈ 5.3 arcminutes. With Explorer's 60° vertical
field of view on a 1080-pixel-tall canvas a pixel spans 3.3 arcminutes, so a texel is about
1.6 pixels and the 5×5 splat covers a few pixels. That is the antialiasing: stars are never
rasterized as points, so they cannot flicker between pixels as the camera turns. The texture
is sampled with bilinear filtering at mip 0 only (textureSampleLevel(…, 0.0),
no mip chain is built), with a sampler that repeats in u across the 0°/360° seam and clamps
in v at the poles. One trait of an equirect bake follows directly: the splat is round in
texels, and texels narrow in right ascension by cos(declination), so stars very near the
celestial poles come out slightly compressed east–west; the bake does not correct for it.
The gain, and what the curve looks like
The stars pass multiplies catalog samples by catalogBrightness, which Explorer's
starsBrightness setting defaults to 4 (slider 0–8). The comment is blunt
about why: "the raw BSC5 flux is dim, so it defaults to 4 for a sky that reads". The pass then
adds the result to the HDR scene before tone mapping and exposure, so a magnitude-0 star
contributes an HDR value around 4 times its Gaussian weight, and the faintest stars about 0.01.
skyExtinction = 6), applied per pixel on top.There is no twinkle. The star path in stars.wgsl has no time input at all; the
only animated thing in the pass is the aurora. Scintillation is an effect of looking through
turbulent air near the horizon, and simulating it as a per-star flicker would also make every
star a temporal-antialiasing problem.
The procedural fallback
Until the asynchronous bake completes, and whenever the "real stars" setting is off, the same
pass draws a procedural field instead: a 300 × 150 cell grid over the equirect, a hash per
cell, a star where the hash exceeds 1 − 0.18·cos(latitude) (fewer cells qualify
near the poles, where equirect cells shrink), a 3×3 neighborhood search so stars near cell
edges aren't cut, a Gaussian exp(−500·d²) glow in cos-latitude-corrected cell
space, and five fixed tints from blue-white to orange. The bake is a plain asynchronous loop
on the main thread after the lazy import; the catalog mode only takes effect once both the flag
and the texture are set, so there is no frame without stars.
When the stars come out
src/geo/geo_sky.ts (CurvedHorizonStarsFeature.update, CurvedHorizonSky.update) · src/shaders/stars.wgsl · src/renderer/render_graph/passes/stars_pass.ts
The stars pass is one full-screen triangle that reads the lit HDR scene and the depth buffer,
and only touches background pixels (dz_is_background(depth), which accounts for
reversed-Z). It is registered after lighting, water and the point-cloud pass and before god
rays, clouds and bloom, so clouds hide the stars and the brightest stars bloom. When nothing it
could draw is visible, it adds no pass at all: StarsPass.contributes checks the night
factor times the visibility from the last update, and in daylight the graph never sees it.
How visible the stars are comes from two separate reasons to see them, and the stronger one wins:
- hcamera altitude over the active body's local ground radius; 60 km is the atmosphere shell, so the fade starts about 7 km up and is complete about 45 km up, where the sky is nearly black
- ŝ, ûunit vector toward the real Sun and the local radial up; the night gate opens as the Sun sinks past about 3° below the horizon and is fully open by about 9°
The shader was written for ground scenes and gates on a sun elevation, not on a visibility number. Rather than fork it, the feature inverts the shader's own formula and hands it a fake sun whose elevation reproduces v exactly:
// Invert night_t = saturate((-sunY - 0.05)*10) so night_t == vis.
const fakeSunY = -0.05 - vis * 0.1;
this.pass!.updateParams(frame.ctx, frame.camera.inverseViewProjectionMatrix(),
frame.camera.position(), { x: 0, y: fakeSunY, z: 0 });
Three more terms shape where stars appear on screen:
- Sky extinction. Each star is multiplied by
exp(−L·skyExtinction), where L is the luminance of the sky already in the pixel. The curved-horizon feature sets it to 6, "tuned against this scene's HDR sky luminance". A black zenith passes stars untouched while the bright band at the horizon eats them, so at twilight and from the edge of space the stars thin out toward the glow with no hard edge. The same term handles stars seen through the daytime sky from 30 km up. - The lower hemisphere. On the ground, stars stop just above the
geometric horizon (
saturate(ray.y·20)). As you climb,lowerHemisphereis set to valt, lifting that clamp so stars wrap the whole sphere: from orbit you can look "down" past the limb into a starry sky. On Mars it is forced to 1 (toHorizon), because Mars' thin air leaves no haze in that band and the clamp would leave a black strip under the Milky Way. - The planet as an occluder. The painted globe is drawn by the
atmosphere pass, which writes no depth. So the stars pass does its own ray–sphere test against
the active body (center and ground radius from
CurvedHorizonSky) and skips any ray that strikes it in front of the camera. Without it, stars would shine through Earth seen from orbit.
The atmosphere pass carries its own procedural star field for ground scenes. In curved-horizon
mode (Explorer's default) setStarsHidden(true) turns it off, since it would double
the stars in a non-rotating frame. The pass also has a visibility uniform intended
for cloud cover; Explorer leaves it at 1 and relies on pass order instead, letting the
volumetric clouds drawn afterward cover the stars physically (see the
clouds deep dive).
The Milky Way and the aurora
src/shaders/modules/postfx_stars.wgsl (postfx_milky_way) · src/shaders/modules/postfx_aurora.wgsl · src/renderer/render_graph/passes/stars_pass.ts (GALACTIC_MATRIX) · explorer/main.ts (MILKY_WAY_GAIN, effects)
The catalog is point stars only, and the diffuse light of the galaxy is what makes a dark-site sky look full. Explorer adds it procedurally, fixed in galactic coordinates so it sits where the real band does and turns with the catalog. The pass composes two rotations per pixel, the celestial matrix and a constant J2000 equatorial-to-galactic matrix built from the north galactic pole and the direction of the galactic center:
if (star_uni.mw_mode > 0.5) {
let gal = star_uni.galactic * (star_uni.celestial * ray_dir);
stars += postfx_milky_way(gal, star_uni.mw_width, star_uni.mw_brightness) * star_fade;
}
In galactic space z is the galactic pole and x points at the center, so latitude is b = asin(z) and longitude l = atan2(y, x). The band is built from four terms:
- wthe band's Gaussian half-width in radians (
milkyWayWidth) - fbmfour octaves of 3D value noise on the galactic direction g, so the mottling has no seam anywhere on the sphere
- termsa mottled Gaussian band; a broad bulge toward the galactic center; a narrower noisy dust rift subtracted down the middle. Clamped at 0, tinted cool (0.85, 0.86, 1.0) and warmer (1.0, 0.95, 0.82) toward the bulge
Three sets of defaults, and a gain
The band's settings are layered. The engine pass declares brightness 0.1 and width 0.3, and
the curved-horizon feature's own defaults are 0.6 and 0.18. Explorer then sets its own: on by default,
milkyWayBrightness: 0.1, milkyWayWidth: 0.38. And every place that
hands the brightness setting to the pass multiplies it by one more constant:
/** Scale on the Milky Way brightness setting: the band was too bright at every setting,
* so the slider's whole range is brought down (applied wherever the setting is used). */
const MILKY_WAY_GAIN = 0.45;
…
starsFeature.milkyWayBrightness = effects.milkyWayBrightness * MILKY_WAY_GAIN;
Scaling the slider's output rather than its default means saved settings and the 0–3 slider range keep working, and the whole range moves down together. At the defaults the band reaches the pass at 0.045, compared with about 4 for a magnitude-0 star: it is a faint glow behind the stars, as it should be, and it shares the stars' night gate, sky extinction and horizon clamp because it is added into the same accumulator.
The aurora
The aurora is off by default (aurora: false, brightness 1.2 when on). It is drawn
by the same pass, in world space rather than galactic space, as rippling curtains in an arc
above the horizon: a base at 0.35 rad (about 20°) above the horizon with a soft width of
0.12 rad that wobbles with azimuth, a vertical envelope that fades out five widths higher, a
slowly drifting coverage mask that opens and closes stretches of the arc, broad cubed-FBM
curtain sheets and fine vertical filaments that drift upward, colored from oxygen green
(0.1, 1.0, 0.45) at the base to red-magenta (0.7, 0.1, 0.6) at the top, and animated by
frame.time.
Curtain noise sampled with the raw azimuth, atan2(dir.x, dir.z), would have a
seam: azimuth jumps from +π to −π behind you, so the noise would too, and a diagonal seam would
run down the sky. The cure applies to any azimuth-driven sky effect: sample
the noise on a horizontal circle, (cos az · r, sin az · r, …), which is periodic
by construction. The radius r then sets how many folds span the sky (2.4 for the
sheets, 11 for the filaments). That needs 3D noise, which is why the aurora module carries its
own value-noise and FBM.
The aurora is not geomagnetically placed; it hangs around the whole horizon wherever you are when switched on. It is an atmosphere-of-the-night option, not a space-weather simulation.
Constellation figures
The wrist unit's Sky guide traces the constellations on the drawn stars
(constellation_lines.wgsl). The figures come from d3-celestial (Olaf Frohn,
BSD-3-Clause), fetched at run time as a third-party asset. Each segment joins two stars'
directions in the stars' own equatorial frame, and the same celestial matrix the star pass uses
turns them into the world, so the lines stay on the stars at every place and hour. Through a
perspective camera a great circle is a straight line, so a segment is only a screen-space quad
between its two clipped ends, leaving a 7 px gap round each star. The lines are drawn on sky
pixels only (a tree in front hides them, a cloud drawn later covers them), fade where the sky
behind is bright, and are divided by the exposure so they keep one brightness on the screen:
an overlay, not part of the sky's light.
Sun and Moon
src/geo/live/sun.ts · src/geo/live/vsop_earth.ts · src/geo/live/moon.ts · src/geo/live/astro_time.ts · src/shaders/atmosphere.wgsl · src/shaders/modules/atmosphere_model.wgsl (moonDiskShade) · explorer/main.ts (applyPaintedMoon, moonLightNow)
The Sun's place comes from VSOP87 (Bretagnon and Francou), in the truncation Meeus gives,
turned into the Sun's apparent place with FK5, nutation and aberration: about one arcsecond,
with its distance. equatorialToEcef subtracts the sidereal angle to put it in
Earth-fixed axes. The Moon uses Meeus' abridgement of ELP-2000/82, 60 terms in longitude and
distance and 60 in latitude, good to about 10″ in longitude and 4″ in latitude. That is enough
to put a total solar eclipse's path within some 20 km and its contacts within half a minute,
which the eclipses depend on. Both theories run on Terrestrial Time,
ΔT apart from UTC, and all of it runs from one UTC simulation clock (the multiplayer host owns
it and guests lock to it).
Two moons
The atmosphere pass can paint a moon itself: a disc in the sky dome with its own flare, shaded
as a lit sphere. Explorer also has a real Moon, the streamed body. When the streamed Moon is
enabled (the default) both exist, and applyPaintedMoon() decides which part of each
is shown:
function applyPaintedMoon(): void {
const pass = atmosphereFeature.pass!;
pass.setMoonHidden(false); // keep the painted-moon block; gate the disk below
pass.setMoonDiskHidden(moonEnabled); // streamed ball is the disk → hide the painted one
pass.setMoonPhase(null); // geometric phase: lit by the real sun
pass.setMoonFlare(MOON_FLARE_DEFAULT); // 0.6
pass.setEarthshine(moonEnabled ? 0 : EARTHSHINE_DEFAULT); // 0.02
}
With the streamed Moon on, the disc you see is the real body (drawn as a distant sphere, next
section), at its true angular size; the atmosphere pass contributes only the soft halo around
it, positioned by a moon provider that returns the camera-to-Moon direction
computed each frame from the same ECEF position the body uses. With it off, the painted disc
stands in. It is deliberately oversized (MOON_COS_THRESH = 0.9997, an angular
radius of about 1.4°, where the real Moon's is 0.26°) and shaded by reconstructing a sphere normal
under each pixel of the disc:
let cam_dir = -moonDir; // disc-center normal, toward the viewer
let perp = rd - moonDir * dot(rd, moonDir); // view offset from disc center
let px = dot(perp, right) / disk_sin;
let py = dot(perp, up) / disk_sin;
let nz = sqrt(max(1.0 - (px * px + py * py), 0.0));
let normal = cam_dir * nz + right * px + up * py;
let lit = smoothstep(-MOON_TERMINATOR_WIDTH, MOON_TERMINATOR_WIDTH, dot(normal, sunDir));
return lit + earthshine * (1.0 - lit); // earthshine fills the dark limb
Lighting that sphere with the real Sun direction gives the true phase for free: crescent,
gibbous and the orientation of the terminator all follow from geometry, with no phase number
anywhere. The disc's rim is antialiased analytically, feathered over about a pixel in cosine
space using fwidth of the view–moon cosine, which is computed at the top of the
fragment shader in uniform control flow so the derivative is valid. The shader comment explains
why it cannot be left to TAA: the history clamp rejects a tiny high-contrast disc.
The painted moon fades in only after sunset, except that Explorer sets the daylight flag
(setMoonDaylight(true)), because the real Moon is often up in daylight and should be
visible then. A daytime Moon also needs care in the distant-sphere pass, described below, so that
the shaded ball's dark side does not read darker than the blue sky around it.
Moonlight
At night the scene's key light becomes the Moon. Its direction is the Moon-to-camera vector of the same placed body, and its level is a product of altitude and phase:
- ethe sine of the Moon's elevation (full strength from about 8.6° up)
- fthe lit fraction of the disc from the Sun–Moon angle seen from Earth's center (
moonIlluminated)
The exponent 2.5 makes a half moon give about 18% of a full moon's light, so dark moonless nights really are dark. The lighting deep dive covers how that key light is used.
Painting a planet in a post-process
explorer/lib/space/distant_body_feature.ts (packBody, BoxOnScreen, unseen) · explorer/lib/space/distant_body.wgsl · explorer/main.ts (the per-frame distant-body feed, the near/far block)
Drawing every body's tiles all the time does not work. Standing on the Moon, you would see Earth's tiles hanging in the sky, and also through the ground: patches of Earth showing through lunar hills a few hundred meters away. Two precision failures stack:
- Vertex precision. Earth's tiles, seen from the Moon, sit tens of thousands of kilometers from the floating origin (the shader comment cites 78,000+ km). A 32-bit float there has a step of several meters, and projecting such a position subtracts large, nearly equal numbers, so its clip-space depth carries an error far larger than the gap between the Moon's surface and Earth in depth terms.
- Depth range. To include the other body the far plane would have to stretch across
the gap. Even with reversed-Z (Explorer creates its context with
reversedZ: true), that steals resolution from the nearby terrain.
Capping the far plane would hide the other body altogether. Instead, only the active body's tiles are drawn, and every other body is painted as an analytic ellipsoid by a full-screen pass that runs only on background pixels. It never takes part in a depth test, so it cannot win one.
if (!dz_is_background(depth)) { return vec4<f32>(scene, 1.0); } // real geometry always wins
for (var i: u32 = 0u; i < n; i = i + 1u) {
let b = bodies[i];
// The ray in the body's own axes; the camera there, in equatorial radii (packed in doubles).
let rd = normalize(vec3<f32>(dot(b.rot0.xyz, ray), dot(b.rot1.xyz, ray), dot(b.rot2.xyz, ray)));
let ro = b.cam.xyz;
if (1.0 / length(ro) < 0.25 * pix_ang) { continue; } // a point of light only
let sc = vec3<f32>(1.0, b.extra.z, b.cam.w); // its three radii over the largest
let os = ro / sc; let ds = rd / sc; // ellipsoid → unit sphere
let qa = dot(ds, ds); let tc = -dot(os, ds) / qa;
let pl = length(os + ds * tc); // closest approach
let cov = clamp(0.5 + (1.0 - pl) / (tc * sqrt(qa) * pix_ang), 0.0, 1.0); // limb AA
… // shade by kind; rings; casters; nearest of body and rings wins
}
… // points of light for bodies under a few pixels; comets
let behind = scene * (1.0 - cover);
var out = mix(body_col + behind, body_col + scene, wash); // replace on a dark sky, add on a bright one
out += (points + glow) * sky_dim; // points and comets fade into day
Precision is handled before the shader. On the CPU, in doubles, packBody turns
the camera's offset from each body into that body's own axes (+Z its north pole) and divides it
by the body's equatorial radius. In those units a planet 600 million km away and a moon a few
thousand km below the camera are both well-conditioned in f32, so nothing is pulled in toward
the camera and no body loses precision. Real terrain in front is an automatic occluder, and a
body sinking behind a ridge is clipped exactly at the ridge line, however far away it is.
The details that make it read
- BodiesUp to 64 per frame (
MAX_BODIES), 64 floats each in a storage buffer: the camera in the body's axes, the world-to-body rotation, the Sun's direction and light there, two colors, rings, up to four shadow casters, a surface-map layer. The nearest hit wins, so a moon can pass in front of its planet, and rings composite over and behind their globe. - ShapeAn ellipsoid of three radii: the oblate giants (Saturn's polar radius is 90% of its equatorial), triaxial asteroids. The limb is anti-aliased analytically: a ray just past it is shaded at the limb and weighted by how much of the pixel the disc covers.
- EarthColor (0.20, 0.36, 0.58), rim 1.3, rim tint (0.35, 0.55, 1.0), and a blue-marble equirect photo, sampled in Earth-fixed axes so the continents stay put as the origin moves. The photo (4096 × 2048, about 43 MB with mips) loads the first time Earth is drawn from afar, not at startup, and is block-compressed where the device can (about 6 MB).
- Moon, MarsGray (0.44, 0.44, 0.46) with no rim; rust (0.52, 0.25, 0.13) with rim 0.35. Their night sides keep a faint 0.025 of the base color; every other body's is 0.004, nearly black.
- PointsUnder a few pixels a body is a Gaussian point of light (σ 0.75 px) whose brightness comes from its apparent magnitude, on the stars' scale. A disc a few pixels across is lifted to as much total light as that point, as a telescope shows a planet, easing to its own shading by 16 px.
- DetailSurface noise octaves follow the disc's radius in pixels, log₂(2rpx) + 1, up to 9 on High and Ultra and 6 on the lighter presets.
- Culling
bodyOnScreenrebuilds the view's center and corner rays from the inverse view-projection (at NDC z = 0.5, finite for reversed and infinite-far depth alike) and keeps a body only if its angular radius, asin(r/d), reaches inside the view cone.unseenalso drops a body whose point is dark (by day) and whose disc is under half a pixel across: by day over San Francisco 122 of them had cost 1 ms of an M1's frame. - Screen boxThe shader runs only in a scissor box round the bodies on screen (each disc and its rings half as wide again, plus 8 px); a plain copy fills the rest. The whole screen is shaded only for a body about the camera, far off the view's middle, or a comet, whose tails can cross the sky. Shading every sky pixel for a planet a pixel wide had been a tenth of a Medium frame's GPU time.
Replacing the sky pixel with the shaded sphere outright would, in daylight, turn the Moon's
shadowed half, lit only by the 0.025 ambient, into a dark gray-and-black blob pasted on a
bright blue sky. The physics says otherwise: a body hundreds of thousands of kilometers away is
behind all of the atmosphere, so the airlight, which is exactly what scene holds on
a sky pixel, is in front of it. The pass therefore blends from a hard replace
over a dark sky (night, space: the body must still block stars) to additive over a bright one
(day: the dark limb disappears into the sky, the lit part is a pale wash), keyed on the
sky's luminance with smoothstep(0.015, 0.25, L). L is the darkest of the
pixel and four taps 3 px away, because a bright star is a point and the daytime airglow is
smooth: a star taken for a bright sky would show through a body's disc.
Near and far
With other bodies out of the depth range, the near and far planes only have to serve the active body. Explorer fits the far plane to the distance to that body's geometric horizon and lifts the near plane with altitude:
- Rthe active body's ground radius at the camera (WGS84, the lunar sphere, or the Mars spheroid at the camera's latitude)
- haltitude above it; at the ISS's ~400 km the near plane is 200 m, at 3,000 km it is 1.5 km
Close subjects override the near plane: the aircraft chase camera, the ISS in its true size, the cockpit (0.08 m) and the Cupola (0.3 m; a closer plane leaves too few bits to rebuild Earth's view rays from, and the painted globe comes out in blocks). Reversed-Z is what makes a near plane that close survivable against a far plane past the horizon. See the frame deep dive for the depth buffer itself.
The solar system
explorer/lib/space/solar_system.ts · solar_looks.ts · moon_maps.ts · surface_maps.ts · small_bodies.ts · small_body_system.ts · belt.wgsl · comets.ts · ring_particles.ts · mars_moons_view.ts · small_body_meshes.ts · solar_travel.ts · hyperspace.wgsl · src/geo/live/planets.ts · moons.ts · body_rotation.ts
Beyond the Earth, the Moon and Mars, Explorer draws Mercury, Venus, Jupiter, Saturn, Uranus, Neptune and Pluto, 20 major moons, 20 named asteroids, the comets, and 150,000 asteroids of the belt. None of it is tiled terrain. The planets and moons are the distant-body pass's ellipsoids at every distance, even in orbit a few hundred kilometers over the cloud tops, and only a few small bodies get a mesh close up. A trip to any of them arrives into an orbit at the real orbital speed for its height. The body is held still in the universe from the moment the trip starts, so it is still where the trip aimed when the trip arrives.
Where they are
- Planets. JPL's approximate Keplerian elements (
planets.ts), heliocentric, turned to the Earth's center and into the universe's frame each frame. - Moons. Jupiter's four from Meeus chapter 44 (Lieske's E2x3 series, refitted to JPL's ephemeris: within about 1,100 km over 1990–2060); Saturn's seven from chapter 46 (Harper and Taylor's theory: within about 1% of each orbit's radius); Mars', Uranus' and Charon from JPL's planetary satellite mean elements; Triton from its IAU rotation model, since it turns once per orbit.
- Rotation. Each body's pole and prime meridian from the IAU working group's models (the 2009 and 2015 reports). The giants turn by System III, and Jupiter's Great Red Spot is tracked in System II (about 50° W in 2025, drifting about 1.8° a month), so it is drawn where it is today.
- Small bodies. A bake of JPL's Small-Body Database: the brightest 150,000 asteroids (absolute magnitude up to 15.6), the named ones, 203 comets and the close approaches to the Earth. Each is propagated on its own two-body orbit, open orbits included (the interstellar 1I, 2I and 3I).
How they look
A body has a kind: rocky, Venus' cloud deck, gas giant, ice giant, or the Earth's photo. Rocky bodies also have a variant with a face of its own. All of it is procedural, built from value-noise FBM with octaves by the body's size on the screen, and tuned by eye to mission imagery:
- Rocky. Two colors mixed by large noise patches, fine mottling, and up to three scales of procedural craters: dark floors, bright rims, the inner wall facing the Sun lit and the far one shaded, and rays round young craters on Mercury. The variants give Io its sulfur and volcanic spots, Europa its lineae, Ganymede its grooved terrain, Callisto its bright crater spots, Enceladus its tiger stripes, Iapetus its coal-dark leading half, Titan its haze and polar hood, Triton its pink southern cap and Pluto its bright heart.
- Shading. Airless, dusty bodies use Lommel–Seeliger, 2μ₀ / (μ₀ + μ), a flat-lit disc with no limb darkening (as the full Moon looks), with the crater walls' slope on top. Titan's haze takes a softer Lambert, Venus a bright, nearly featureless deck with faint chevrons, and the giants a limb darkening of μ₀0.15·μ0.25.
- Giants. Their bands come from a 512 × 8 half-float looks texture. Rows 0–3 hold each giant's cloud color by latitude, with the zonal wind (m/s, from published wind profiles) in alpha. Each latitude's clouds are carried round at its jet's speed against a wind clock, and noise stretched about nine times along the bands gives them their shear. On top: Jupiter's Great Red Spot and the white ovals south of it, Saturn's north polar hexagon, Neptune's dark spot and bright high streaks.
- Jupiter's photo. Hubble's OPAL global map of 19 January 2015 (2048 × 1024), turned so its Red Spot sits where the spot is now, with the drawn bands at the poles the map has no data for and fine turbulence over it close up.
- Moon maps. Fifteen moons carry USGS maps from Voyager, Galileo and Cassini imagery, baked to equirect WebP whose alpha marks where there is data. They share a texture array of 6 layers (4 on phones), 1440 texels wide (1024 on phones), filled least recently used once a disc is 6 px in radius. The mip comes from each pixel's footprint on the body. Where a map has no data the procedural surface shows, matched to the brightness of the data round the gap (a coarse mip of the map), except on Iapetus, whose gaps are bright terrain beside the dark.
Rings
A ring system is a plane through the equator, intersected per pixel. Rows 4–7 of the looks texture hold the radial profiles of Saturn's, Uranus', Neptune's and Jupiter's rings, from the published radii and optical depths: the particles' color times their single-scattering albedo, and the normal optical depth τ averaged over each texel (the kilometer-wide rings of Uranus and Neptune carry their equivalent depth). The rings' opacity along the ray is 1 − e−τ/μ, and their light is single scattering in a thin slab:
- μ, μ₀the cosines of the view and the Sun to the ring plane's normal
- τthe normal optical depth at that radius
The shadows go both ways: the planet's ellipsoid shadows the rings, and the rings dim the
sunlight on the globe by e−τ/|sz|. Flying in Saturn's rings on High and
Ultra, the plane gives way to geometry within 1.5 km of it (ring_particles.ts):
cells 160 m across, each a block of ice chunks going round Saturn at the Keplerian speed for its
own radius, their count following the optical depth (the B ring packed, the Cassini Division
sparse, the Encke gap empty) and their sizes the measured power law n(a) ∝ a⁻³ from 0.2 to 4 m,
in a sheet 30 m thick.
Shadows between worlds
Each body carries up to four shadow casters: its moons for a planet, its planet for a moon.
For each one caster_tint finds how far the sunward ray from the surface point passes
from the caster's center, and darkens across a penumbra as wide as the Sun's disc seen from
there. That gives Jupiter its moons' shadow transits and puts the moons into its shadow. A
caster with air, the Earth seen on the Moon, leaves a dim copper light in its umbra instead of
black (see lunar eclipses).
As bright as they really are
A point's light is the body's apparent magnitude m, as 10−0.4m times the star pass's catalog gain, so Jupiter and Venus sit among the stars on the same scale. The planets use Mallama and Hilton (2018), the Astronomical Almanac's method: 5 log₁₀(rΔ) plus each planet's phase curve, Saturn's with its rings by how open they are to the camera (Pluto, not in that paper: V(1,0) = −1.01 and 0.03 mag a degree). Moons and asteroids use the H system's simple form, the moons' H from their size and albedo (D = 1329 km / √p · 10−H/5), and comets their total magnitude, M₁ + 5 log Δ + K₁ log r (NEOWISE's and Tsuchinshan–ATLAS' refitted to what was seen). The planets come out in twilight before the stars do, and fade into a bright sky behind them as e−6L. A disc's own light is the Sun's at the body over the Sun's at the camera (1/r², at most 50×) times its albedo: lit as the eye adapted to the Sun where the camera is would see it.
The asteroid belt on the GPU
The belt's 150,000 asteroids (40,000 on phones) are not bodies. They are instanced quads in the same pass, each propagated from its orbital elements in the vertex shader for the clock's instant:
let m = (e1.y + e1.z * u.t_days) % 6.2831853; // mean anomaly, kept within a turn
let ea = kepler_e(m, ecc); // six Newton steps
let xp = a * (cos(ea) - ecc);
let yp = a * sqrt(1.0 - ecc * ecc) * sin(ea);
… // rotate by ω, i, Ω into the J2000 ecliptic (AU)
let mag = e1.w + 5.0 * log2(r * d) * 0.30103; // H + 5 log10(r Δ)
out.flux = u.gain * exp2(-1.3287712 * mag); // 10^(−0.4 m)
var clip = u.view_proj * vec4<f32>(wdir, 0.0); // a direction: a point at infinity
clip.z = clip.w * 0.5;
The elements are 8 floats (32 bytes) an asteroid: a, e, i, Ω, ω, the mean anomaly at the epoch, the mean motion and H. f32 holds a position to about 15 km at 3 AU, plenty for a point seen from far off. Each one is projected as a direction (w = 0), so the near and far planes never come into it, and the fragment shader does the sky test against the depth buffer. True to life, nearly all of them are far too faint to see, so out in space the belt is lifted 13 magnitudes to show its shape: the Kirkwood gaps and Jupiter's Trojans.
Comets
A comet's nucleus is a body (to aim at and orbit), and the rest is glow, up to 16 comets at a time. The coma falls off as e−r/(coma/4), its whole light spread over its size on the screen. The ion tail runs straight away from the Sun. The dust tail bends back along the orbit on a quadratic curve, four straight pieces long, each a Gaussian about the ray's closest approach to it, widening and fading toward its end. The coma begins inside 5 AU of the Sun, the dust tail inside 4 and the ion tail inside 3, and the tails grow as 1/r² (up to 80 and 150 million km), scaled by how bright the comet gets. A tail can cross the whole sky, so a comet on screen turns the pass's scissor box off.
Close up
An ellipsoid is wrong for a lumpy body seen from a few kilometers, so three cases get real meshes near the camera. Phobos and Deimos use Ernst et al.'s 2023 shape models (Phobos with the USGS Viking mosaic) within 3,000 km. Named asteroids under 150 km and comet nuclei use a third-party rock mesh scaled to their three published axes and turned with them, within 300 of their radii; a nucleus is darkened to its few percent albedo. With nothing else to light a night side out past the belt, these get a fill light that grows from nothing at 2 AU from the Sun to a fifth of the sunlit face at 10 AU: a dark nucleus met from its dark side had been black on black.
The jump
A trip between planets crosses its distance on a log scale: the distance left falls by the same
share each moment. Meanwhile hyperspace.wgsl draws the stars out into streaks
pouring past from the point ahead, on sky pixels only. The sky is unrolled about the way ahead
into the angle round that axis and the stereographic distance from it, log tan(θ/2), in which a
streak running straight out keeps its length on the screen, and cut into thin sectors that each
hold one sliding streak.
Standing on the Moon and Mars
explorer/main.ts (MOON_* and MARS_* constants, the space-sun override, loadMoon / loadMars) · src/geo/geo_sky.ts (CurvedHorizonSky.update)
When the Moon or Mars becomes active, CurvedHorizonSky.update re-centers the
sky on it every frame. The atmosphere pass is analytic
in its per-body parameters (betaR, betaM, shell and sun intensity are uniforms, no LUT is
re-baked to switch planets), so a body swap is a uniform write. Earth's values are re-applied
whenever the active body carries none, so leaving Mars always restores a blue sky.
The Moon: an atmosphere 500 m thick
An airless body still runs the same sky pass. Its shell is collapsed to
AIRLESS_SHELL_M = 500, which makes the scattering integral vanish while the
painted ground globe, the sun disc and the stars still render. Aerial perspective is switched
off outright (maxOpacity: 0), and the stars are forced to full visibility on the
whole sphere (forceFull), day or night.
The regolith itself needs help. Its real albedo is about 0.12; under one hard sun against
black space that reads as dull gray. So the lunar tiles get a material tweak: albedo × 6
(MOON_ALBEDO_BOOST), roughness 0.6, full dielectric specular, and the key light ×
1.6 at the Moon. The shadowed ground has no sky to light it, so it would be pure black; the
albedo texture is reused as a dim emissive (0.22 on and near the surface) to keep crater detail
legible in shadow, "a cheap stand-in for the ambient an atmosphere would provide". The same
emissive ramps up to 6.0 only when the Moon is a distant disc (50 km to 80,000 km of altitude),
and the band is that wide because with a low far altitude the glow would pin to full across the
whole approach and wash the craters to flat white.
Taurus–Littrow from low over the valley: regolith with the albedo boost and emissive floor
Mars from orbit: streamed tiles, the rust painted globe beyond them, and the butterscotch limbFrom the Moon, the Earth passes over the Sun at every lunar eclipse; that view, and the copper light it leaves on the regolith, is in the eclipses section.
The lunar tiles are baked around the Moon's position when loaded and translated each frame
by the orbit offset. Once you commit to the Moon and the offset exceeds 50 km
(MOON_REBASE_MIN_DELTA), the tileset is re-baked in place so its vertices sit near
the origin again; otherwise the accumulated offset would show up as float jitter, "stutter", in
the terrain.
Mars: a spheroid and a thin sky
Mars needs the most care per line of code in this part of the renderer, and most of it is geometry. Cesium's Mars tiles are authored on a biaxial spheroid, equatorial radius 3,396,190 m and polar 3,376,200 m. A sphere would put the painted ground globe, the curved horizon and the clip planes up to about 2 km off the real tile surface, which clips the terrain out of view, so the ground radius is computed at the camera's latitude:
- A, Cequatorial and polar radius; d is the camera's offset from Mars' center, Z the polar axis
The other details: tilesets on both the Moon and Mars set maxRenderDistance = Infinity,
since the default cap (sized for dense city buildings) cuts the planetary terrain into a patch
with a straight edge. The sky's ground radius is clamped to just under the camera,
min(R, rcam − 2), because Jezero's crater floor lies kilometers below the
Mars datum and a camera "underground" to the scattering math gets a black horizon and an opaque
aerial fog. And aerial perspective is off on Mars (aerialStrength: 0): its
in-scatter is additive and grows with path length, so even scaled down it washes the surface to
white at grazing angles; Mars' air is about 1% of Earth's, and the sky dome alone carries the
look.
The rest is tint. Mars' sky uses a red-dominant Rayleigh coefficient (21, 12, 6) ×10⁻⁶ with a
dustier Mie term and an 80 km shell; the comment is honest that this is stylized, since the real
Martian sky is dust-driven and "not physically reproducible here". The key light is a pale warm
(1.0, 0.93, 0.84) at 0.78 of Earth's. The tiles get albedo × 2.5, roughness 0.85 and specular
0.5, with an emissive floor of 0.18 on the ground that falls to 0.02 between 30 and 100 km up,
because "seen from space it is the sun that shapes the planet". From Mars, the painted
Earth-sky moon and its glow are hidden (setMoonHidden(activeBody !== earthBody));
the Moon ball is still drawn by the distant-body pass.
Eclipses
explorer/lib/space/eclipse.ts · explorer/lib/space/eclipse_view.ts · src/renderer/eclipse_shadow.ts · src/shaders/modules/eclipse.wgsl · src/shaders/atmosphere.wgsl (ecl_*) · src/shaders/deferred_lighting.wgsl · src/shaders/aerial_volume.wgsl · src/shaders/clouds_hq.wgsl · explorer/lib/space/distant_body.wgsl (caster_tint) · explorer/main.ts (the eclipse exposure, earthEclipseFrom)
The Sun and Moon come from VSOP87 and ELP-2000/82 at the clock's instant, so solar eclipses happen by themselves, at the right place and minute. How the calculator compares with NASA's Canon is in the Science and engineering overview. The renderer's job is what an eclipse looks like: the Moon's shadow on the ground, the haze, the clouds and the sky; the Sun at its true size with the Moon's jagged limb across it; the corona; and the eye adapting to the dark.
One shadow, every pass
The host works out, in doubles, the Moon's center and radius, the shadow's axis (from the Sun
through the Moon) and the Sun–Moon distance. It hands every pass the same three vec4s
(EclipseShadow), and each pass evaluates the light left at its own points with one
function:
- c, âthe Moon's center and the shadow's axis; z how far behind the Moon the point is, d how far off the axis
- Dthe Sun–Moon distance; x and k are the Moon's offset and radius in solar radii as seen from the point
The covered share of the limb-darkened disc is summed over six rings, spaced evenly in μ rather
than in radius (r dr = μ dμ crowds them toward the limb). Spaced evenly in radius,
the last thin crescent before totality fell outside the outermost ring and the light went out
early. One evaluation is a few tens of ALU and six acos; a world-space f32 point
400,000 km from the Moon is good to about 30 m. For totality the Moon's radius is the Canon's
k = 0.272281 Earth radii, a little under the mean, because the valleys of its limb let
sunlight through to the last.
- LightingThe direct sun is multiplied by the light at the pixel over the light at the camera, which the key light already carries (floored at 10⁻³ so the ratio stays finite). The ground under you can be dark while hills outside the umbra are still sunlit, and the shadow's edge can be seen crossing a valley.
- SkyThe sky pass averages the light along each view ray, 8 samples weighted by air density and transmittance, so overhead is dark while the air tens of km off, outside the umbra, is still lit: the sunset all round the horizon at totality. Where the ray's air is lit from outside more than at the camera it is tinted warm, (1.0, 0.68, 0.40), the light having come a long way through low air.
- HazeThe froxel haze takes the same shadow per froxel. Sky and haze both keep a floor of 0.02 for the light scattered in from the sunlit air round the shadow; without it the haze over far land glowed brighter than the sky behind it, orange ridges against a black horizon.
- CloudsThe cloud pass takes the shadow at the middle of each ray's march through the deck, with a key light of 1, since its sunlight is not dimmed beforehand.
- Ambient, starsThe sky's ambient light keeps at least 3%, so totality reads as deep twilight with the land's shapes visible, not black. The stars come out as the light falls from 3% to 0.05%.
The Sun, the Moon's limb and the corona
Out of an eclipse the sky draws the Sun as a disc of about 1.6° radius, three times the real one, so that it reads as a sun. Once the Moon is within 4° of the Sun the eclipse terms turn on, and between 3° and 1.2° the disc eases to its true size so that the Moon covers it exactly. The Moon's disc gets a jagged limb, five sine terms by position angle adding up to about a tenth of a percent of its radius (a few arcseconds on its 930 or so). The sunlight through its valleys at second and third contact is Baily's beads, and the last of it the diamond ring. Both edges are anti-aliased over a pixel.
The corona and the prominences come up only as the last 0.4% of the light goes. The corona falls off as r⁻⁴ plus an exponential wing, with fine radial rays and streamers from noise round the circle. Where the Sun is in its 11-year cycle (counted from a minimum at 2019.9) sets its shape: long wings along the equator at minimum, streamers all round near maximum, turned by the position angle of the Sun's pole. A thin pink chromosphere and tongues of prominences sit at the limb. Since a total eclipse's Moon is up to 8% larger than the Sun, the tall prominences show all through totality and the chromosphere only at the contacts. The noise is seeded by the lunation, so each eclipse has its own corona.
On the ground
- Shadow bands. In the minute or two either side of totality, with between about 0.02% and 2.5% of the light left, two sets of faint wavy bands about 15 cm apart drift across light ground at a couple of meters a second, across the shadow's travel, at up to 6% contrast. They fade out between 12 and 40 m from the camera, where they would only alias.
- Pinhole crescents. Under a tree every gap in the leaves is a pinhole that throws an image of the Sun. In the partial phases, where the shadow map is partly lit, a fine pattern of 3.5 cm Sun images, one to a jittered 11 cm cell, takes the place of its soft average while keeping about as much light. Each image is the Sun's disc less the Moon's at its real offset, inverted as a pinhole inverts. The host says where the soft shadows are leaves; the shadow map cannot tell a tree from a wall.
The eye
An auto-exposure meter would take 99% coverage for night and open up. Instead the meter's
anchor and the day's exposure ceiling are lifted by 1/√light, at most ten times, as the eye
adapts while the light goes. The deep partial phase therefore reads as an eerie, dim day. In
totality the lift eases back to 5% of that (ECLIPSE_TOTALITY_LIFT): twilight about
the corona, with the horizon's glow, the land's shapes and the bright stars. Eclipse glasses hold
back 10 stops after the meter, with the film's amber (1.0, 0.72, 0.38): the daylit scene goes
black and only the Sun's disc stays bright.
Lunar eclipses, from both sides
From the Earth, the Moon in the distant-body pass gets the Earth as a shadow caster with air, its radius enlarged by 1/85 (Danjon's rule for the shadow's growth by the atmosphere). In the penumbra the light falls with the share of the Sun covered. In the umbra it does not go black: it falls to a dim copper, (0.13, 0.036, 0.010), up to 60% darker toward the umbra's middle. That copper is the reddened light of every sunrise and sunset on Earth bent into the shadow, about Danjon 2.5. It is brighter than the real few ten-thousandths, as the dark-adapted eye sees it.
From the Moon, a lunar eclipse is a solar eclipse by the Earth. earthEclipseFrom
works out the share of the Sun the Earth's disc leaves at the camera, with the same limb-darkened
sum. The key light is dimmed by it (to no less than 8% at the umbra's edge and 4% at its axis)
and tinted copper, (0.8, 0.32, 0.12), as the light falls under 5%. The sky draws the Earth in
the occluder's place, with the Sun true to size behind it and the corona about it in totality.
On the Earth's disc in the distant-body pass, with the Sun behind it, the limb lights up as a
thin red ring, its air lit by the light passing through and reddened along that long path.
Earth from orbit
explorer/lib/ground/earth_imagery.ts (EarthImagery, cloudCoverFromInfrared, CLOUD_MAP_CREDIT) · src/shaders/atmosphere.wgsl (group 2: surf_uv, surf_sample) · src/geo/live/tile_window.ts · explorer/main.ts
From orbit, most of what you see of Earth is not tiles. Terrain and photoreal tiles stream
around the camera, but the planet's far reaches, the limb and everything during the ISS ride
(tiles are hidden there) are the atmosphere pass's painted globe: where a sky ray hits
the ground sphere, the pass shades a lit surface, adds city lights on the night side, and
composites it as surface · T + inscatter, so the blue limb haze is the same
integral as the sky. The atmosphere deep dive covers
that integral and the limb. This section is about what the surface is made of.
NASA imagery on the painted globe
By default the painted globe shows procedural blue-green continents. Once the camera first
climbs above 100 km over Earth (or boards the ISS), EarthImagery loads two
whole-globe layers from NASA GIBS, keyless and CORS-open: Blue Marble Next Generation (cloud-free
surface reflectance) for day and VIIRS City Lights 2012 for night. Both are equirectangular in
EPSG:4326, assembled from tiles at GIBS level 3, 5,120 × 2,560 texels (about 7.8 km a texel) and
mipmapped. Phones take level 2 and the low-memory iOS path level 1; the comment puts a level-3
layer at about 67 MB against about 17 MB at level 2.
While riding the ISS, each layer also gets a detail crop at up to level 7 (about 490 m a texel) around the ground point under the lower middle of the screen. Its center snaps to a grid of half its half-span, so at 7 km/s the crop is re-assembled about every 30 seconds rather than every frame, and the old crop stays bound until the new one is ready.
The shader picks levels explicitly. It runs in non-uniform control flow (no derivatives), and
an atan2-derived longitude would mis-pick mips at the antimeridian anyway, so it
estimates each pixel's ground footprint and turns it into a LOD:
// Ground footprint of one pixel (m): slant range × pixel angle, stretched by obliquity.
let footprint = tg.x * surf.pixel_angle / max(dot(n, -rd), 0.05);
…
let base_lod = max(log2(footprint * base_h / (PI * radius)), 0.0);
var c = textureSampleLevel(base, surf_samp, uv, base_lod).rgb;
// the crop has no mips: fade it back to the base where it would be minified
let w = d.a * smoothstep(0.0, 0.03, edge) * (1.0 - smoothstep(0.5, 1.5, detail_lod));
c = mix(c, d.rgb, w);
Here π·R / base_h is the ground length of one texel (half a meridian over the
texture's height), so the LOD is log₂ of footprint over texel size. The latitude in
surf_uv is geodetic, using the ellipsoid's eccentricity, so the imagery lines up
with the tiles where they meet.
City lights
VIIRS composites sit on a navy backdrop with land faintly tinted in, and the lights are warm
yellow-white. The shader keys on red and green, caps blue at green (dropping the navy),
subtracts a floor of 0.02 (dropping the land tint), and turns the lights on past the terminator
with smoothstep(0.02, −0.12, n·ŝ), multiplied by the City lights setting
(default 1.5). The same night layer is sampled on the CPU side, as a Gaussian-weighted mean
luminance read back from a one-workgroup compute pass, for light that can't be drawn texel by
texel: the glow of a town on the underside of the clouds over it.
Today's clouds
Blue Marble is cloud-free, which looks wrong from orbit. Explorer overlays a whole-globe cloud
map, remade every three hours from geostationary weather satellites' infrared images by Live
Cloud Maps (the credit CLOUD_MAP_CREDIT reads "Clouds: EUMETSAT, via Live Cloud
Maps (M. Eason)" and is shown only once the map has actually been used). Infrared brightness
means cold, which is cloud tops but also polar ground and cold sea, so the conversion to
coverage is relative to each latitude's clear level:
- Clear level per row. A 256-bin histogram of every other pixel in the row; the 15th percentile is taken as the clear, warmest ground at that latitude.
- Smooth it. A box average over ±4% of the image height.
- Coverage. A pixel 16 levels above its row's clear level begins to be
cloud, and 90 above is solid:
t = clamp((v − (clear + 16)) / 74), smoothstepped. - Overlay. The result becomes the alpha of a white image, drawn with high-quality smoothing at 0.92 opacity over each assembled piece of day imagery, base and crops alike.
The volumetric cloud deck, by contrast, belongs to the ground: it is gated to Earth being
active and fades out between 3 and 40 km above its top, so the 3D clouds and the 2D map never
stack. Away from Earth the pass is handed setSurfaceImagery(null), explicitly, so it
cannot keep binding a detail crop that the streamer has since destroyed, which would be a
validation error on every submit after a spaceship leaves for the Moon.
Sixteen thousand satellites
src/geo/live/satellites.ts (SatelliteCatalog) · src/geo/live/frames.ts · src/geo/live/sgp4.ts · src/geo/satellite_feature.ts (GeoSatelliteFeature, SAT_INSTANCE_BYTES) · src/geo/satellite.wgsl · explorer/lib/space/satellite_models.ts · explorer/lib/space/satellite_range.ts · explorer/main.ts (updateSatellites, pickSatModels, the ISS)
The satellite layer is off by default. When it is on and you are in orbit, it shows every
object in a committed snapshot of CelesTrak general-perturbations element sets: 15,995 objects
(10,741 Starlink, 23 crewed stations and related objects, 5,231 others), generated 2026-07-11
from the active, starlink and stations groups. Each is
propagated with SGP4, the standard model those element sets are fitted for, using a vendored
propagator. TLEs plus SGP4 mean there is no polling: positions are computed analytically for any
instant.
From elements to the world
SGP4 returns position and velocity in TEME, an Earth-centered inertial frame, in kilometers.
temeToEcef rotates by the IAU-82 sidereal angle; GeoFrame maps ECEF
to the floating-origin world. All of it is double precision on the CPU until the final world
position is written as a float. Satellites are propagated at real UTC (new Date()),
not the simulation clock, because whether a satellite is in Earth's shadow is part of what you
are looking at, and the ISS ride needs the station where it really is. Its elements, months old
in the snapshot (stale elements can put the ISS thousands of kilometers off along-track), are refreshed from
CelesTrak's stations group when it is first wanted, cached for two hours because
CelesTrak refuses repeat downloads, with another source as a fallback.
Sunlit or eclipsed
The look of real satellite-spotting comes from shadow: at dusk only objects high enough to catch the sun are visible. Each object gets a sunlit flag from a cylindrical umbra test against a low-precision solar vector (Vallado's Sun algorithm, about 0.01°), both in the inertial frame:
export function isSunlit(posKm: EcVec3, sunUnit: EcVec3, earthRadiusKm = 6371.0): boolean {
const along = posKm.x * sunUnit.x + posKm.y * sunUnit.y + posKm.z * sunUnit.z;
if (along >= 0) { return true; } // day side of the terminator plane
const px = posKm.x - along * sunUnit.x, py = …, pz = …; // distance from the Earth–Sun axis
return px * px + py * py + pz * pz > earthRadiusKm * earthRadiusKm;
}
With "sunlit only" on (off by default), eclipsed objects are not packed at all, which gives the dusk satellite-spotting view. With it off, they are drawn dimmed to 0.7 of their color, chosen so the shell "reads as full coverage rather than a half-empty globe over the bright daylit surface".
Not spending sixteen thousand propagations
Re-propagating and re-packing the whole catalog a few times a second, with no culling, would cause a visible hitch each time. Instead the scheme has two tiers and one important omission:
- A rolling refresh. Every frame, 1/120 of the catalog
(
SAT_FULL_REFRESH_FRAMES) is propagated, so no object is more than about two seconds stale at 60 fps. Its only job is to have an object roughly right before it enters view. - The in-view set, every frame.
propagateInViewre-propagates only objects whose last position is inside the view, with a 200 km margin that exceeds the drift between refreshes. Cost scales with what is on screen. - The frustum in ECEF. Rather than transform 16,000 positions to world space to cull them, the six world-space frustum planes are transformed to ECEF once: a plane n·p + d ≥ 0 with p = R·pe + t becomes (Rᵀn)·pe + (n·t + d) ≥ 0.
- No far plane. The camera's far plane hugs the horizon, about 200 km out on the ground, but satellites orbit 400 to 35,000 km away and draw as sprites beyond it. Culling against the far plane would reject the entire shell, so it is replaced by a plane that always passes (row 4 or 5 depending on reversed-Z, which swaps the near and far rows).
- An Earth-limb test. Without a far plane the view cone is unbounded
and sweeps in the far side of the planet. Each candidate is tested for whether the segment
from the camera to it passes within 6,350 km of Earth's center (
SAT_OCCLUDER_R, just under the polar radius so limb-grazing objects survive).
The result is a steady 0.5 to 1.1 ms. And "the cheapest millisecond is the one not spent": the catalog is not even downloaded unless the camera is in Earth orbit, 100 km to 100,000 km up with 5% slack at both edges so flying along a boundary doesn't toggle it, or riding the ISS. On the ground and in flight the layer is off regardless of the setting.
Billboards
The packed instance is 16 bytes: a float32×3 world position and a unorm8×4 whose RGB is the glow color and whose alpha is a size scale. Explorer's groups are pale blue-white for generic objects (size 0.28), amber for Starlink (0.34) and green for crewed stations (1.0). The vertex shader expands each instance into a quad sized in pixels:
- s₀the base point size (Explorer's
satellitesSize, default 1.5 px) - athe instance's size byte, 0..1 (×0.25 to ×4)
- D_ref1,500 km reference distance; d is the camera distance
- s_min, s_max1 px and, in Explorer, 10 px: "uncapped (pointSize × 8) they swell into blobs overhead"
The quad is offset in clip space times w, so it survives the perspective divide at
that pixel size, and it uses the jittered view-projection so it moves with the TAA
jitter like everything else. There is no depth attachment: the fragment shader loads the scene
depth at its pixel, normalizes both depths to standard-Z (the pipeline override
REVERSED_Z), discards if behind, and otherwise adds a glow, a sharp core plus a
soft halo, blended one + one so order doesn't matter:
let r = sqrt(r2);
let core = pow(1.0 - r, camera.params.y); // sharpness, 3.5 by default
let halo = (1.0 - r2) * 0.35;
let glow = (core + halo) * camera.params.x; // brightness, 2.5
let lin = pow(in.color, vec3<f32>(2.2)); // approx sRGB → linear
return vec4<f32>(lin * glow, glow);
This little feature is one of the most reused in Explorer. The same
GeoSatelliteFeature, with its own size and brightness range, draws the ISS beacon
and navigation lights, runway edge and threshold lights, the aircraft's exterior lamps,
street lamps, rooftop obstruction lights and the lights of live air traffic: anything that is a
glowing point at a known world position.
Models when close, and the station
A point is right for something under a pixel. When an object would be at least 8 px across at
the model scale, it is drawn as a low-poly model built in code instead (and removed from the
points): a generic satellite (a foil bus 1.8 × 1.8 × 2.2 m, two 6 m solar wings, an
Earth-facing dish; 14.6 m across) or a Starlink (a flat chassis and one 8 × 2.8 m array; 11.3 m),
at most 48 per frame, the largest on screen first. Models are scaled by the same exaggeration
as the ISS (satellitesIssScale, default 40; true size while riding), with a floor
of twice the point's diameter so that some ever qualify. Their previous-frame matrices are kept
by catalog index for the velocity buffer: at about 7.5 km/s, a model without motion vectors
smears into a streak under TAA.
The ISS itself is a real glTF model of about 325,000 vertices, loaded and drawn only within
500 km (ISS_MODEL_RANGE_M, about 8 px across at the default scale), with its many
co-orbiting element sets (modules, docked vehicles) hidden from the points so they don't stack
into a green blob. Beyond that range a strobing beacon marks it: a separate billboard instance
with a minimum on-screen size of 6 px, so the station can be found from the ground or deep
space. Up close it carries its own lights: red to port and green to starboard at the truss
ends, white anti-collision strobes (a double flash every 2 s), and floodlights on the modules
that glow only on the night side.
Exposure in a black sky
explorer/main.ts (the auto-exposure anchor block, AE_* constants, the lens-flare limb fade, wantSpaceSun) · src/shaders/atmosphere.wgsl (sun disc)
A metering camera pointed at space has a problem: most of the frame is black, so it opens up, and the sunlit spaceship, Moon or station burns to white. Worse, Explorer's normal exposure anchor is computed from the sun's height over the local horizon, which means nothing in space and would pulse like a strobe as the floating frame turns with each re-anchor. So above the air the meter is blended toward a fixed anchor, "as a camera is set for a sunlit thing in space":
- spacea smoothstep from 0 at 30 km to 1 at 100 km above the active body when flying, riding the ISS or at Mars; always 1 on an airless body ("one sun lights everything there, no sky evens it out")
- anchor
0.07 · (sunOnGround + 0.3 · sunHere), where in space the sun on the ground is the full sun regardless of its elevation - anchor weight0.5 on the ground, rising to 1 (the anchor only) in space
- ISS rideone stop further down (
AE_ISS_STOP_DOWN_EV), no daylight lift, and a minimum exposure of 0.05 instead of 0.35: the subject is a white station over cloud tops
The sun itself, in a black sky, is still drawn by the atmosphere pass: a disc of HDR value
1,000 times transmittance inside SUN_COS_THRESH = 0.9996 (an angular radius of
about 1.6°, deliberately larger than the real 0.27°), plus a tunable flare halo. On an airless
body the 500 m shell makes the transmittance about 1, so the disc is at full strength. Above
100 km over Earth (80 km on the way down, to avoid thrash), or at the Moon or Mars, the scene's
key light is forced to the full real sun instead of the day/night light that would otherwise
switch to dim moonlight at Earth's night: the Moon is sunlit regardless of what time it is in
Greenwich.
One more interaction: the lens flare occludes against scene depth, but the painted planet has no depth, so from orbit the flare would shine straight through Earth when the sun is behind it. Explorer fades it with the closest approach of the camera-to-sun ray to the active body's center, from 0 at the ground radius to 1 at 30 km above it, so the flare dies as the sun sets behind the limb. The post-processing deep dive covers the exposure meter, the flare and the tone curve these feed.
References
- D. Hoffleit, W. H. Warren Jr., The Bright Star Catalog, 5th revised edition, Yale University Observatory, 1991. The 9,096 stars, their magnitudes and temperatures.
- T. Helland, “How to Convert Temperature (K) to RGB: Algorithm and Sample Code”, 2012. The blackbody fit used for star colors.
- D. A. Vallado, P. Crawford, R. Hujsak, T. S. Kelso, “Revisiting Spacetrack Report #3”, AIAA/AAS Astrodynamics Specialist Conference, 2006. The SGP4 model, TEME,
gstimeandjday. - D. A. Vallado, Fundamentals of Astrodynamics and Applications, 4th ed., Microcosm Press, 2013. The low-precision Sun vector and the sidereal-time series.
- P. Bretagnon, G. Francou, “Planetary theories in rectangular and spherical variables: VSOP87 solutions”, Astronomy and Astrophysics 202, 1988. The Earth's place, hence the Sun's, in
vsop_earth.ts. - J. Meeus, Astronomical Algorithms, 2nd ed., Willmann-Bell, 1998. The VSOP87 truncation, the ELP-2000/82 abridgement (chapter 47), Jupiter's moons (chapter 44, Lieske's E2x3) and Saturn's (chapter 46, Harper and Taylor), phase and illuminated fraction.
- A. Mallama, J. L. Hilton, “Computing apparent planetary magnitudes for The Astronomical Almanac”, Astronomy and Computing 25, 2018. The planets' brightness as points of light, Saturn's with its rings.
- B. A. Archinal et al., “Report of the IAU Working Group on Cartographic Coordinates and Rotational Elements: 2015”, Celestial Mechanics and Dynamical Astronomy 130, 2018. Each body's pole and prime meridian.
- JPL Solar System Dynamics: approximate planetary Keplerian elements, Planetary Satellite Mean Elements, the Small-Body Database. The planets, Mars', Uranus' and Pluto's moons, the belt, the named asteroids and the comets.
- F. Espenak, J. Meeus, Five Millennium Canon of Solar Eclipses: −1999 to +3000, NASA/TP-2006-214141, 2006. The Moon's umbral radius k = 0.272281 and the ΔT the eclipses run on.
- A. A. Simon, M. H. Wong, G. S. Orton, “First results from the Hubble OPAL program: Jupiter in 2015”, The Astrophysical Journal 812, 2015. Jupiter's global map.
- NASA 3D Resources: moon maps (USGS, JPL and Caltech, from Voyager, Galileo and Cassini imagery); C. M. Ernst et al., shape models of Phobos and Deimos, 2023. The moons' surfaces.
- O. Frohn, d3-celestial (BSD-3-Clause). The constellation figures.
- E. Bruneton, F. Neyret, “Precomputed Atmospheric Scattering”, Computer Graphics Forum (EGSR), 2008; S. Hillaire, “A Scalable and Production Ready Sky and Atmosphere Rendering Technique”, Computer Graphics Forum (EGSR), 2020. The scattering model behind the limb and the per-body skies (see the atmosphere deep dive).
- NASA Global Imagery Browse Services (GIBS): Blue Marble Next Generation; VIIRS City Lights 2012. The day and night imagery on the painted Earth.
- CelesTrak, General Perturbations element sets (celestrak.org). The satellite snapshot and the ISS refresh.
- Live Cloud Maps (clouds.matteason.co.uk), EUMETSAT data. The three-hourly infrared cloud map over the Blue Marble.
- NASA LRO (LOLA, LROC), MOLA, ESA/DLR HRSC, Viking MDIM 2.1, HiRISE, USGS Astrogeology; Cesium ion: Cesium Moon Terrain, Mars. The streamed lunar and Martian terrain: Explorer's own tilesets, and the fallback.