Physical Night Sky, Phase-Accurate Moon, Starfield & God Rays in Three.js
Physically grounded WebGL 2 night sky dome in Three.js r183 featuring Lommel-Seeliger lunar shading, analytic 1D-integrated phase-shaped moon halo, Kasten-Young air-mass extinction, boundary-free 2x2x2-cell twinkling stars, great-circle meteors, and phase-aware radial light shafts.
- sky
- moon
- stars
- night
- god-rays
- light-shafts
- meteor
- scattering
- lommel-seeliger
- air-mass
- shader
No demo.
When to Use & Field Best Practices
Naive night skies suffer from four telltale artifacts: a Lambertian moon that reads like a chalk ball instead of uniformly bright regolith, a circular halo that glows past the *dark* side of a crescent moon, stars that pop at grid boundaries when turning the camera, and low orange moons that crush scene lighting.
Five night-sky patterns for Three.js r183:
- Lommel-Seeliger reflectance + opposition surge: Lunar regolith back-scatters sunlight (
2 * mu0 / (mu0 + n.z)), keeping a full moon evenly bright to its limb while dimming away from full by0.4 + 0.6 * exp(-1.2 * phaseAngle). Add cool earthshine on the dark side and a copper-red umbra gradient for lunar eclipses. - Analytic 1D-integrated phase-shaped moon halo (
glowRow/moonGlowK): Integrateexp(-kx * |x - p|)analytically across 16 horizontal rows of the lit lunar segment over the full disc so a crescent glows along its bright limb and barely at all past its dark side—with zero extra render passes. - Kasten & Young air-mass reddening & decoupled scene dimming: Dim the moon disc steeply (
through^0.75) near the horizon while dimming scene light gently (through^0.30) so a low red moonrise keeps gameplay readable. - Seamless
2x2x2-cell procedural starfield: Check the pixel's spherical cell and its nearest neighbors within2.5 * wso stars never pop at cell faces during camera rotation, with horizon-deepened 3-sine scintillation. - Great-circle shooting stars & phase-aware radial god rays: Parameterize meteors along a great circle
(uMetA, uMetB)with hot blue-white heads and warm fading trails; pair withGOD_RAYS_FRAGfor radial moonlight shafts over a cloud transmittance buffer.
Mathematical & Algorithmic Core
- Lommel-Seeliger + Opposition Surge (
L = (sinφ, 0, -cosφ), α = |π - φ|): $I(n, φ) = min\!(frac2max(n·L, 0)max(n·L + n_z, 10^-4),\, 1.6)smoothstep(0, w, n·L)(0.4 + 0.6\,e^-1.2α)$ - Kasten & Young Air Mass (
h^circ ≥ 0,τ_RGB = (0.149, 0.194, 0.309)): $m(h) = (sin h^circ + 0.50572\,(h + 6.07995)^-1.6364)^-1, T_c = e^-τ_c (m(h) - m_0)$
Engine Implementation
Strict TypeScript Physical Night Sky Module (Assets/Game/nightSky.ts)
Zero external texture downloads (procedural lunar maria/highlands), strict erasable TypeScript, and clean BackSide sky-dome integration with game.scene:
import * as THREE from 'three';
import type { Game } from 'ccgd';
export interface NightSkyOptions {
/** 0 = new, 0.25 = first quarter, 0.5 = full, 0.75 = last quarter. */
phase?: number;
altitudeDeg?: number;
azimuthDeg?: number;
eclipse?: number;
earthshine?: number;
twinkle?: number;
meteorRatePerMinute?: number;
moonAngularRadius?: number;
}
export interface NightSkyController {
mesh: THREE.Mesh;
moonDirection: THREE.Vector3;
moonLightColor: THREE.Color;
moonLightIntensity: number;
uniforms: Record<string, THREE.IUniform>;
setPhase(phase: number): void;
setPosition(altitudeDeg: number, azimuthDeg: number): void;
setEclipse(amount: number): void;
launchMeteor(fireball?: boolean): boolean;
dispose(): void;
}
/** Optional half-res radial light-shaft fragment shader over a cloud transmittance buffer. */
export const GOD_RAYS_FRAG = /* glsl */ `
precision highp float;
uniform sampler2D tCloud;
uniform vec2 uMoonUV;
uniform float uAspect, uMoonRuv, uFade, uMoonPhase;
varying vec2 vUv;
float ign(vec2 p){ return fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715)))); }
void main(){
if (uFade <= 0.0){ gl_FragColor = vec4(0.0); return; }
float pa = uMoonPhase * 6.2831853, ct = cos(pa), sg = sin(pa) >= 0.0 ? 1.0 : -1.0;
vec2 gc = vec2(sg * (1.0 + ct) * 0.42441318, 0.0);
const int N = 48; vec2 delta = (uMoonUV - vUv) / float(N);
float j = ign(gl_FragCoord.xy), decay = 1.0, sum = 0.0; vec2 s = vUv + delta * j;
for (int i = 0; i < N; i++){
vec4 c = textureLod(tCloud, s, 0.0);
vec2 d = (s - uMoonUV) * vec2(uAspect, 1.0) / max(uMoonRuv, 1e-4);
float r = length(d), ang = (fract(float(i) * 0.6180340 + j) - 0.5) * 0.7;
vec2 pd = mat2(cos(ang), sin(ang), -sin(ang), cos(ang)) * d / max(r, 1.0);
float lit = smoothstep(-0.2, 0.0, sg * pd.x - ct * sqrt(max(1.0 - pd.y * pd.y, 0.0)));
float rg = length(d - gc);
sum += c.a * (smoothstep(1.25, 0.75, r) * lit + 0.32 * exp(-rg * 0.75) + 0.025 * exp(-rg * 0.28)) * decay;
decay *= 0.972; s += delta;
}
gl_FragColor = vec4(vec3(sum / float(N) * uFade), 1.0);
}
`;
const VERT = /* glsl */ `
varying vec3 vWorldOffset;
void main(){ vWorldOffset = position; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }
`;
const FRAG = /* glsl */ `
precision highp float;
uniform vec3 uMoonDir, uMoonDiskTint, uMetA, uMetB;
uniform float uMoonR, uMoonPhase, uMoonL, uEarth, uEclipse, uMoonClear, uTime, uPixAng, uTwinkle, uStarLow;
uniform vec4 uMet;
varying vec3 vWorldOffset;
float hash12(vec2 p){ vec3 p3 = fract(vec3(p.xyx) * 0.1031); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.x + p3.y) * p3.z); }
vec3 hash33(vec3 p3){ p3 = fract(p3 * vec3(0.1031, 0.1030, 0.0973)); p3 += dot(p3, p3.yxz + 33.33); return fract((p3.xxy + p3.yxx) * p3.zyx); }
float vnoise(vec2 p){
vec2 i = floor(p), f = fract(p); f = f * f * (3.0 - 2.0 * f);
return mix(mix(hash12(i), hash12(i + vec2(1.0, 0.0)), f.x), mix(hash12(i + vec2(0.0, 1.0)), hash12(i + vec2(1.0, 1.0)), f.x), f.y);
}
float moonAlbedo(vec2 uv){
float f = 0.55 * vnoise(uv * 3.8 + 1.3) + 0.28 * vnoise(uv * 8.5 + 4.1) + 0.17 * vnoise(uv * 19.0 + 9.7);
return mix(0.46, 1.18, smoothstep(0.32, 0.62, f));
}
vec3 skyBase(vec3 rd, vec3 m){
float y = rd.y;
vec3 col = mix(vec3(0.0075, 0.0135, 0.0280), vec3(0.0016, 0.0038, 0.0115), smoothstep(-0.02, 0.22, y));
col = mix(col, vec3(0.0005, 0.0012, 0.0045), smoothstep(0.18, 0.85, y));
float az = max(dot(normalize(rd.xz + 1e-5), normalize(m.xz + 1e-5)), 0.0);
col += vec3(0.34, 0.19, 0.09) * exp(-abs(y + 0.015) * 16.0) * (0.03 + 0.97 * pow(az, 6.0)) * 0.20;
col += vec3(0.10, 0.10, 0.12) * exp(-abs(y + 0.015) * 5.0) * pow(az, 3.0) * 0.08;
float a = 2.0 * asin(clamp(length(rd - m) * 0.5, 0.0, 1.0));
col += (vec3(0.30, 0.46, 0.90) * 0.0035 * exp(-a * 2.4) + vec3(0.55, 0.66, 0.88) * 0.0150 * exp(-a * 8.5)
+ vec3(1.00, 0.90, 0.74) * 0.1100 * exp(-a * 28.0) + vec3(1.00, 0.93, 0.80) * 0.4500 * exp(-a * 90.0)) * uMoonDiskTint;
return col;
}
float moonLit(vec3 n, float w){
float pa = uMoonPhase * 6.2831853, mu0 = dot(n, vec3(sin(pa), 0.0, -cos(pa)));
float ls = min(2.0 * max(mu0, 0.0) / max(mu0 + n.z, 1e-4), 1.6);
return ls * smoothstep(0.0, w, mu0) * (0.4 + 0.6 * exp(-1.2 * abs(3.1415927 - pa)));
}
float glowRow(float a, float b, float p, float k){
if (b <= a) return 0.0;
float ea = exp(-k * abs(a - p)), eb = exp(-k * abs(b - p));
if (p < a) return ea * (1.0 - exp(-k * (b - a)));
if (p > b) return eb * (1.0 - exp(-k * (b - a)));
return 2.0 - ea - eb;
}
vec2 moonGlowK(vec2 uv){
float pa = uMoonPhase * 6.2831853, c = cos(pa), sg = sin(pa) >= 0.0 ? 1.0 : -1.0;
vec2 k = vec2(28.0, 90.0) * uMoonR, L = vec2(0.0), D = vec2(0.0);
for (int i = 0; i < 16; i++){
float y = -1.0 + (float(i) + 0.5) * 0.125, s = sqrt(1.0 - y * y);
float a = sg > 0.0 ? c * s : -s, b = sg > 0.0 ? s : -c * s, dy = abs(y - uv.y);
vec2 kx = k / sqrt(1.0 + k * dy), wy = exp(-k * dy) / kx;
L += wy * vec2(glowRow(a, b, uv.x, kx.x), glowRow(a, b, uv.x, kx.y));
D += wy * vec2(glowRow(-s, s, uv.x, kx.x), glowRow(-s, s, uv.x, kx.y));
}
return L / max(D, vec2(1e-30));
}
vec3 moonNight(vec3 rd, vec3 m, float am, float litAt){
float haloK = mix(0.08, 1.0, uMoonL), pa = uMoonPhase * 6.2831853;
vec2 gk = vec2(0.5 - 0.5 * cos(pa));
if (am < 0.3){
vec3 mr = normalize(cross(m, vec3(0.0, 1.0, 0.0))), mu = cross(mr, m);
gk = mix(moonGlowK(vec2(dot(rd, mr), dot(rd, mu)) / uMoonR), gk, smoothstep(0.22, 0.3, am));
}
gk *= 0.4 + 0.6 * exp(-1.2 * abs(3.1415927 - pa));
vec3 haloW = (vec3(0.30, 0.46, 0.90) * 0.0035 * exp(-am * 2.4) + vec3(0.55, 0.66, 0.88) * 0.0150 * exp(-am * 8.5)) * uMoonDiskTint;
float amD = mix(max(am, uMoonR), am, litAt);
vec3 h28 = vec3(1.00, 0.90, 0.74) * 0.1100 * uMoonDiskTint, h90 = vec3(1.00, 0.93, 0.80) * 0.4500 * uMoonDiskTint;
return skyBase(rd, m) - haloW * (1.0 - haloK) - h28 * (exp(-am * 28.0) - exp(-amD * 28.0) * gk.x) - h90 * (exp(-am * 90.0) - exp(-amD * 90.0) * gk.y);
}
vec3 moonDisk(vec3 rd, vec3 m, out float litAt){
litAt = 1.0; if (dot(rd, m) < 0.9) return vec3(0.0);
vec3 mr = normalize(cross(m, vec3(0.0, 1.0, 0.0))), mu = cross(mr, m);
vec2 uv = vec2(dot(rd, mr), dot(rd, mu)) / uMoonR;
float r = length(uv), aa = uPixAng / uMoonR, edge = 1.0 - smoothstep(1.0 - aa * 1.2, 1.0 + aa * 0.6, r);
if (edge <= 0.0) return vec3(0.0);
vec3 n = vec3(uv, sqrt(max(1.0 - r * r, 0.0)));
float alb = mix(0.85, moonAlbedo(uv), uMoonClear), limb = mix(0.96, 0.88 + 0.12 * pow(n.z, 0.6), uMoonClear);
vec3 tint = mix(vec3(1.0, 0.90, 0.74), mix(vec3(1.00, 0.82, 0.60), vec3(1.0, 0.93, 0.80), n.z), uMoonClear);
litAt = clamp(moonLit(n, max(aa, 0.02)), 0.0, 1.0);
vec3 earth = vec3(0.55, 0.68, 1.0) * alb * 0.004 * (1.0 - 0.7 * uMoonL) * uEarth;
vec3 col = mix(earth, tint * alb * limb * 1.35, litAt) * uMoonDiskTint;
if (uEclipse > 0.0){
float side = clamp(0.5 + 0.5 * dot(uv, vec2(0.55, -0.83)), 0.0, 1.0);
vec3 ecl = mix(vec3(0.62, 0.10, 0.05), vec3(1.0, 0.38, 0.16), side * side) * (0.55 + 0.45 * side);
col = mix(col, ecl * mix(0.85, alb, 0.8) * limb * 0.55, uEclipse);
}
return col * edge;
}
float twinkle(float s, float amp){
float n = 0.5 * sin(uTime * (11.0 + 7.0 * fract(s * 1.37)) + s * 40.0)
+ 0.3 * sin(uTime * (17.0 + 9.0 * fract(s * 2.11)) + s * 13.0)
+ 0.2 * sin(uTime * (5.0 + 3.0 * fract(s * 3.70)) + s * 7.0);
return 1.0 - amp * (0.5 + 0.5 * n);
}
vec3 starField(vec3 rd){
vec3 col = vec3(0.0);
for (int l = 0; l < 2; l++){
float sc = l == 0 ? 150.0 : 320.0;
float thr = (l == 0 ? 0.9935 : 0.9915) - (1.0 - smoothstep(0.0, 0.3, rd.y)) * (l == 0 ? 0.006 : 0.008);
float w = max(0.045, uPixAng * sc * 0.85);
vec3 p = rd * sc, c0 = floor(p), fp = fract(p), s = step(0.5, fp) * 2.0 - 1.0, skipAx = step(2.5 * w, min(fp, 1.0 - fp));
for (int k = 0; k < 8; k++){
vec3 o = vec3(mod(float(k), 2.0), mod(floor(float(k) * 0.5), 2.0), floor(float(k) * 0.25));
if (dot(o, skipAx) > 0.0) continue;
vec3 id = c0 + o * s, h = hash33(id + float(l) * 71.3); if (h.x < thr) continue;
vec3 h2 = hash33(id * 1.7 + 11.0), pt = normalize(id + 0.5 + (h2 - 0.5) * 0.55) * sc;
if (any(notEqual(floor(pt), id))) continue;
float d = length(pt - rd * dot(pt, rd)), mag = (l == 0 ? 1.0 : 0.45) * (0.18 + 2.6 * pow(h2.y, 7.0));
float tw = twinkle(h.y + h2.x * 3.1, min(mix(0.6, 0.32, smoothstep(0.05, 0.45, rd.y)) * uTwinkle, 1.0));
col += mix(vec3(0.70, 0.80, 1.00), vec3(1.00, 0.88, 0.72), h.z) * mag * tw * exp(-d * d / (w * w)) * (0.045 * 0.045) / (w * w);
}
}
return col;
}
vec3 meteorStreak(vec3 rd){
vec3 n = normalize(cross(uMetA, uMetB)); float dn = dot(rd, n), w = max(uPixAng * 0.75, 2.0e-4);
if (abs(dn) > 6.0 * w) return vec3(0.0);
float ang = max(acos(clamp(dot(uMetA, uMetB), -1.0, 1.0)), 1e-4);
vec3 q = rd - n * dn; float s = atan(dot(cross(uMetA, q), n), dot(uMetA, q)) / ang;
float p = uMet.x, tl = max(uMet.z, 1e-3), k = (s - (p - tl)) / tl;
if (s < 0.0 || k < 0.0 || s > p + 6.0 * w / ang) return vec3(0.0);
float across = exp(-dn * dn / (w * w)), ds = (s - p) * ang;
float head = 2.2 * exp(-(ds * ds + dn * dn) / (w * w * 2.0));
float env = smoothstep(0.0, 0.12, p) * smoothstep(1.0, 0.72, p) * (0.6 + 0.6 * p);
return (mix(vec3(1.00, 0.80, 0.55), vec3(0.85, 1.00, 0.92), k) * (k < 1.0 ? k * k : 0.0) * across + vec3(0.88, 1.00, 0.95) * head) * env * uMet.y;
}
void main(){
vec3 rd = normalize(vWorldOffset), m = normalize(uMoonDir);
float am = 2.0 * asin(clamp(length(rd - m) * 0.5, 0.0, 1.0)), haloK = mix(0.08, 1.0, uMoonL);
float diskMask = 1.0 - smoothstep(uMoonR * 0.92, uMoonR * 0.99, am);
float starVis = smoothstep(max(uStarLow - 0.035, 0.0), uStarLow, rd.y) * mix(0.7, 1.0, smoothstep(0.0, 0.2, rd.y)) * mix(1.0, smoothstep(0.06, 0.45, am), haloK) * (1.0 - diskMask);
float litAt; vec3 disk = moonDisk(rd, m, litAt), night = moonNight(rd, m, am, litAt);
vec3 st = starVis > 0.0 ? starField(rd) * starVis : vec3(0.0);
if (uMet.w > 0.0 && rd.y > 0.0) st += meteorStreak(rd) * smoothstep(0.0, 0.03, rd.y);
gl_FragColor = vec4(night * (1.0 - 0.82 * diskMask * litAt) + st + disk, 1.0);
#include <colorspace_fragment>
}
`;
const MOON_HUES: readonly [number, number, number, number][] = [
[1, 1, 0.34, 0.16], [3, 1, 0.64, 0.32], [6, 1, 0.84, 0.62], [12, 1, 1, 1], [35, 0.96, 1, 1.06], [75, 0.93, 0.99, 1.1],
];
const MOON_TAU = [0.149, 0.194, 0.309] as const;
const airMass = (altDeg: number) => { const h = Math.max(altDeg, 0); return 1 / (Math.sin((h * Math.PI) / 180) + 0.50572 * Math.pow(h + 6.07995, -1.6364)); };
export function createNightSky(game: Game, opts: NightSkyOptions = {}): NightSkyController {
const moonDirection = new THREE.Vector3(), moonLightColor = new THREE.Color(0xdde8ff), air0 = airMass(12);
let phase = opts.phase ?? 0.5, altDeg = opts.altitudeDeg ?? 12, azDeg = opts.azimuthDeg ?? -15, eclipse = opts.eclipse ?? 0, moonLightIntensity = 1;
const uniforms: Record<string, THREE.IUniform> = {
uMoonDir: { value: moonDirection }, uMoonDiskTint: { value: new THREE.Vector3(1, 1, 1) },
uMoonR: { value: opts.moonAngularRadius ?? 0.044 }, uMoonPhase: { value: phase }, uMoonL: { value: 1 },
uEarth: { value: opts.earthshine ?? 1 }, uEclipse: { value: eclipse }, uMoonClear: { value: 1 },
uTime: { value: 0 }, uPixAng: { value: 0.0014 }, uTwinkle: { value: opts.twinkle ?? 1.3 }, uStarLow: { value: 0.035 },
uMetA: { value: new THREE.Vector3(0, 0.2, -0.98).normalize() }, uMetB: { value: new THREE.Vector3(0.2, 0.08, -0.97).normalize() }, uMet: { value: new THREE.Vector4(0, 0, 0.3, 0) },
};
function recomputeOptics(): void {
const a = THREE.MathUtils.degToRad(altDeg), z = THREE.MathUtils.degToRad(azDeg);
moonDirection.set(Math.cos(a) * Math.sin(z), Math.sin(a), -Math.cos(a) * Math.cos(z)).normalize();
const rawDAir = airMass(altDeg) - air0, dAir = rawDAir < 0 ? rawDAir * 0.5 : rawDAir;
const through = 0.2126 * Math.exp(-MOON_TAU[0] * dAir) + 0.7152 * Math.exp(-MOON_TAU[1] * dAir) + 0.0722 * Math.exp(-MOON_TAU[2] * dAir);
let i = 1; while (i < MOON_HUES.length - 1 && MOON_HUES[i][0] < altDeg) i++;
const lo = MOON_HUES[i - 1], hi = MOON_HUES[i], f = THREE.MathUtils.clamp((altDeg - lo[0]) / Math.max(hi[0] - lo[0], 1e-4), 0, 1);
const cr = lo[1] + (hi[1] - lo[1]) * f, cg = lo[2] + (hi[2] - lo[2]) * f, cb = lo[3] + (hi[3] - lo[3]) * f;
const lum = Math.max(0.2126 * cr + 0.7152 * cg + 0.0722 * cb, 1e-4);
const gd = Math.pow(through, 0.75) / lum, gl = Math.pow(through, 0.3) / lum;
const lit = 0.5 - 0.5 * Math.cos(phase * Math.PI * 2);
let moonL = Math.pow(lit, 1.5), dr = cr * gd, dg = cg * gd, db = cb * gd, lr = cr * gl, lg = cg * gl, lb = cb * gl;
if (eclipse > 0) {
dr += (0.3 - dr) * eclipse; dg += (0.045 - dg) * eclipse; db += (0.022 - db) * eclipse;
lr += (0.8 - lr) * eclipse; lg += (0.26 - lg) * eclipse; lb += (0.13 - lb) * eclipse;
moonL *= 1 - 0.65 * eclipse;
}
uniforms.uMoonPhase.value = phase; uniforms.uMoonL.value = moonL; uniforms.uEclipse.value = eclipse;
uniforms.uMoonClear.value = rawDAir > 0 ? 0.3 + 0.7 * Math.exp(-0.12 * rawDAir) : 1;
(uniforms.uMoonDiskTint.value as THREE.Vector3).set(dr, dg, db);
moonLightColor.setRGB(lr, lg, lb); moonLightIntensity = moonL;
}
recomputeOptics();
const geom = new THREE.SphereGeometry(Math.min(520, game.camera.far * 0.88), 24, 16);
const mat = new THREE.ShaderMaterial({ vertexShader: VERT, fragmentShader: FRAG, uniforms, side: THREE.BackSide, depthWrite: false });
const mesh = new THREE.Mesh(geom, mat);
mesh.name = 'PhysicalNightSky'; mesh.renderOrder = -1000; mesh.frustumCulled = false;
game.scene.add(mesh);
const met = { on: false, t: 0, dur: 1, next: opts.meteorRatePerMinute ? 60 / opts.meteorRatePerMinute : 30 };
const tmpR = new THREE.Vector3(), tmpU = new THREE.Vector3(), tmpF = new THREE.Vector3();
const tmpA = new THREE.Vector3(), tmpB = new THREE.Vector3(), tmpE = new THREE.Vector3(), tmpT = new THREE.Vector3(), sizeScratch = new THREE.Vector2();
function launchMeteor(fireball = false): boolean {
game.camera.updateMatrixWorld(); game.camera.matrixWorld.extractBasis(tmpR, tmpU, tmpF); tmpF.negate();
const ty = Math.tan(THREE.MathUtils.degToRad(game.camera.fov * 0.5)), tx = ty * game.camera.aspect;
tmpA.copy(tmpF).addScaledVector(tmpR, (Math.random() * 1.4 - 0.7) * tx).addScaledVector(tmpU, (0.15 + Math.random() * 0.6) * ty).normalize();
if (tmpA.y < 0.08) return false;
tmpE.set(tmpA.z, 0, -tmpA.x).normalize(); tmpT.crossVectors(tmpA, tmpE);
const th = -Math.PI * (0.2 + Math.random() * 0.6), len = (fireball ? 0.28 : 0.14) + Math.random() * 0.18;
tmpB.copy(tmpA).multiplyScalar(Math.cos(len)).addScaledVector(tmpE, Math.sin(len) * Math.cos(th)).addScaledVector(tmpT, Math.sin(len) * Math.sin(th)).normalize();
(uniforms.uMetA.value as THREE.Vector3).copy(tmpA); (uniforms.uMetB.value as THREE.Vector3).copy(tmpB);
(uniforms.uMet.value as THREE.Vector4).set(0, fireball ? 0.6 : 0.18, 0.32, 1);
met.on = true; met.t = 0; met.dur = len * (fireball ? 5.5 : 3.5);
return true;
}
game.onUpdate((dt) => {
const rate = opts.meteorRatePerMinute ?? 2;
if (met.on) {
if ((met.t += dt) < met.dur) (uniforms.uMet.value as THREE.Vector4).x = met.t / met.dur;
else { met.on = false; (uniforms.uMet.value as THREE.Vector4).w = 0; met.next = rate > 0 ? (-Math.log(1 - Math.min(0.999, Math.random())) * 60) / rate : Infinity; }
} else if (Number.isFinite(met.next) && (met.next -= dt) <= 0) {
launchMeteor(Math.random() < 0.08); if (!met.on) met.next = rate > 0 ? 60 / rate : Infinity;
}
});
game.onAlways(() => {
mesh.position.copy(game.camera.position); uniforms.uTime.value = game.time;
game.renderer.getDrawingBufferSize(sizeScratch);
const h = Math.max(1, Math.round((game.canvas.clientHeight || sizeScratch.y || 360) * game.renderer.getPixelRatio()));
uniforms.uPixAng.value = (2 * Math.tan(THREE.MathUtils.degToRad(game.camera.fov * 0.5))) / h;
});
return {
mesh, moonDirection, moonLightColor, get moonLightIntensity() { return moonLightIntensity; }, uniforms,
setPhase(next: number) { phase = THREE.MathUtils.clamp(next, 0, 1); recomputeOptics(); },
setPosition(alt: number, az: number) { altDeg = THREE.MathUtils.clamp(alt, 1, 75); azDeg = az; recomputeOptics(); },
setEclipse(amount: number) { eclipse = THREE.MathUtils.clamp(amount, 0, 1); recomputeOptics(); },
launchMeteor, dispose() { game.scene.remove(mesh); geom.dispose(); mat.dispose(); },
};
}
Performance & Browser Budgets
- Single draw call:
moonGlowKruns only within0.3 radof the moon andstarFieldruns only aboveuStarLow, keeping fragment cost under 0.35 ms at 1080p and instantaneous on SwiftShader. - Sync your directional light: Copy
sky.moonDirection,sky.moonLightColor, andsky.moonLightIntensityonto your scene'sDirectionalLightwhen phase, altitude, or eclipse changes. - Zero external fetches: Procedural maria/highlands render offline; swap in a texture under
Assets/Game/Textures/viagame.url(...)if desired.
Verification Checklist
- Run
compile(threeCompile) and verify zero WebGL shader compile/link errors. - Call
sky.setPhase(0.14)andsky.setPosition(2.5, -10), capture a view, and confirm the narrow halo hugs only the lit crescent limb. - Rotate the camera smoothly and confirm stars never clip or pop at cell boundaries.
Official references
- Weeb Labs — Nightscape (MIT)
- F. Kasten & A. T. Young (Applied Optics 1989 — Revised Optical Air Mass Tables)
- Bruce Hapke (Theory of Reflectance and Emittance Spectroscopy — Lommel-Seeliger Lunar Law)
- Kenny Mitchell (GPU Gems 3 — Volumetric Light Scattering as a Post-Process)
Open-source sources
- Adapts code from Nightscape by Weeb Labs (MIT License): moon, stars, meteors and god-ray shaders adapted to Three.js 0.183 TypeScript and the ccgd kit
Games built with this guide carry these credits, and the licence notices they ask for, in their third-party notices.
More Three.js games
Games made with GameCrew on the same engine. No game has been built with this guide yet: these show what Three.js games here look like.
More Three.js techniques
Baked 3D Volumetric Cloud Sea, World-Anchored Marching & TAA in Three.js →
Endless fly-above volumetric cloud sea in Three.js r183 WebGL 2 using a GPU-baked WebGL3DRenderTarget SDF and lighting volume, anti-boiling world-anchored z-plane marching, 3-octave Henyey-Greenstein scattering, and variance-clamped depth-packed TAA.
BVH Mesh & Character Capsule Collision in Three.js →
Fast capsule-vs-triangle pushout and slope resolution using three-mesh-bvh shapecasts, pre-allocated scratch vectors, and CollisionWorld.
Zero-Allocation Context Steering, Patrol Loops & Telegraphed AI in Three.js →
Deterministic 60 Hz enemy and companion AI in Three.js using 8-slot context steering against CollisionWorld, level.json patrol loops, attack-token pacing, and telegraphed strikes.
Instanced Wind Foliage, Object-Pooled Particles & Spring Feel in Three.js →
Single-draw-call THREE.InstancedMesh wind foliage with player bend, zero-GC pooled burst particles, and dt-invariant second-order springs that keep 60 Hz steps under 2 ms.
Use verified techniques inside a real game
Describe your game idea for free or connect an MCP assistant to search and contribute techniques.
