Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

Moonlight and Tokyo's night sky: the moon as a second directional light where it stands on the date, a light dome on the night sky's glow, and black directional lights skipped by the kernel (ROADMAP § 0 step 1a, part 3)

Evan (Yifeng) Wangb4172955d888
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 539c857..1953f42 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -399,6 +399,49 @@ Earlier direction (2026-11-05, kept for the history below): finish the three.js
emitter CDF and refits the light tree over all 1.4 M emitters. A group therefore switches on every tile in one
frame; making that update incremental is the next item.
- Next for step 1a: the commit's cost, moonlight and the night sky.
+ - Status, part 3 (2026-11-10, branch `moonlight`): moonlight and the night sky.
+ - The moon (`games/tokyo/moon.ts`): a second directional light in the time-of-day rooms, where the moon stands
+ over Tokyo at that moment.
+ - Position by Schlyter's method: mean elements and the main perturbations, within a few arcminutes.
+ - Its light by phase: Allen's magnitude against the sun's, through the same air as the sun's (Rayleigh, Mie at
+ 10×, ozone; Kasten and Young's air mass).
+ - Checked at November 2026's phases (`tools/tokyo/test/moon.test.ts`, USNO times): new on the 9th, first
+ quarter on the 17th, full on the 24th, 0.25 lx above the air.
+ - The rooms take a date (`-d20261124`); 2026-11-09 is a new moon.
+ - It is black while it is down, until civil dusk, and under starlight's 1 mlx.
+ - The full moon high over Shinjuku at 23:00 changes the city by ΔE 0.05 at EV 5 (0.2 lx against its lit
+ streets), as in photographs: the moonlight is lost in the city's light.
+ - The kernel skips a black directional light (no BSDF, no shadow ray), after the cone's random numbers, so
+ every other light sees the same ones.
+ - The moon while down, and the sun at night, cost nothing. Shiba from 16:18 to 17:36 live, GPU p50 with a
+ black moon: 14.30 / 14.33 ms without the skip, 13.58 / 13.61 with it (serverless-agent-test#130: 13.7).
+ - The 12 catalog scenes render byte-identical.
+ - The night sky: `SkyAtmosphere` `horizonGlow`, a light dome over the glow (nits at the horizon, falling to
+ 1/e at `horizonGlowHeight`). `tests/render/sky-night-glow.ts`: 1.349 measured, 1.349 analytic.
+ - Tokyo's (`NIGHT_GLOW` in `games/tokyo`):
+ - 27 mcd/m² at the zenith (16.5 mag/arcsec², Tokyo's clear-night zenith measured from Sumida, 2010–11);
+ - a dome of 0.26 cd/m² more at the horizon, falling to 1/e by 3.5°;
+ - a violet-blue zenith and a warm dome.
+ - Set against photographs of the Shinjuku skyline at night (Wikimedia Commons, 2004 and 2005; not
+ committed):
+ - the sky at 1°, 7° and 15° reads 7.3 : 1.95 : 1, and the dome is shaped on that;
+ - the colours are the 2004 photograph's, white-balanced on its office windows;
+ - at the 2005 photograph's exposure (EV 3) our sky reads 4× brighter than its top of frame, whose blacks
+ are crushed, and darker than the 2004 one (a longer exposure).
+ - The static night rooms now have the same sky as the time-of-day rooms: the atmosphere with the sun 40°
+ down, and the glow. Before, a uniform blue sky lit the city from below the horizon too.
+ - The land beyond the area now fades into the dome by night (the aerial perspective's haze carries its light),
+ not a black band under the sky. At EV 5 the sky stays near black, as in photographs at that exposure.
+ Before and after, at EV 5 and as a long exposure: `docs/img/tokyo-night-sky.jpg`.
+ - The commit's cost (ThreeRT#3, first serverless-agent-test#135): a power edit rebuilt the emitter CDF and refit
+ the light tree in the frame, ~13–15 ms over Tokyo's 1.4 M emitters, ~90 times in the Shiba fly-past (the
+ street lamps and the window groups switching).
+ - Scenes with many emitters now rebuild both on a worker thread (`EmitterWorker`). The edits land with the
+ result, a few frames later.
+ - The fly-past's frame interval p95 went from 29.7 / 28.5 to 17.20 / 17.17 ms, and its commits over 5 ms from
+ 91 to 0.
+ - Next for step 1a: the acceptance runs (the fly-past and a Shinjuku drive, 5 poses × 4 times, in place against a
+ fresh load, a clip).
1b. **Weather on Tokyo.** States, and transitions between them, all in place (no rebuild):
- rain: wet streets and puddles reflecting the city, and the rain curtain (Bistro's), measured on Tokyo;
- fog and mist: height fog over the city, thickening and clearing;
diff --git a/docs/img/tokyo-night-sky.jpg b/docs/img/tokyo-night-sky.jpg
new file mode 100644
index 0000000..e99ce9b
Binary files /dev/null and b/docs/img/tokyo-night-sky.jpg differ
diff --git a/games/tokyo/moon.ts b/games/tokyo/moon.ts
new file mode 100644
index 0000000..f40bee1
--- /dev/null
+++ b/games/tokyo/moon.ts
@@ -0,0 +1,76 @@
+// The moon over Tokyo: where it stands, how much of it is lit, and the light it sends, at a moment (UTC ms). Schlyter's
+// method (mean orbital elements plus the main perturbations, within a few arcminutes): position from the moon's and the
+// sun's mean elements, then horizontal coordinates for the observer. Light: the moon's magnitude by phase angle (Allen:
+// -12.73 + 0.026|a| + 4e-9 a^4, at its mean distance) against the sun's -26.74, so its illuminance as a fraction of the
+// sun's, both above the atmosphere; then the air between, with the sky's own constants (renderer/src/sky.rs Earth).
+const RAD = Math.PI / 180;
+const rev = (x: number) => ((x % 360) + 360) % 360;
+const sin = (deg: number) => Math.sin(deg * RAD), cos = (deg: number) => Math.cos(deg * RAD);
+
+export type Moon = {
+ /** Degrees above the horizon (topocentric: parallax taken off). */
+ elevation: number;
+ /** Degrees, as `DirectionalLight.setSunAngles` takes them: from the south (+z) towards the east (+x). */
+ azimuth: number;
+ /** The fraction of its disc that is lit, 0 (new) to 1 (full). */
+ lit: number;
+ /** Its illuminance as a fraction of the sun's, both above the atmosphere (full moon at perigee: ~2.5e-6). */
+ toSun: number;
+};
+
+/** The moon at `utcMs` seen from (lat, lon) degrees; by default Tokyo Tower. */
+export function moonAt(utcMs: number, lat = 35.6586, lon = 139.7454): Moon {
+ const d = utcMs / 86400000 + 2440587.5 - 2451543.5; // days from 2000 Jan 0.0 UT
+ const ut = (((utcMs / 3600000) % 24) + 24) % 24;
+ // the sun: its true longitude (for the phase) and mean longitude (for sidereal time and the perturbations)
+ const ws = 282.9404 + 4.70935e-5 * d, es = 0.016709 - 1.151e-9 * d, Ms = rev(356.047 + 0.9856002585 * d);
+ const Es = Ms + (es / RAD) * sin(Ms) * (1 + es * cos(Ms));
+ const sunLon = rev(Math.atan2(Math.sqrt(1 - es * es) * sin(Es), cos(Es) - es) / RAD + ws);
+ const Ls = rev(Ms + ws);
+ // the moon's orbit: ascending node, inclination, argument of perigee, mean distance (Earth radii), eccentricity, mean anomaly
+ const N = rev(125.1228 - 0.0529538083 * d), i = 5.1454, w = rev(318.0634 + 0.1643573223 * d), a = 60.2666, e = 0.0549;
+ const M = rev(115.3654 + 13.0649929509 * d);
+ let E = M + (e / RAD) * sin(M) * (1 + e * cos(M));
+ for (let k = 0; k < 5; k++) E -= (E - (e / RAD) * sin(E) - M) / (1 - e * cos(E));
+ const xv = a * (cos(E) - e), yv = a * Math.sqrt(1 - e * e) * sin(E);
+ const vw = Math.atan2(yv, xv) / RAD + w;
+ let r = Math.hypot(xv, yv);
+ const xh = r * (cos(N) * cos(vw) - sin(N) * sin(vw) * cos(i));
+ const yh = r * (sin(N) * cos(vw) + cos(N) * sin(vw) * cos(i));
+ const zh = r * sin(vw) * sin(i);
+ let mLon = Math.atan2(yh, xh) / RAD, mLat = Math.atan2(zh, Math.hypot(xh, yh)) / RAD;
+ // the main perturbations (degrees; Earth radii)
+ const Lm = rev(M + w + N), D = rev(Lm - Ls), F = rev(Lm - N);
+ mLon += -1.274 * sin(M - 2 * D) + 0.658 * sin(2 * D) - 0.186 * sin(Ms) - 0.059 * sin(2 * M - 2 * D) - 0.057 * sin(M - 2 * D + Ms) + 0.053 * sin(M + 2 * D) + 0.046 * sin(2 * D - Ms) + 0.041 * sin(M - Ms) - 0.035 * sin(D) - 0.031 * sin(M + Ms) - 0.015 * sin(2 * F - 2 * D) + 0.011 * sin(M - 4 * D);
+ mLat += -0.173 * sin(F - 2 * D) - 0.055 * sin(M - F - 2 * D) - 0.046 * sin(M + F - 2 * D) + 0.033 * sin(F + 2 * D) + 0.017 * sin(2 * M + F);
+ r += -0.58 * cos(M - 2 * D) - 0.46 * cos(2 * D);
+ // ecliptic -> equatorial -> horizontal
+ const ecl = 23.4393 - 3.563e-7 * d;
+ const xe = cos(mLon) * cos(mLat), ye = sin(mLon) * cos(mLat) * cos(ecl) - sin(mLat) * sin(ecl), ze = sin(mLon) * cos(mLat) * sin(ecl) + sin(mLat) * cos(ecl);
+ const ra = Math.atan2(ye, xe) / RAD, dec = Math.atan2(ze, Math.hypot(xe, ye)) / RAD;
+ const ha = rev(Ls + 180 + ut * 15 + lon - ra);
+ const x = cos(ha) * cos(dec), y = sin(ha) * cos(dec), z = sin(dec);
+ const xHor = x * sin(lat) - z * cos(lat), zHor = x * cos(lat) + z * sin(lat);
+ let elevation = Math.asin(zHor) / RAD;
+ elevation -= (Math.asin(1 / r) / RAD) * cos(elevation);
+ // azimuth from the north, clockwise (east 90), then from the south towards the east
+ const fromNorth = rev(Math.atan2(y, xHor) / RAD + 180);
+ // phase angle (sun - moon - earth), the lit fraction and the magnitude
+ const phase = 180 - Math.acos(cos(sunLon - mLon) * cos(mLat)) / RAD;
+ const mag = -12.73 + 0.026 * Math.abs(phase) + 4e-9 * phase ** 4;
+ return { elevation, azimuth: rev(180 - fromNorth), lit: (1 + cos(phase)) / 2, toSun: 10 ** (-0.4 * (mag + 26.74)) * (a / r) ** 2 };
+}
+
+/**
+ * Direct sunlight's (or moonlight's) transmittance through the air at `elevation` degrees, RGB: Rayleigh, Mie at
+ * `mieScale` and ozone with renderer/src/sky.rs's Earth (scale heights 8 km and 1.2 km; ozone a 30 km tent about 25 km),
+ * over Kasten and Young's air mass. Zero below the horizon.
+ */
+export function airTransmittance(elevation: number, mieScale = 1): [number, number, number] {
+ if (elevation <= 0) return [0, 0, 0];
+ const mass = 1 / (sin(elevation) + 0.50572 * (elevation + 6.07995) ** -1.6364);
+ const rayleigh = [5.802e-3, 13.558e-3, 33.1e-3].map((s) => s * 8); // per km x 8 km
+ const mie = (3.996e-3 * mieScale + 0.444e-3) * 1.2;
+ const ozone = [0.65e-3, 1.881e-3, 0.085e-3].map((s) => s * 15);
+ return [0, 1, 2].map((k) => Math.exp(-mass * (rayleigh[k] + mie + ozone[k]))) as [number, number, number];
+}
diff --git a/games/tokyo/tokyo-tod.game.ts b/games/tokyo/tokyo-tod.game.ts
index 5ffdd3f..1197ac9 100644
--- a/games/tokyo/tokyo-tod.game.ts
+++ b/games/tokyo/tokyo-tod.game.ts
@@ -3,9 +3,13 @@
// lamps (street lights, Tokyo Tower's bulbs and beacons) switching on, tile by tile, as the sun goes down. The sky is
// `dynamic`: the live view moves the sun's light and re-bakes the sky in place, with no scene rebuild.
//
-// Room id: "<area>[-<from>-<to>-<seconds>][-r<radius>]", e.g. "shiba-15.5-17.75-7-r1600": the clock runs from 15:30 to
-// 17:45 (JST) over the first 7 s of scene time, and only the tiles within 1600 m of the area's origin are loaded (Shiba's
-// origin is Tokyo Tower). Defaults: shiba, 15.5 -> 17.75 over 7 s, every tile.
+// Room id: "<area>[-<from>-<to>-<seconds>][-r<radius>][-d<yyyymmdd>]", e.g. "shiba-15.5-17.75-7-r1600": the clock runs
+// from 15:30 to 17:45 (JST) over the first 7 s of scene time, and only the tiles within 1600 m of the area's origin are
+// loaded (Shiba's origin is Tokyo Tower). Defaults: shiba, 15.5 -> 17.75 over 7 s, every tile, 2026-11-09 (a new moon:
+// "d20261124" gives a full one, "d20261117" the first quarter).
+//
+// The moon is a second directional light, where it stands at that moment, as bright as its phase and the air between
+// make it (./moon.ts): ~0.2 lx full and high; nothing while it is down, before civil dusk, or under 1 mlx (near new).
//
// Data: 3D city model, Project PLATEAU (MLIT Japan); elevation and aerial photos, GSI; roads and places,
// © OpenStreetMap contributors (ODbL). Compiled tiles are a derived database under the ODbL: not to be published.
@@ -14,6 +18,7 @@ import { defineGame, type FrameContext } from "@threert/gameplay";
import { WINDOW_NODES, windowSwitchAt, type AreaIndex } from "./area.ts";
import shiba from "./areas/shiba.ts";
import shinjuku from "./areas/shinjuku.ts";
+import { airTransmittance, moonAt } from "./moon.ts";
import { tokyoSky } from "./tokyo.game.ts";
const AREAS: Record<string, AreaIndex> = { shiba, shinjuku };
@@ -62,24 +67,49 @@ export function switchAt(x: number, z: number): number {
return 1 - 4 * (h - Math.floor(h));
}
-type Room = { area: AreaIndex; from: number; to: number; seconds: number; radius: number };
+type Room = { area: AreaIndex; from: number; to: number; seconds: number; radius: number; date: [number, number, number] };
export function parseRoom(room: string): Room {
const parts = room.split("-");
const area = AREAS[parts[0]] ?? shiba;
const r = parts.find((p) => /^r\d+$/.test(p));
- const nums = parts.slice(1).filter((p) => !/^r\d+$/.test(p)).map(Number);
+ const d = parts.find((p) => /^d\d{8}$/.test(p));
+ const nums = parts.slice(1).filter((p) => !/^[rd]\d+$/.test(p)).map(Number);
const [from = 15.5, to = 17.75, seconds = 7] = nums.length === 3 && nums.every(Number.isFinite) ? nums : [];
- return { area, from, to, seconds, radius: r ? Number(r.slice(1)) : Infinity };
+ const date: [number, number, number] = d ? [Number(d.slice(1, 5)), Number(d.slice(5, 7)), Number(d.slice(7, 9))] : [2026, 11, 9];
+ return { area, from, to, seconds, radius: r ? Number(r.slice(1)) : Infinity, date };
+}
+
+/** The room's date at `hour` JST: UTC milliseconds, and the day of the year (1 = January 1st) for `sunAt`. */
+function moment(date: [number, number, number], hour: number): { utc: number; day: number } {
+ const midnight = Date.UTC(date[0], date[1] - 1, date[2]);
+ return { utc: midnight + (hour - 9) * 3600000, day: Math.round((midnight - Date.UTC(date[0], 0, 1)) / 86400000) + 1 };
}
+/** The sun's illuminance above the atmosphere (lux), the moon's measured against it. */
+const SUN_LUX = 100000;
+/** Moonlight's colour (linear): sunlight off the moon's regolith, redder than the sun (B-V 0.92 against 0.65). */
+const MOON_RGB: [number, number, number] = [1, 0.86, 0.66];
+
let room: Room = parseRoom("shiba");
/** What the clock switches (lamps, window groups): the object, the sun elevation it comes on at, and whether it is on. */
let lamps: { name: string; at: number; on?: boolean }[] = [];
-function place(sun: DirectionalLight, camera: PerspectiveCamera, t: number, lampOf: (name: string) => { power: number } | undefined) {
- const s = sunAt(hourAt(t, room.from, room.to, room.seconds));
+function place(sun: DirectionalLight, moon: DirectionalLight | undefined, camera: PerspectiveCamera, t: number, lampOf: (name: string) => { power: number } | undefined) {
+ const hour = hourAt(t, room.from, room.to, room.seconds), at = moment(room.date, hour);
+ const s = sunAt(hour, undefined, undefined, at.day);
sun.setSunAngles(s.elevation, s.azimuth);
camera.setManualExposure(evAt(s.elevation));
+ if (moon) {
+ // The moon's light through the air (Tokyo's haze, tokyoSky). Black (the kernel then skips it) while it is down,
+ // until the sun is 6 degrees down (civil dusk: the sky gives lux of its own), and below starlight's 1 mlx (a moon
+ // a few days from new).
+ const m = moonAt(at.utc), tr = airTransmittance(m.elevation, 10);
+ const rgb = MOON_RGB.map((c, k) => c * tr[k]), y = 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2];
+ const lux = SUN_LUX * m.toSun * y;
+ moon.setSunAngles(Math.max(m.elevation, 0), m.azimuth);
+ if (y > 0) moon.color.setRGB(rgb[0] / y, rgb[1] / y, rgb[2] / y);
+ moon.intensity = s.elevation < -6 && lux >= 1e-3 ? lux : 0;
+ }
// only what switches this frame is looked up and touched: a few hundred objects a frame cost the frame script 15-20 ms
for (const l of lamps) {
const on = s.elevation < l.at;
@@ -100,8 +130,11 @@ export function sceneFor(id: string) {
const sun = new DirectionalLight(0xfff4e8, 100000);
sun.name = "sun";
scene.add(sun);
- // The night sky's glow over a lit city once the sun has set (the atmosphere alone goes black).
- scene.environment = tokyoSky(sun, { dynamic: true, glow: 0x6b7fb3, glowIntensity: 0.03 });
+ const moon = new DirectionalLight(0xffffff, 0);
+ moon.name = "moon";
+ scene.add(moon);
+ // The night sky's glow over a lit city once the sun has set (the atmosphere alone goes black): NIGHT_GLOW.
+ scene.environment = tokyoSky(sun, { dynamic: true });
// The land beyond the area (not compiled): a plain plane below the lowest terrain, out to 100 km.
const land = new Mesh(new PlaneGeometry(200000, 200000), new MeshStandardMaterial({ color: 0x3b3a36, roughness: 0.95 }));
land.rotation.x = -Math.PI / 2;
@@ -137,7 +170,7 @@ export function sceneFor(id: string) {
camera.position.set(900, 260, -900);
camera.lookAt(0, 180, 0);
scene.add(camera);
- place(sun, camera, 0, (n) => scene.getObjectByName(n));
+ place(sun, moon, camera, 0, (n) => scene.getObjectByName(n));
return { scene, camera, options: { name: `tokyo-${area.area}-tod`, width: 1280, height: 720 } };
}
@@ -149,6 +182,6 @@ export default defineGame<Record<string, never>>({
return sceneFor(ctx.roomId || "shiba");
},
frame(f: FrameContext<Record<string, never>>) {
- place(f.object("sun") as DirectionalLight, f.camera, f.time, (n) => f.object(n));
+ place(f.object("sun") as DirectionalLight, f.object("moon") as DirectionalLight | undefined, f.camera, f.time, (n) => f.object(n));
},
});
diff --git a/games/tokyo/tokyo.game.ts b/games/tokyo/tokyo.game.ts
index 071eceb..517d073 100644
--- a/games/tokyo/tokyo.game.ts
+++ b/games/tokyo/tokyo.game.ts
@@ -8,7 +8,7 @@
//
// Data: 3D city model, Project PLATEAU (MLIT Japan); elevation and aerial photos, GSI; roads and places,
// © OpenStreetMap contributors (ODbL). Compiled tiles are a derived database under the ODbL: not to be published.
-import { Color, DirectionalLight, GLTFModel, Mesh, MeshStandardMaterial, PerspectiveCamera, PlaneGeometry, Scene, SkyAtmosphere, SkyColor } from "@threert/scene";
+import { Color, DirectionalLight, GLTFModel, Mesh, MeshStandardMaterial, PerspectiveCamera, PlaneGeometry, Scene, SkyAtmosphere } from "@threert/scene";
import { defineGame } from "@threert/gameplay";
import { WINDOW_NODES, type AreaIndex } from "./area.ts";
import shinjuku from "./areas/shinjuku.ts";
@@ -42,24 +42,43 @@ export const SUN = { elevation: 36.8, azimuth: 349.5 };
* a visual range near 70 km (Koschmieder, 3.9 / extinction at 550 nm), and its aerial perspective, so the land beyond
* the area and the far city fade into the sky at the horizon.
*/
-export function tokyoSky(sun: DirectionalLight, o: { dynamic?: boolean; glow?: number; glowIntensity?: number } = {}): SkyAtmosphere {
- const sky = new SkyAtmosphere({ sun, aerialPerspective: 1, ...o });
+export function tokyoSky(sun: DirectionalLight, o: ConstructorParameters<typeof SkyAtmosphere>[0] = {}): SkyAtmosphere {
+ const sky = new SkyAtmosphere({ sun, aerialPerspective: 1, ...NIGHT_GLOW, ...o });
sky.mieScale = 10;
return sky;
}
+/**
+ * Tokyo's night sky: the city's light scattered back down by the air (light pollution), which the atmosphere alone does
+ * not give once the sun has set. Added above the horizon by day too, where it is lost in the daylight.
+ * - At the zenith 27 mcd/m², 16.5 mag/arcsec²: Tokyo's clear-night zenith, measured from Sumida in the winter of
+ * 2010-11 (a camera; JpGU 2012 G01-P01). Berlin's centre reads 6-11 mcd/m² (Jechow et al. 2017, 2022).
+ * - The light dome: brighter toward the horizon, 0.26 cd/m² more at it, falling to 1/e by 3.5 degrees up. Shaped on
+ * photographs of the Shinjuku skyline at night (Wikimedia Commons: Shinjuku20040421.jpg, public domain; Shinjuku night
+ * skyline.jpg, 2005): the sky at 1, 7 and 15 degrees reads 7.3 : 1.95 : 1, just above the lit horizon about 7x the top
+ * of the frame.
+ * - Colours from the 2004 photograph, white-balanced on its office windows: a violet-blue zenith (the city's light
+ * scattered by the air, Rayleigh's blue), a warm dome at the horizon (the lights themselves, through the haze).
+ */
+export const NIGHT_GLOW = {
+ glow: new Color().setRGB(1.05, 0.95, 1.39),
+ glowIntensity: 0.027,
+ horizonGlow: new Color().setRGB(1.28, 0.93, 0.86),
+ horizonGlowIntensity: 0.26,
+ horizonGlowHeight: 3.5 * (Math.PI / 180),
+};
+/** The sun at night in the static rooms: well below the horizon (the sky is the glow alone). */
+const NIGHT_SUN = { elevation: -40, azimuth: 0 };
+
export function sceneFor(room: string) {
const [areaId = "shinjuku", time = "night"] = room.split("-");
const area = AREAS[areaId] ?? AREAS.shinjuku;
const scene = new Scene();
- if (time === "day") {
- const sun = new DirectionalLight(0xfff4e8, 100000).setSunAngles(SUN.elevation, SUN.azimuth);
- scene.add(sun);
- scene.environment = tokyoSky(sun);
- } else {
- // Urban night sky glow, as Bistro's.
- scene.environment = new SkyColor(new Color().setRGB(0.35, 0.45, 0.8), 0.04);
- }
+ // the sun by day; by night, set (the night sky is NIGHT_GLOW)
+ const s = time === "day" ? SUN : NIGHT_SUN;
+ const sun = new DirectionalLight(0xfff4e8, 100000).setSunAngles(s.elevation, s.azimuth);
+ scene.add(sun);
+ scene.environment = tokyoSky(sun);
// The land beyond the area (not compiled): a plain plane below the lowest terrain, out to 100 km.
const land = new Mesh(new PlaneGeometry(200000, 200000), new MeshStandardMaterial({ color: 0x3b3a36, roughness: 0.95 }));
land.rotation.x = -Math.PI / 2;
diff --git a/packages/scene/src/core.ts b/packages/scene/src/core.ts
index 3ad24e4..4f4e997 100644
--- a/packages/scene/src/core.ts
+++ b/packages/scene/src/core.ts
@@ -2013,19 +2013,29 @@ export class SkyAtmosphere {
/** Night-sky glow (light pollution) added above the horizon: colour × `glowIntensity` nits. Off at 0. */
glow: Color = new Color(0x6b7fb3);
glowIntensity = 0;
+ /**
+ * The glow's light dome over a city: colour × `horizonGlowIntensity` nits at the horizon, on top of the glow, falling
+ * off with elevation (to 1/e at `horizonGlowHeight` radians). Off at 0.
+ */
+ horizonGlow: Color = new Color(0xffb46b);
+ horizonGlowIntensity = 0;
+ horizonGlowHeight = 0.06;
/**
* Aerial perspective: the atmosphere's haze over the surfaces behind it, at this multiple of the atmosphere's own
* density (Rayleigh and Mie, `rayleighScale` / `mieScale`). Distant land fades into the sky at the horizon behind
* it, by day and by night (the glow). Off at 0 (the default): surfaces are seen through clear air.
*/
aerialPerspective = 0;
- constructor(opts: { sun?: DirectionalLight | null; groundAlbedo?: ColorLike; skyLightIntensity?: number; dynamic?: boolean; glow?: ColorLike; glowIntensity?: number; aerialPerspective?: number } = {}) {
+ constructor(opts: { sun?: DirectionalLight | null; groundAlbedo?: ColorLike; skyLightIntensity?: number; dynamic?: boolean; glow?: ColorLike; glowIntensity?: number; horizonGlow?: ColorLike; horizonGlowIntensity?: number; horizonGlowHeight?: number; aerialPerspective?: number } = {}) {
this.sun = opts.sun ?? null;
if (opts.groundAlbedo !== undefined) this.groundAlbedo = new Color(opts.groundAlbedo);
if (opts.skyLightIntensity !== undefined) this.skyLightIntensity = opts.skyLightIntensity;
if (opts.dynamic !== undefined) this.dynamic = opts.dynamic;
if (opts.glow !== undefined) this.glow = new Color(opts.glow);
if (opts.glowIntensity !== undefined) this.glowIntensity = opts.glowIntensity;
+ if (opts.horizonGlow !== undefined) this.horizonGlow = new Color(opts.horizonGlow);
+ if (opts.horizonGlowIntensity !== undefined) this.horizonGlowIntensity = opts.horizonGlowIntensity;
+ if (opts.horizonGlowHeight !== undefined) this.horizonGlowHeight = opts.horizonGlowHeight;
if (opts.aerialPerspective !== undefined) this.aerialPerspective = opts.aerialPerspective;
}
}
diff --git a/packages/scene/src/engine.ts b/packages/scene/src/engine.ts
index 5c5d676..227d3c6 100644
--- a/packages/scene/src/engine.ts
+++ b/packages/scene/src/engine.ts
@@ -62,7 +62,7 @@ export interface CameraDesc {
}
export type SkyDesc =
- | { type: "atmosphere"; /** the sun light's object */ sun: number | null; groundAlbedo: Vec3; rayleighScale: number; mieScale: number; mieAnisotropy: number; skyLightIntensity: number; /** the sun moves (time of day) */ dynamic?: boolean; /** night-sky glow, nits */ glow?: Vec3; /** aerial perspective: density multiple (0 = off) */ aerial?: number }
+ | { type: "atmosphere"; /** the sun light's object */ sun: number | null; groundAlbedo: Vec3; rayleighScale: number; mieScale: number; mieAnisotropy: number; skyLightIntensity: number; /** the sun moves (time of day) */ dynamic?: boolean; /** night-sky glow, nits */ glow?: Vec3; /** its light dome: nits at the horizon (RGB), the elevation (radians) it falls to 1/e by */ horizonGlow?: [number, number, number, number]; /** aerial perspective: density multiple (0 = off) */ aerial?: number }
| { type: "color"; color: Vec3; /** nits */ intensity: number; skyLightIntensity: number }
| { type: "hdri"; texture: number; intensity: number; rotation: number; skyLightIntensity: number }
| {
@@ -1394,6 +1394,7 @@ export class SceneBinding {
const a: SkyDesc = { type: "atmosphere", sun: sun ?? null, groundAlbedo: vec3(env.groundAlbedo), rayleighScale: env.rayleighScale, mieScale: env.mieScale, mieAnisotropy: env.mieAnisotropy, skyLightIntensity: env.skyLightIntensity };
if (env.dynamic) a.dynamic = true;
if (env.glowIntensity > 0) a.glow = vec3(env.glow).map((c) => c * env.glowIntensity) as Vec3;
+ if (env.horizonGlowIntensity > 0) a.horizonGlow = [...vec3(env.horizonGlow).map((c) => c * env.horizonGlowIntensity), env.horizonGlowHeight] as [number, number, number, number];
if (env.aerialPerspective > 0) a.aerial = env.aerialPerspective;
return a;
}
diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgsl
index a5d2456..7413aa4 100644
--- a/renderer/shaders/pathtrace.wgsl
+++ b/renderer/shaders/pathtrace.wgsl
@@ -1788,6 +1788,9 @@ fn direct_light(s: Surface, lb: Lobes, v: vec3<f32>) -> vec3<f32> {
let phi = 2.0 * PI * rnd();
let tb = basis(to_light);
let l = tb * vec3<f32>(sin_t * cos(phi), sin_t * sin(phi), cos_t);
+ // A light gone black (a moon that has set, the sun at night) costs neither its BSDF nor its shadow ray. (After
+ // the cone's random numbers: every other light sees the same ones as before.)
+ if (all(li.color.rgb <= vec3<f32>(0.0))) { continue; }
let f = eval_bsdf_k(s, lb, v, l, li.x.y);
if (any(f > vec3<f32>(0.0))) {
let vis = light_vis(li.ext.w >= 0.5, o, l, INF);
@@ -1899,6 +1902,7 @@ fn fog_scatter(o: vec3<f32>, d: vec3<f32>, t0: f32, t1: f32, tr: f32) -> vec3<f3
for (var i = 0u; i < P.counts2.x; i++) {
let li = lights[i];
let l = -li.dir.xyz;
+ if (all(li.color.rgb <= vec3<f32>(0.0))) { continue; } // black: no shadow ray (direct_light)
if (li.ext.w < 0.5 || !occluded(x, l, INF)) { ls += li.color.rgb * hg_phase(P.vol.y, dot(l, d)) * li.x.x; }
}
// One shadow ray: either the local lights (RIS) or one emissive point, chosen with equal odds when both exist.
@@ -2140,6 +2144,7 @@ fn phase_direct(x: vec3<f32>, d: vec3<f32>, g: f32) -> vec3<f32> {
let sin_t = sqrt(max(0.0, 1.0 - cos_t * cos_t));
let phi = 2.0 * PI * rnd();
let l = basis(-li.dir.xyz) * vec3<f32>(sin_t * cos(phi), sin_t * sin(phi), cos_t);
+ if (all(li.color.rgb <= vec3<f32>(0.0))) { continue; } // black: no shadow ray (direct_light)
let ph = hg_phase(g, dot(l, d));
let vis = light_vis(li.ext.w >= 0.5, x, l, INF);
if (any(vis > vec3<f32>(0.0))) {
@@ -2236,6 +2241,7 @@ fn point_direct(x: vec3<f32>) -> vec3<f32> {
let sin_t = sqrt(max(0.0, 1.0 - cos_t * cos_t));
let phi = 2.0 * PI * rnd();
let l = basis(-li.dir.xyz) * vec3<f32>(sin_t * cos(phi), sin_t * sin(phi), cos_t);
+ if (all(li.color.rgb <= vec3<f32>(0.0))) { continue; } // black: no shadow ray (direct_light)
if (li.ext.w < 0.5 || !occluded(x, l, INF)) { sum += li.color.rgb * ph; }
}
let nd = P.counts2.x;
diff --git a/renderer/src/desc.rs b/renderer/src/desc.rs
index cd3ccfa..37b4392 100644
--- a/renderer/src/desc.rs
+++ b/renderer/src/desc.rs
@@ -166,6 +166,9 @@ pub enum Sky {
dynamic: bool,
#[serde(default)]
glow: Option<Vec3>,
+ /// The glow's light dome: radiance (nits, RGB) at the horizon and the elevation (radians) it falls to 1/e by.
+ #[serde(default)]
+ horizon_glow: Option<[f32; 4]>,
/// Aerial perspective: the atmosphere's haze on the surfaces it lies in front of, at this multiple of its own
/// density (0 = off; pathtrace.wgsl `aerial_tr`).
#[serde(default)]
diff --git a/renderer/src/lib.rs b/renderer/src/lib.rs
index c7df2b5..141cc49 100644
--- a/renderer/src/lib.rs
+++ b/renderer/src/lib.rs
@@ -480,13 +480,13 @@ pub fn prepare(g: &gpu::Gpu, sc: &mut scene::Scene, timings: &mut Vec<(String, f
static LAST: std::sync::Mutex<Option<(Vec<u32>, std::sync::Arc<sky::SkyBake>)>> = std::sync::Mutex::new(None);
let alt = sc.camera.position.y.max(0.0);
let (bw, bh) = if *dynamic { sky::DYNAMIC_SKY } else { (1024, 512) };
- let key: Vec<u32> = [*rayleigh, *mie, *mie_g, ground.x, ground.y, ground.z, sun_dir.x, sun_dir.y, sun_dir.z, sun_lux.x, sun_lux.y, sun_lux.z, alt, glow.x, glow.y, glow.z, bw as f32].iter().map(|f| f.to_bits()).collect();
+ let key: Vec<u32> = [*rayleigh, *mie, *mie_g, ground.x, ground.y, ground.z, sun_dir.x, sun_dir.y, sun_dir.z, sun_lux.x, sun_lux.y, sun_lux.z, alt, glow.uniform.x, glow.uniform.y, glow.uniform.z, glow.horizon.x, glow.horizon.y, glow.horizon.z, glow.height, bw as f32].iter().map(|f| f.to_bits()).collect();
let mut last = LAST.lock().unwrap();
let bake = match last.as_ref() {
Some((k, b)) if *k == key => b.clone(),
_ => {
let atm = sky::Atmosphere::earth(*rayleigh, *mie, *mie_g, *ground);
- let b = std::sync::Arc::new(if *dynamic || *glow != Vec3::ZERO {
+ let b = std::sync::Arc::new(if *dynamic || !glow.is_zero() {
sky::bake_atmosphere_tables(&atm, &sky::SkyTables::new(&atm), *sun_dir, *sun_lux, alt, bw, bh, *glow)
} else {
sky::bake_atmosphere(&atm, *sun_dir, *sun_lux, alt, bw, bh)
diff --git a/renderer/src/live.rs b/renderer/src/live.rs
index 6fc5590..5f28982 100644
--- a/renderer/src/live.rs
+++ b/renderer/src/live.rs
@@ -442,11 +442,11 @@ struct DynamicSky {
impl DynamicSky {
fn new(world: &World, (w, h): (u32, u32), altitude: f32, env_nee_floor: f32) -> Option<DynamicSky> {
- let crate::desc::Sky::Atmosphere { rayleigh_scale, mie_scale, mie_anisotropy, ground_albedo, glow, sun: Some(_), .. } = &world.environment.sky else {
+ let crate::desc::Sky::Atmosphere { rayleigh_scale, mie_scale, mie_anisotropy, ground_albedo, glow, horizon_glow, sun: Some(_), .. } = &world.environment.sky else {
return None;
};
let atm = Arc::new(crate::sky::Atmosphere::earth(*rayleigh_scale, *mie_scale, *mie_anisotropy, glam::Vec3::from(*ground_albedo)));
- let glow = glow.map(glam::Vec3::from).unwrap_or(glam::Vec3::ZERO);
+ let glow = crate::sky::glow_of(glow, horizon_glow);
let (ask, asked) = mpsc::channel::<(glam::Vec3, glam::Vec3)>();
let (tx, done) = mpsc::channel();
let a = atm.clone();
diff --git a/renderer/src/scene.rs b/renderer/src/scene.rs
index c9f68a5..7d80ad3 100644
--- a/renderer/src/scene.rs
+++ b/renderer/src/scene.rs
@@ -396,7 +396,7 @@ pub enum SkyData {
None,
Color(Vec3),
/// `dynamic`: baked at `sky::DYNAMIC_SKY` (the live view re-bakes it as the sun moves); `glow`: night-sky radiance.
- Atmosphere { sun_dir: Vec3, sun_lux: Vec3, rayleigh: f32, mie: f32, g: f32, ground: Vec3, sun_node: Option<usize>, dynamic: bool, glow: Vec3 },
+ Atmosphere { sun_dir: Vec3, sun_lux: Vec3, rayleigh: f32, mie: f32, g: f32, ground: Vec3, sun_node: Option<usize>, dynamic: bool, glow: crate::sky::Glow },
Gradient(crate::sky::Gradient),
}
@@ -1666,7 +1666,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let env = &w.environment;
let sky = match &env.sky {
- Sky::Atmosphere { sun, ground_albedo, rayleigh_scale, mie_scale, mie_anisotropy, dynamic, glow, .. } => {
+ Sky::Atmosphere { sun, ground_albedo, rayleigh_scale, mie_scale, mie_anisotropy, dynamic, glow, horizon_glow, .. } => {
let sun_light = sun.and_then(|s| w.objects.get(&s).map(|o| (s, o)));
let (sun_dir, sun_lux) = match sun_light.map(|(s, o)| (worlds.get(&s).copied().unwrap_or(Mat4::IDENTITY), &o.kind)) {
Some((m, Kind::Light(Light::Directional { color, intensity, .. }))) => (-m.transform_vector3(Vec3::NEG_Z).normalize(), Vec3::from(*color) * *intensity),
@@ -1683,7 +1683,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
ground: Vec3::from(*ground_albedo),
sun_node: idx,
dynamic: *dynamic,
- glow: glow.map(Vec3::from).unwrap_or(Vec3::ZERO),
+ glow: crate::sky::glow_of(glow, horizon_glow),
}
}
Sky::Color { color, intensity, .. } if *intensity > 0.0 => SkyData::Color(Vec3::from(*color) * *intensity),
diff --git a/renderer/src/sky.rs b/renderer/src/sky.rs
index 4ea2950..c219608 100644
--- a/renderer/src/sky.rs
+++ b/renderer/src/sky.rs
@@ -269,7 +269,7 @@ const SKY_LIGHT_CUBE: f32 = 128.0;
/// sky fades to black across one texel row of the side faces at the horizon (0.9 deg at a face's centre, 0.63 at its
/// edges). UE's path tracer shows that fade below every horizon (Khronos layer B: the band beyond a 2 km ground plane).
pub fn bake_atmosphere(a: &Atmosphere, sun_dir: Vec3, sun_lux: Vec3, altitude_m: f32, width: u32, height: u32) -> SkyBake {
- bake_atmosphere_with(a, &Luts::build(a), sun_dir, sun_lux, altitude_m, width, height, Vec3::ZERO)
+ bake_atmosphere_with(a, &Luts::build(a), sun_dir, sun_lux, altitude_m, width, height, Glow::default())
}
/// The atmosphere's transmittance and multiple-scattering tables: they depend on the atmosphere alone, so a sky whose
@@ -282,9 +282,36 @@ impl SkyTables {
}
}
-/// `bake_atmosphere` with tables built once (`SkyTables`), plus `glow`: radiance (nits) added to every texel above the
-/// horizon, the night sky's light pollution, which the atmosphere alone does not give once the sun has set.
-pub fn bake_atmosphere_tables(a: &Atmosphere, t: &SkyTables, sun_dir: Vec3, sun_lux: Vec3, altitude_m: f32, width: u32, height: u32, glow: Vec3) -> SkyBake {
+/// The night sky's glow (light pollution), which the atmosphere alone does not give once the sun has set: radiance
+/// (nits) added above the horizon, `uniform` everywhere and `horizon` at the horizon, falling off with elevation (1/e at
+/// `height` radians): a city's light dome.
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+pub struct Glow {
+ pub uniform: Vec3,
+ pub horizon: Vec3,
+ pub height: f32,
+}
+
+/// The glow of an atmosphere sky's description (`desc::Sky::Atmosphere` `glow`, `horizon_glow`).
+pub fn glow_of(uniform: &Option<[f32; 3]>, horizon: &Option<[f32; 4]>) -> Glow {
+ Glow { uniform: uniform.map(Vec3::from).unwrap_or(Vec3::ZERO), horizon: horizon.map_or(Vec3::ZERO, |h| Vec3::new(h[0], h[1], h[2])), height: horizon.map_or(0.0, |h| h[3]) }
+}
+
+impl Glow {
+ /// The glow at `elevation` radians (the horizon's below it).
+ pub fn at(&self, elevation: f32) -> Vec3 {
+ if self.horizon == Vec3::ZERO {
+ return self.uniform;
+ }
+ self.uniform + self.horizon * (-elevation.max(0.0) / self.height.max(1e-3)).exp()
+ }
+ pub fn is_zero(&self) -> bool {
+ self.uniform == Vec3::ZERO && self.horizon == Vec3::ZERO
+ }
+}
+
+/// `bake_atmosphere` with tables built once (`SkyTables`), plus the night sky's `glow` above the horizon.
+pub fn bake_atmosphere_tables(a: &Atmosphere, t: &SkyTables, sun_dir: Vec3, sun_lux: Vec3, altitude_m: f32, width: u32, height: u32, glow: Glow) -> SkyBake {
bake_atmosphere_with(a, &t.0, sun_dir, sun_lux, altitude_m, width, height, glow)
}
@@ -295,7 +322,7 @@ pub fn sun_illuminance(a: &Atmosphere, sun_dir: Vec3, sun_lux: Vec3) -> Vec3 {
}
#[allow(clippy::too_many_arguments)]
-fn bake_atmosphere_with(a: &Atmosphere, luts: &Luts, sun_dir: Vec3, sun_lux: Vec3, altitude_m: f32, width: u32, height: u32, glow: Vec3) -> SkyBake {
+fn bake_atmosphere_with(a: &Atmosphere, luts: &Luts, sun_dir: Vec3, sun_lux: Vec3, altitude_m: f32, width: u32, height: u32, glow: Glow) -> SkyBake {
// Planet frame: Z up. Map Y-up world -> planet frame (x, z, y).
let to_planet = |d: Vec3| Vec3::new(d.x, d.z, d.y);
let sun_p = to_planet(sun_dir).normalize();
@@ -316,7 +343,7 @@ fn bake_atmosphere_with(a: &Atmosphere, luts: &Luts, sun_dir: Vec3, sun_lux: Vec
}
let (dir, k) = if r < 0.5 { (Vec3::new(d.x, side / SKY_LIGHT_CUBE, d.z).normalize(), r + 0.5) } else { (d, 1.0) };
let (l, _) = luts.integrate(a, pos, to_planet(dir), sun_p, 40, false, Some(()), false);
- let l = (l * sun_lux + glow) * k;
+ let l = (l * sun_lux + glow.at(dir.y.clamp(-1.0, 1.0).asin())) * k;
[l.x, l.y, l.z, 1.0]
})
.collect();
diff --git a/tests/render/sky-night-glow.ts b/tests/render/sky-night-glow.ts
new file mode 100644
index 0000000..e4d869d
--- /dev/null
+++ b/tests/render/sky-night-glow.ts
@@ -0,0 +1,20 @@
+// The night sky's glow on the atmosphere (SkyAtmosphere glow + horizonGlow): the sun 40 degrees down (the air alone
+// is black), 1 nit of glow everywhere above the horizon and a light dome of 2 nits more at the horizon, falling to 1/e
+// by 0.1 rad. A narrow lens 10 degrees up reads 1 + 2 exp(-0.1745 / 0.1) = 1.349.
+import { DirectionalLight, Scene, SkyAtmosphere } from "@threert/scene";
+import { CENTER, camera, result, type TestMeta } from "./lib.ts";
+
+export const test: TestMeta = {
+ id: "sky/night-glow", features: ["sky-atmosphere"], reference: "analytic", temporal: false,
+ metric: { kind: "radiance", region: CENTER, expected: 1.349, tolerance: 0.02 },
+ note: "glow 1 + horizon glow 2 exp(-elevation / 0.1 rad) at 10 degrees up, the sun far below the horizon",
+};
+
+export default function () {
+ const scene = new Scene();
+ const sun = new DirectionalLight(0xffffff, 100000).setSunAngles(-40, 0);
+ scene.add(sun);
+ scene.environment = new SkyAtmosphere({ sun, glow: 0xffffff, glowIntensity: 1, horizonGlow: 0xffffff, horizonGlowIntensity: 2, horizonGlowHeight: 0.1 });
+ const up = 10 * (Math.PI / 180);
+ return result(scene, camera(scene, [0, 1.7, 0], [0, 1.7 + 100 * Math.sin(up), -100 * Math.cos(up)], 2));
+}
diff --git a/tools/tokyo/test/moon.test.ts b/tools/tokyo/test/moon.test.ts
new file mode 100644
index 0000000..675cbc0
--- /dev/null
+++ b/tools/tokyo/test/moon.test.ts
@@ -0,0 +1,34 @@
+// The moon over Tokyo (games/tokyo/moon.ts) at November 2026's phases (USNO times, UTC): new on the 9th at 07:02, first
+// quarter on the 17th at 11:47, full on the 24th at 14:53.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { airTransmittance, moonAt } from "../../../games/tokyo/moon.ts";
+
+test("the moon's phase at November 2026's new moon, first quarter and full moon", () => {
+ const at = (iso: string) => moonAt(Date.parse(iso));
+ assert.ok(at("2026-11-09T07:02:00Z").lit < 0.005, "new");
+ assert.ok(Math.abs(at("2026-11-17T11:47:00Z").lit - 0.5) < 0.02, "first quarter");
+ const full = at("2026-11-24T14:53:00Z");
+ assert.ok(full.lit > 0.995, "full");
+ // a full moon near perigee: about 0.25 lux above the atmosphere against the sun's 100 klx
+ assert.ok(full.toSun > 2e-6 && full.toSun < 3e-6, `full moon ${full.toSun}`);
+ assert.ok(at("2026-11-17T11:47:00Z").toSun < full.toSun / 8, "a half moon is far dimmer than half the full (opposition surge)");
+});
+
+test("the moon's place: the full moon high in the south near midnight, the new one down at night", () => {
+ const full = moonAt(Date.parse("2026-11-24T23:53:00+09:00"));
+ assert.ok(full.elevation > 65 && full.elevation < 85, `elevation ${full.elevation}`);
+ // azimuth from the south towards the east: within 45 degrees of the south
+ assert.ok(Math.min(full.azimuth, 360 - full.azimuth) < 45, `azimuth ${full.azimuth}`);
+ assert.ok(moonAt(Date.parse("2026-11-09T21:00:00+09:00")).elevation < -30, "set with the sun");
+ // the first quarter sets around midnight: up in the evening, in the south-west (azimuth west of south: past 270)
+ const quarter = moonAt(Date.parse("2026-11-17T20:00:00+09:00"));
+ assert.ok(quarter.elevation > 15 && quarter.azimuth > 270, `${quarter.elevation} ${quarter.azimuth}`);
+});
+
+test("the air between: clear-ish overhead, reddened and dim at the horizon, nothing below it", () => {
+ const top = airTransmittance(90, 10), low = airTransmittance(5, 10);
+ assert.ok(top[0] > 0.85 && top[2] > 0.65 && top[2] < top[0]);
+ assert.ok(low[0] < 0.5 && low[2] < low[0] / 3);
+ assert.deepEqual(airTransmittance(-1), [0, 0, 0]);
+});