Spaces:
Running
Running
Download js/scene.js from AK51/MOP_tutorial: direct link, hf CLI and curl.
- Browser
- Download file 52.6 kB
-
https://huggingface.co/spaces/AK51/MOP_tutorial/resolve/main/js/scene.js
- Command line
-
hf download hf://spaces/AK51/MOP_tutorial/js/scene.js
-
curl -L -o scene.js https://huggingface.co/spaces/AK51/MOP_tutorial/resolve/main/js/scene.js
52.6 kB
// 3D magnetosphere scene: planet, dipole field lines, magnetopause, bow shock,
// solar wind, plasma torus, moons with flux tubes, and layered aurora shells.
// The Sun is always in the +X direction. Distances are compressed (not to scale).
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { CSS2DRenderer, CSS2DObject } from 'three/addons/renderers/CSS2DRenderer.js';
import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';
import { createMoonFX } from './moonfx.js';
THREE.ColorManagement.enabled = false;
const DEG = Math.PI / 180;
const SUN_DIR = new THREE.Vector3(1, 0, 0);
const MP_ALPHA = 0.6; // magnetopause flaring
const BS_SCALE = 1.35; // bow-shock stand-off relative to magnetopause
const BS_ALPHA = 0.8;
// mp = visual magnetopause stand-off distance in planet radii (compressed).
// Moon fields: dist = visual orbit radius (compressed), realDist = real orbit radius in planet radii,
// period = orbital period in days (negative = retrograde), dia = diameter in km,
// foot = draw the flux tube and auroral footprint.
export const PLANET_CFG = {
earth: {
style: 0, tex: 'earth', radiusKm: 6371, obliquity: 23.4, dipoleTilt: 11, offset: [0, 0, 0], period: 24, mp: 4.5,
atmo: [0.35, 0.6, 1.0], field: [0.45, 0.8, 1.0], disc: 0,
aurora: { colat: 20, width: 2.6, c1: [0.15, 1.0, 0.45], c2: [1.0, 0.2, 0.35], patchy: 0.15, intensity: 1.5, height: 0.07 },
rings: null, torus: null,
moons: [
{ key: 'moon', dist: 6.8, realDist: 60.3, period: 27.32, dia: 3474, incl: 5.1 }
]
},
jupiter: {
style: 1, tex: 'jupiter', radiusKm: 69911, obliquity: 3.1, dipoleTilt: 9.6, offset: [0, 0, 0], period: 9.93, mp: 10,
atmo: [0.9, 0.8, 0.65], field: [0.55, 0.75, 1.0], disc: 0.55,
aurora: { colat: 16, width: 2.0, c1: [0.75, 0.45, 1.0], c2: [1.0, 0.35, 0.85], patchy: 0.05, intensity: 1.9, height: 0.09 },
rings: null,
torus: { r: 3.2, tube: 0.32, color: [1.0, 0.45, 0.25], label: 'lbl.torusJ' },
moons: [
{ key: 'io', dist: 3.2, realDist: 5.9, period: 1.769, dia: 3643, foot: true },
{ key: 'europa', dist: 4.1, realDist: 9.4, period: 3.551, dia: 3122, foot: true },
{ key: 'ganymede', dist: 5.2, realDist: 15.0, period: 7.155, dia: 5268, foot: true },
{ key: 'callisto', dist: 6.6, realDist: 26.3, period: 16.69, dia: 4821 }
]
},
saturn: {
style: 2, tex: 'saturn', radiusKm: 58232, obliquity: 26.7, dipoleTilt: 0.0, offset: [0, 0.04, 0], period: 10.6, mp: 7.5,
atmo: [0.95, 0.85, 0.6], field: [0.5, 0.8, 1.0], disc: 0.25,
aurora: { colat: 15, width: 2.0, c1: [0.45, 0.6, 1.0], c2: [0.85, 0.4, 1.0], patchy: 0.35, intensity: 1.6, height: 0.08 },
rings: { inner: 1.24, outer: 2.27, style: 0 },
torus: { r: 2.9, tube: 0.42, color: [0.35, 0.6, 1.0], label: 'lbl.torusS' },
moons: [
{ key: 'mimas', dist: 2.5, realDist: 3.08, period: 0.942, dia: 396 },
{ key: 'enceladus', dist: 2.9, realDist: 3.95, period: 1.370, dia: 504, foot: true },
{ key: 'tethys', dist: 3.35, realDist: 4.89, period: 1.888, dia: 1062 },
{ key: 'dione', dist: 3.85, realDist: 6.26, period: 2.737, dia: 1123 },
{ key: 'rhea', dist: 4.55, realDist: 8.74, period: 4.518, dia: 1527 },
{ key: 'titan', dist: 6.0, realDist: 20.3, period: 15.945, dia: 5149 },
{ key: 'iapetus', dist: 8.8, realDist: 59.1, period: 79.32, dia: 1469, incl: 15 }
]
},
uranus: {
style: 3, tex: 'uranus', radiusKm: 25362, obliquity: 97.8, dipoleTilt: 59, offset: [0.05, -0.3, 0.0], period: 17.24, mp: 6.5,
atmo: [0.6, 0.9, 1.0], field: [0.45, 0.95, 0.9], disc: 0,
aurora: { colat: 18, width: 3.0, c1: [0.4, 1.0, 0.9], c2: [1.0, 0.45, 0.8], patchy: 0.8, intensity: 1.6, height: 0.07 },
rings: { inner: 1.6, outer: 2.0, style: 1 },
torus: null,
moons: [
{ key: 'miranda', dist: 2.4, realDist: 5.08, period: 1.413, dia: 472, incl: 4.3 },
{ key: 'ariel', dist: 2.9, realDist: 7.47, period: 2.520, dia: 1158 },
{ key: 'umbriel', dist: 3.5, realDist: 10.4, period: 4.144, dia: 1169 },
{ key: 'titania', dist: 4.4, realDist: 17.1, period: 8.706, dia: 1577 },
{ key: 'oberon', dist: 5.4, realDist: 22.8, period: 13.46, dia: 1523 }
]
},
neptune: {
style: 4, tex: 'neptune', radiusKm: 24622, obliquity: 28.3, dipoleTilt: 46.9, offset: [0.17, -0.5, 0.1], period: 16.1, mp: 6.5,
atmo: [0.35, 0.55, 1.0], field: [0.45, 0.75, 1.0], disc: 0,
aurora: { colat: 18, width: 3.0, c1: [0.4, 0.85, 1.0], c2: [0.7, 0.5, 1.0], patchy: 0.85, intensity: 1.5, height: 0.07 },
rings: { inner: 1.7, outer: 2.55, style: 2 },
torus: null,
moons: [
{ key: 'triton', dist: 4.2, realDist: 14.4, period: -5.877, dia: 2707, incl: 23 }
]
}
};
// Visual moon radius in planet radii: square-root scaling keeps small moons visible.
export function moonSize(planetCfg, m) {
return Math.max(0.035, 0.5 * Math.sqrt((m.dia / 2) / planetCfg.radiusKm));
}
// Featured moons for the page section (order matters).
export const FEATURED_MOONS = ['io', 'europa', 'ganymede', 'callisto', 'enceladus', 'titan', 'ariel', 'triton'];
export function moonHost(key) {
return Object.keys(PLANET_CFG).find(p => PLANET_CFG[p].moons.some(m => m.key === key));
}
export function moonData(key) {
const host = moonHost(key);
return host ? { host, ...PLANET_CFG[host].moons.find(m => m.key === key) } : null;
}
const TEX_BASE = 'textures/';
const texLoader = new THREE.TextureLoader();
const texCache = new Map();
function tex(name) {
if (!texCache.has(name)) {
const t = texLoader.load(TEX_BASE + name);
t.anisotropy = 8;
texCache.set(name, t);
}
return texCache.get(name);
}
/* ------------------------------------------------------------------ GLSL */
const NOISE_GLSL = /* glsl */`
float hash3(vec3 p){ p = fract(p*0.3183099 + 0.1); p *= 17.0; return fract(p.x*p.y*p.z*(p.x+p.y+p.z)); }
float noise3(vec3 x){
vec3 i = floor(x); vec3 f = fract(x); f = f*f*(3.0-2.0*f);
return mix(mix(mix(hash3(i+vec3(0,0,0)), hash3(i+vec3(1,0,0)), f.x),
mix(hash3(i+vec3(0,1,0)), hash3(i+vec3(1,1,0)), f.x), f.y),
mix(mix(hash3(i+vec3(0,0,1)), hash3(i+vec3(1,0,1)), f.x),
mix(hash3(i+vec3(0,1,1)), hash3(i+vec3(1,1,1)), f.x), f.y), f.z);
}
float fbm(vec3 p){ float a = 0.5, s = 0.0; for (int i = 0; i < 5; i++){ s += a*noise3(p); p *= 2.03; a *= 0.5; } return s; }
`;
// Shared deformation: compress the dayside field to the magnetopause and stretch the nightside into a tail.
const DEFORM_GLSL = /* glsl */`
float shueR(float cosT, float r0, float a){ return r0 * pow(2.0 / max(1.0 + cosT, 0.04), a); }
float softTanh(float x){ float e = exp(2.0*clamp(x,-10.0,10.0)); return (e-1.0)/(e+1.0); }
vec3 deformMag(vec3 p, float mp){
float r = length(p);
if (r < 1e-4) return p;
vec3 d = p / r;
float night = 1.0 - smoothstep(-0.6, 0.0, d.x);
float k = smoothstep(mp*0.45, mp*1.3, r);
p.x -= night * k * r * 1.3;
p.yz *= 1.0 - night * k * 0.35;
r = length(p); d = p / r;
float R = shueR(d.x, mp*0.97, ${MP_ALPHA.toFixed(2)});
float x = r / R;
float xs = x < 0.6 ? x : 0.6 + 0.4 * softTanh((x - 0.6) / 0.4);
return d * xs * R;
}
`;
function fieldLineMaterial(color, opacity, pulseSpeed = 0.35) {
return new THREE.ShaderMaterial({
uniforms: {
uTime: { value: 0 }, uMp: { value: 5 }, uColor: { value: new THREE.Color(...color) },
uOpacity: { value: opacity }, uSpeed: { value: pulseSpeed }
},
vertexShader: /* glsl */`
uniform float uMp;
attribute float aT; attribute float aSeed;
varying float vT; varying float vSeed; varying float vFade;
${DEFORM_GLSL}
void main(){
vec3 p = (modelMatrix * vec4(position, 1.0)).xyz;
p = deformMag(p, uMp);
vT = aT; vSeed = aSeed;
vFade = 1.0 - smoothstep(uMp*2.6, uMp*4.0, length(p));
gl_Position = projectionMatrix * viewMatrix * vec4(p, 1.0);
}`,
fragmentShader: /* glsl */`
uniform float uTime; uniform vec3 uColor; uniform float uOpacity; uniform float uSpeed;
varying float vT; varying float vSeed; varying float vFade;
void main(){
float s = abs(vT - 0.5) * 2.0; // 0 at magnetic equator, 1 at the footpoints
float pulse = pow(fract(s*3.0 - uTime*uSpeed + vSeed), 12.0);
float base = 0.22 + 0.25*(1.0 - s);
vec3 col = uColor * (base + pulse * 2.2);
gl_FragColor = vec4(col * uOpacity * vFade, 1.0);
}`,
transparent: true, depthWrite: false, blending: THREE.AdditiveBlending
});
}
function planetMaterial(cfg) {
return new THREE.ShaderMaterial({
uniforms: {
uStyle: { value: cfg.style }, uSun: { value: SUN_DIR.clone() },
uAtmo: { value: new THREE.Vector3(...cfg.atmo) }, uMap: { value: tex(cfg.tex + '.jpg') }
},
vertexShader: /* glsl */`
varying vec3 vObj; varying vec3 vWN; varying vec3 vWP; varying vec2 vUv;
void main(){
vObj = position; vUv = uv;
vWN = normalize(mat3(modelMatrix) * normal);
vec4 wp = modelMatrix * vec4(position, 1.0); vWP = wp.xyz;
gl_Position = projectionMatrix * viewMatrix * wp;
}`,
fragmentShader: /* glsl */`
uniform int uStyle; uniform vec3 uSun; uniform vec3 uAtmo; uniform sampler2D uMap;
varying vec3 vObj; varying vec3 vWN; varying vec3 vWP; varying vec2 vUv;
${NOISE_GLSL}
void main(){
vec3 col = texture2D(uMap, vUv).rgb;
vec3 N = normalize(vWN);
float ndl = dot(N, uSun);
// soft terminator: gas giants scatter light a little past the day-night line
float diff = uStyle == 0 ? max(ndl, 0.0) : smoothstep(-0.08, 1.0, ndl);
vec3 lit = col * (0.02 + 0.92 * diff);
vec3 V = normalize(cameraPosition - vWP);
float rim = pow(1.0 - max(dot(N, V), 0.0), 3.0);
lit += uAtmo * rim * (0.05 + 0.6 * smoothstep(-0.2, 0.6, ndl)) * 0.5;
if (uStyle == 0){
// city lights on the night side, only over land
float land = smoothstep(0.02, 0.1, max(col.r, col.g) - col.b);
vec3 n = normalize(vObj);
float night = 1.0 - smoothstep(-0.15, 0.08, ndl);
float city = land * smoothstep(0.6, 0.8, noise3(n * 70.0)) * (1.0 - smoothstep(0.65, 0.8, abs(n.y)));
lit += vec3(1.0, 0.72, 0.35) * city * night * 0.7;
}
gl_FragColor = vec4(lit, 1.0);
}`
});
}
function auroraMaterial(cfg, layer) {
const a = cfg.aurora;
return new THREE.ShaderMaterial({
uniforms: {
uTime: { value: 0 }, uLayer: { value: layer },
uNorth: { value: new THREE.Vector3(0, 1, 0) }, uSouth: { value: new THREE.Vector3(0, -1, 0) },
uColat: { value: a.colat }, uWidth: { value: a.width }, uPatchy: { value: a.patchy },
uIntensity: { value: a.intensity },
uC1: { value: new THREE.Vector3(...a.c1) }, uC2: { value: new THREE.Vector3(...a.c2) },
uFoot: { value: Array.from({ length: 6 }, () => new THREE.Vector3(0, 0, 0)) },
uFootW: { value: new Array(6).fill(0) },
uBoost: { value: 1 }
},
vertexShader: /* glsl */`
varying vec3 vObj; varying vec3 vWN; varying vec3 vV;
void main(){
vObj = position;
vWN = normalize(mat3(modelMatrix) * normal);
vec4 wp = modelMatrix * vec4(position, 1.0);
vV = cameraPosition - wp.xyz;
gl_Position = projectionMatrix * viewMatrix * wp;
}`,
fragmentShader: /* glsl */`
uniform float uTime, uLayer, uColat, uWidth, uPatchy, uIntensity, uBoost;
uniform vec3 uNorth, uSouth, uC1, uC2;
uniform vec3 uFoot[6]; uniform float uFootW[6];
varying vec3 vObj; varying vec3 vWN; varying vec3 vV;
${NOISE_GLSL}
float oval(vec3 n, vec3 pole, float seed){
float c = degrees(acos(clamp(dot(n, pole), -1.0, 1.0)));
if (c > uColat * 2.2 + 8.0) return 0.0;
vec3 ref = abs(pole.y) < 0.9 ? vec3(0.0,1.0,0.0) : vec3(1.0,0.0,0.0);
vec3 t1 = normalize(cross(pole, ref)); vec3 t2 = cross(pole, t1);
float az = atan(dot(n, t2), dot(n, t1));
vec2 cs = vec2(cos(az), sin(az));
float w = (noise3(vec3(cs*1.7, uTime*0.07 + seed)) - 0.5) * uColat * 0.4;
float d = (c - uColat - w) / uWidth;
float ring = exp(-d*d);
float rays = 0.45 + 0.55 * noise3(vec3(cs*26.0, uTime*0.5 + seed));
float patches = smoothstep(0.42, 0.75, noise3(vec3(cs*3.2, uTime*0.12 + seed))) * 2.2;
float patchMix = mix(1.0, patches, uPatchy);
float polar = (1.0 - smoothstep(0.0, uColat*0.85, c)) * pow(noise3(n*8.0 + vec3(0.0, uTime*0.35, seed)), 3.0) * 1.4;
return ring * rays * patchMix + polar * (1.0 - uPatchy);
}
void main(){
vec3 n = normalize(vObj);
float a = oval(n, uNorth, 0.0) + oval(n, uSouth, 7.3);
for (int i = 0; i < 6; i++){
float dd = length(n - uFoot[i]);
a += uFootW[i] * exp(-dd*dd / 0.0009) * 2.5;
}
float layerFade = pow(1.0 - uLayer, 1.5);
vec3 N = normalize(vWN);
float mu = abs(dot(N, normalize(vV)));
float limb = 0.45 + 0.9 * (1.0 - mu);
vec3 col = mix(uC1, uC2, smoothstep(0.0, 1.0, uLayer));
gl_FragColor = vec4(col * a * layerFade * limb * uIntensity * uBoost * 0.32, 1.0);
}`,
transparent: true, depthWrite: false, blending: THREE.AdditiveBlending
});
}
function boundaryMaterial(color, strength, tail) {
return new THREE.ShaderMaterial({
uniforms: { uTime: { value: 0 }, uColor: { value: new THREE.Color(...color) }, uStrength: { value: strength }, uTail: { value: tail },
uFrontX: { value: 1e6 }, uCR: { value: 1 }, uCP: { value: 0 }, uKb: { value: 1 }, uCW: { value: 1 } },
vertexShader: /* glsl */`
uniform float uFrontX, uCR, uCP, uKb, uCW;
varying vec3 vN; varying vec3 vV; varying vec3 vP;
float sc(float k){ return clamp(pow(k, -0.22), 0.7, 1.35); }
void main(){
vec4 wp = modelMatrix * vec4(position, 1.0);
// CME front is a paraboloid x = front + rho^2 / 2R; everything sunward of it feels the extra pressure
float rho = length(wp.yz);
float amt = smoothstep(-uCW, uCW, wp.x - (uFrontX + rho * rho / (2.0 * uCR)));
wp.xyz *= sc(uKb + uCP * amt) / sc(uKb);
vP = wp.xyz; vN = normalize(mat3(modelMatrix) * normal); vV = cameraPosition - wp.xyz;
gl_Position = projectionMatrix * viewMatrix * wp;
}`,
fragmentShader: /* glsl */`
uniform float uTime, uStrength, uTail; uniform vec3 uColor;
varying vec3 vN; varying vec3 vV; varying vec3 vP;
void main(){
float f = pow(1.0 - abs(dot(normalize(vN), normalize(vV))), 2.2);
float waves = 0.75 + 0.25 * sin(vP.x * 1.2 + uTime * 2.0 + sin(vP.y * 0.8) * 2.0);
float fade = smoothstep(-uTail, -uTail * 0.55, vP.x);
float a = (f * 0.85 + 0.03) * waves * fade * uStrength;
gl_FragColor = vec4(uColor * a, 1.0);
}`,
transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, side: THREE.DoubleSide
});
}
// Coronal mass ejection: a glowing, turbulent cap of plasma that sweeps from the Sun past the planet.
function cmeMaterial(R, cosCap) {
return new THREE.ShaderMaterial({
uniforms: { uTime: { value: 0 }, uFade: { value: 1 }, uR: { value: R }, uCap: { value: cosCap }, uNear: { value: R / 3.2 } },
vertexShader: /* glsl */`
uniform float uR;
varying float vC; varying vec3 vN; varying vec3 vV; varying vec3 vL;
void main(){
vC = position.y / uR; vL = position / uR;
vec4 wp = modelMatrix * vec4(position, 1.0);
vN = normalize(mat3(modelMatrix) * normal); vV = cameraPosition - wp.xyz;
gl_Position = projectionMatrix * viewMatrix * wp;
}`,
fragmentShader: /* glsl */`
uniform float uTime, uFade, uCap, uNear;
varying float vC; varying vec3 vN; varying vec3 vV; varying vec3 vL;
${NOISE_GLSL}
void main(){
float edge = smoothstep(uCap, uCap + (1.0 - uCap) * 0.55, vC);
float n = noise3(vL * 7.0 + vec3(0.0, uTime * 0.6, 0.0));
float fil = pow(noise3(vL * 22.0 - vec3(uTime * 0.9)), 2.0);
float f = pow(1.0 - abs(dot(normalize(vN), normalize(vV))), 1.4);
vec3 col = mix(vec3(1.0, 0.35, 0.12), vec3(1.0, 0.85, 0.5), n);
float a = edge * (0.25 + 0.75 * n + fil * 1.2) * (0.2 + 1.2 * f) * uFade;
// fade out as the front sweeps past the camera so it never floods the screen
a *= smoothstep(uNear * 0.4, uNear * 1.6, length(vV));
gl_FragColor = vec4(col * a * 0.32, 1.0);
}`,
transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, side: THREE.DoubleSide
});
}
function torusMaterial(color) {
return new THREE.ShaderMaterial({
uniforms: { uTime: { value: 0 }, uColor: { value: new THREE.Vector3(...color) } },
vertexShader: /* glsl */`
varying vec3 vN; varying vec3 vV; varying vec3 vObj;
void main(){
vObj = position;
vec4 mv = modelViewMatrix * vec4(position, 1.0);
vN = normalize(normalMatrix * normal); vV = normalize(-mv.xyz);
gl_Position = projectionMatrix * mv;
}`,
fragmentShader: /* glsl */`
uniform float uTime; uniform vec3 uColor;
varying vec3 vN; varying vec3 vV; varying vec3 vObj;
${NOISE_GLSL}
void main(){
float f = abs(dot(normalize(vN), normalize(vV)));
float n = noise3(vObj * 3.0 + vec3(0.0, 0.0, uTime * 0.2));
float g = pow(f, 1.6) * (0.5 + 0.9 * n);
gl_FragColor = vec4(uColor * g * 0.32, 1.0);
}`,
transparent: true, depthWrite: false, blending: THREE.AdditiveBlending
});
}
function ringMaterial(cfg) {
return new THREE.ShaderMaterial({
uniforms: {
uInner: { value: cfg.rings.inner }, uOuter: { value: cfg.rings.outer },
uStyle: { value: cfg.rings.style }, uSun: { value: SUN_DIR.clone() },
uRing: { value: cfg.rings.style === 0 ? tex('saturn_ring.png') : null }
},
vertexShader: /* glsl */`
varying vec3 vObj; varying vec3 vWP;
void main(){
vObj = position;
vec4 wp = modelMatrix * vec4(position, 1.0); vWP = wp.xyz;
gl_Position = projectionMatrix * viewMatrix * wp;
}`,
fragmentShader: /* glsl */`
uniform float uInner, uOuter; uniform int uStyle; uniform vec3 uSun; uniform sampler2D uRing;
varying vec3 vObj; varying vec3 vWP;
void main(){
float r = length(vObj.xy);
float t = (r - uInner) / (uOuter - uInner);
float dens; vec3 col;
if (uStyle == 0){
vec4 tx = texture2D(uRing, vec2(clamp(t, 0.0, 1.0), 0.5));
dens = tx.a; col = tx.rgb;
} else {
float ringlets = 0.0;
for (int i = 0; i < 6; i++){
float c = 0.08 + float(i) * 0.17;
ringlets += exp(-pow((t - c) / 0.012, 2.0));
}
dens = ringlets * (uStyle == 1 ? 0.45 : 0.25);
col = vec3(0.55, 0.6, 0.65);
}
float along = dot(vWP, uSun);
float perp = length(vWP - along * uSun);
float shadow = (along < 0.0 && perp < 1.0) ? 0.08 : 1.0;
gl_FragColor = vec4(col * shadow, dens);
}`,
transparent: true, depthWrite: false, side: THREE.DoubleSide
});
}
/* ------------------------------------------------------------- helpers */
function shue(cosT, r0, a) { return r0 * Math.pow(2 / Math.max(1 + cosT, 0.04), a); }
function deformMagJS(p, mp) {
// CPU copy of the GLSL deformation, used to place labels and moons' flux tubes consistently.
let r = p.length();
if (r < 1e-4) return p;
let d = p.clone().divideScalar(r);
const sm = (e0, e1, x) => { const t = Math.min(1, Math.max(0, (x - e0) / (e1 - e0))); return t * t * (3 - 2 * t); };
const night = 1 - sm(-0.6, 0, d.x);
const k = sm(mp * 0.45, mp * 1.3, r);
p.x -= night * k * r * 1.3;
p.y *= 1 - night * k * 0.35; p.z *= 1 - night * k * 0.35;
r = p.length(); d = p.clone().divideScalar(r);
const R = shue(d.x, mp * 0.97, MP_ALPHA);
const x = r / R;
const xs = x < 0.6 ? x : 0.6 + 0.4 * Math.tanh((x - 0.6) / 0.4);
return d.multiplyScalar(xs * R);
}
function boundaryGeometry(r0, alpha, tailLen) {
// Surface of revolution around the X axis (Shue et al. magnetopause shape), open at the tail.
let thMax = 0;
for (let th = 0; th < 175 * DEG; th += 0.25 * DEG) {
thMax = th;
if (shue(Math.cos(th), r0, alpha) * Math.cos(th) < -tailLen) break;
}
const nT = 90, nP = 96;
const pos = [], idx = [];
for (let i = 0; i <= nT; i++) {
const th = thMax * i / nT;
const r = shue(Math.cos(th), r0, alpha);
for (let j = 0; j <= nP; j++) {
const ph = 2 * Math.PI * j / nP;
pos.push(r * Math.cos(th), r * Math.sin(th) * Math.cos(ph), r * Math.sin(th) * Math.sin(ph));
}
}
for (let i = 0; i < nT; i++) for (let j = 0; j < nP; j++) {
const a = i * (nP + 1) + j, b = a + nP + 1;
idx.push(a, b, a + 1, b, b + 1, a + 1);
}
const g = new THREE.BufferGeometry();
g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
g.setIndex(idx);
g.computeVertexNormals();
return g;
}
function fieldLineGeometry(cfg) {
const pos = [], aT = [], aSeed = [];
const Ls = [0.26, 0.38, 0.52, 0.7, 0.9, 1.25, 1.9, 3.0].map(f => Math.max(1.25, f * cfg.mp));
const nLon = 10, N = 110;
Ls.forEach((L, li) => {
const th0 = Math.asin(Math.min(1, Math.sqrt(1 / L)));
for (let j = 0; j < nLon; j++) {
const phi = (j / nLon) * 2 * Math.PI + li * 0.26;
const seed = Math.random();
let prev = null;
for (let i = 0; i <= N; i++) {
const u = i / N;
const th = th0 + (Math.PI - 2 * th0) * u;
const s = Math.sin(th);
let r = L * s * s;
if (cfg.disc) r *= 1 + cfg.disc * Math.pow(s, 10) * Math.min(1, L / cfg.mp);
const x = r * s * Math.cos(phi), y = r * Math.cos(th), z = r * s * Math.sin(phi);
if (prev) { pos.push(prev[0], prev[1], prev[2], x, y, z); aT.push(prev[3], u); aSeed.push(seed, seed); }
prev = [x, y, z, u];
}
}
});
const g = new THREE.BufferGeometry();
g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
g.setAttribute('aT', new THREE.Float32BufferAttribute(aT, 1));
g.setAttribute('aSeed', new THREE.Float32BufferAttribute(aSeed, 1));
return g;
}
function glowTexture(inner = 'rgba(255,255,255,1)', outer = 'rgba(255,255,255,0)') {
const c = document.createElement('canvas'); c.width = c.height = 128;
const g = c.getContext('2d');
const grd = g.createRadialGradient(64, 64, 0, 64, 64, 64);
grd.addColorStop(0, inner); grd.addColorStop(0.25, inner.replace(/[\d.]+\)$/, '0.6)')); grd.addColorStop(1, outer);
g.fillStyle = grd; g.fillRect(0, 0, 128, 128);
const t = new THREE.CanvasTexture(c);
return t;
}
function makeLabel(key, cls = '') {
const el = document.createElement('div');
el.className = 'scene-label ' + cls;
el.dataset.key = key;
const obj = new CSS2DObject(el);
obj.userData.labelKey = key;
return obj;
}
/* --------------------------------------------------------------- scene */
export function createScene(container, { t = k => k, onPlanetChange = () => {}, onSelect = () => {} } = {}) {
const renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: 'high-performance' });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.LinearSRGBColorSpace;
renderer.setClearColor(0x02030a, 1);
container.appendChild(renderer.domElement);
const labelRenderer = new CSS2DRenderer();
labelRenderer.domElement.className = 'label-layer';
container.appendChild(labelRenderer.domElement);
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(45, 1, 0.05, 3000);
camera.position.set(6, 3, 18);
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.06;
controls.minDistance = 1.5;
controls.maxDistance = 120;
controls.autoRotate = false;
const composer = new EffectComposer(renderer);
composer.addPass(new RenderPass(scene, camera));
const bloom = new UnrealBloomPass(new THREE.Vector2(256, 256), 0.65, 0.5, 0.9);
composer.addPass(bloom);
composer.addPass(new OutputPass());
scene.add(new THREE.AmbientLight(0xffffff, 0.06));
const sunLight = new THREE.DirectionalLight(0xffffff, 1.6);
sunLight.position.copy(SUN_DIR).multiplyScalar(100);
scene.add(sunLight);
// Milky Way backdrop + stars
{
const sky = new THREE.Mesh(new THREE.SphereGeometry(1500, 64, 32), new THREE.MeshBasicMaterial({ map: tex('milkyway.jpg'), side: THREE.BackSide, depthWrite: false, color: 0xb0b0c0 }));
sky.rotation.set(0.5, 0, 0.9);
scene.add(sky);
}
{
const n = 2500, p = new Float32Array(n * 3), c = new Float32Array(n * 3);
for (let i = 0; i < n; i++) {
const v = new THREE.Vector3().randomDirection().multiplyScalar(900 + Math.random() * 300);
p.set([v.x, v.y, v.z], i * 3);
const b = 0.4 + Math.random() * 0.6, tint = Math.random();
c.set([b * (0.85 + 0.15 * tint), b * 0.9, b * (1.0 - 0.15 * tint)], i * 3);
}
const g = new THREE.BufferGeometry();
g.setAttribute('position', new THREE.BufferAttribute(p, 3));
g.setAttribute('color', new THREE.BufferAttribute(c, 3));
scene.add(new THREE.Points(g, new THREE.PointsMaterial({ size: 1.6, sizeAttenuation: false, vertexColors: true, depthWrite: false })));
}
// Sun glow (far away in +X)
const sun = new THREE.Sprite(new THREE.SpriteMaterial({ map: glowTexture('rgba(255,236,190,1)', 'rgba(255,170,60,0)'), blending: THREE.AdditiveBlending, depthWrite: false }));
sun.position.set(400, 0, 0); sun.scale.set(90, 90, 1);
scene.add(sun);
const dotTex = glowTexture();
const state = {
name: null, cfg: null, root: null, time: 0, speed: 1,
layers: { field: true, wind: true, mp: true, aurora: true, torus: true, moons: true, labels: true },
objs: {}, tween: null, auroraBoost: 1, follow: null, wind: 1, windK: 1
};
/* ---------------------------------------------------- build a planet */
function disposeRoot() {
if (!state.root) return;
state.root.traverse(o => {
if (o.geometry) o.geometry.dispose();
if (o.material) (Array.isArray(o.material) ? o.material : [o.material]).forEach(m => m.dispose());
if (o.isCSS2DObject && o.element.parentNode) o.element.parentNode.removeChild(o.element);
});
scene.remove(state.root);
state.root = null;
}
function build(name) {
disposeRoot();
const cfg = PLANET_CFG[name];
state.name = name; state.cfg = cfg;
const root = new THREE.Group();
const tilt = new THREE.Group();
tilt.rotation.z = -cfg.obliquity * DEG; // lean the spin axis towards/away from the Sun
const spin = new THREE.Group();
tilt.add(spin); root.add(tilt);
const planet = new THREE.Mesh(new THREE.SphereGeometry(1, 128, 64), planetMaterial(cfg));
spin.add(planet);
planet.userData.pick = { type: 'planet' };
let clouds = null;
if (cfg.style === 0) {
clouds = new THREE.Mesh(new THREE.SphereGeometry(1.012, 96, 48), new THREE.MeshLambertMaterial({ color: 0xffffff, alphaMap: tex('earth_clouds.jpg'), transparent: true, depthWrite: false, opacity: 0.9 }));
spin.add(clouds);
}
// Magnetic frame (rotates with the planet, tilted and offset dipole)
const mag = new THREE.Group();
mag.position.set(...cfg.offset);
mag.rotation.z = cfg.dipoleTilt * DEG;
spin.add(mag);
const fieldMat = fieldLineMaterial(cfg.field, 0.42);
fieldMat.uniforms.uMp.value = cfg.mp;
const field = new THREE.LineSegments(fieldLineGeometry(cfg), fieldMat);
field.frustumCulled = false;
mag.add(field);
// Aurora poles in spin-frame coordinates
const axis = new THREE.Vector3(0, 1, 0).applyEuler(mag.rotation);
const off = new THREE.Vector3(...cfg.offset);
const north = axis.clone().add(off.clone().multiplyScalar(0.8)).normalize();
const south = axis.clone().negate().add(off.clone().multiplyScalar(0.8)).normalize();
const auroraGroup = new THREE.Group();
const auroraMats = [];
const nShell = 9;
for (let i = 0; i < nShell; i++) {
const layer = i / (nShell - 1);
const m = auroraMaterial(cfg, layer);
m.uniforms.uNorth.value.copy(north); m.uniforms.uSouth.value.copy(south);
const shell = new THREE.Mesh(new THREE.SphereGeometry(1.004 + layer * cfg.aurora.height, 128, 64), m);
shell.renderOrder = 2;
auroraGroup.add(shell); auroraMats.push(m);
}
spin.add(auroraGroup);
// Rings
let rings = null;
if (cfg.rings) {
rings = new THREE.Mesh(new THREE.RingGeometry(cfg.rings.inner, cfg.rings.outer, 256, 1), ringMaterial(cfg));
rings.rotation.x = -Math.PI / 2;
rings.renderOrder = 1;
tilt.add(rings);
}
// Plasma torus (follows the tilted magnetic/centrifugal equator, so it wobbles)
let torus = null;
if (cfg.torus) {
const pivot = new THREE.Group();
pivot.rotation.z = cfg.dipoleTilt * DEG * 0.66;
torus = new THREE.Mesh(new THREE.TorusGeometry(cfg.torus.r, cfg.torus.tube, 48, 160), torusMaterial(cfg.torus.color));
torus.rotation.x = Math.PI / 2;
torus.scale.set(1, 1, 0.65);
pivot.add(torus);
const lab = makeLabel(cfg.torus.label, 'torus');
lab.position.set(0, 0, 0);
const labHolder = new THREE.Object3D(); labHolder.position.set(-cfg.torus.r * 0.75, cfg.torus.r * 0.75, cfg.torus.tube);
pivot.add(labHolder); labHolder.add(lab);
spin.add(pivot);
torus.userData.pivot = pivot; torus.userData.label = lab;
}
// Moons and flux tubes
const moons = [];
cfg.moons.forEach((m, mi) => {
m = { ...m, size: moonSize(cfg, m), phase: m.phase ?? (0.7 + mi * 2.4) };
const holder = new THREE.Group();
if (m.incl) holder.rotation.x = m.incl * DEG;
const mesh = new THREE.Mesh(new THREE.SphereGeometry(m.size, 48, 24), new THREE.MeshStandardMaterial({ map: tex(m.key + '.jpg'), roughness: 1, metalness: 0 }));
mesh.userData.pick = { type: 'moon', key: m.key };
// invisible, larger hit sphere so small moons are easy to click
const hit = new THREE.Mesh(new THREE.SphereGeometry(Math.max(m.size * 1.8, 0.14), 12, 8), new THREE.MeshBasicMaterial({ visible: false }));
hit.userData.pick = mesh.userData.pick;
mesh.add(hit);
holder.add(mesh);
tilt.add(holder);
const label = makeLabel('moons.' + m.key, 'moon');
label.position.set(0, m.size + 0.1, 0);
mesh.add(label);
let tube = null;
if (m.foot) {
const n = 81;
const g = new THREE.BufferGeometry();
g.setAttribute('position', new THREE.BufferAttribute(new Float32Array(n * 3), 3));
const at = new Float32Array(n); for (let i = 0; i < n; i++) at[i] = i / (n - 1);
g.setAttribute('aT', new THREE.BufferAttribute(at, 1));
g.setAttribute('aSeed', new THREE.BufferAttribute(new Float32Array(n), 1));
const tm = fieldLineMaterial([1.0, 0.85, 0.45], 1.6, 0.9);
tm.uniforms.uMp.value = cfg.mp;
tube = new THREE.Line(g, tm);
tube.frustumCulled = false;
root.add(tube);
}
// plasma, aurora, plumes and atmosphere around the moon
const fx = createMoonFX(m.key, { size: m.size, dist: m.dist, holder });
const fxLabels = [];
if (fx) {
mesh.add(fx.group);
fx.anchors.forEach(a => { const l = makeLabel('fx.' + a.key, 'fx'); l.visible = false; l.userData.aurora = a.aurora; l.userData.cond = a.cond; a.obj.add(l); fxLabels.push(l); });
}
moons.push({ cfg: m, holder, mesh, tube, label, fx, fxLabels });
});
// Boundaries (fixed in the Sun-planet frame)
const tailLen = cfg.mp * 3.6;
const mpMesh = new THREE.Mesh(boundaryGeometry(cfg.mp, MP_ALPHA, tailLen), boundaryMaterial([0.3, 0.7, 1.0], 0.3, tailLen));
const bsMesh = new THREE.Mesh(boundaryGeometry(cfg.mp * BS_SCALE, BS_ALPHA, tailLen * 0.7), boundaryMaterial([1.0, 0.55, 0.25], 0.18, tailLen * 0.7));
mpMesh.renderOrder = 3; bsMesh.renderOrder = 3;
mpMesh.userData.base = 0.3; bsMesh.userData.base = 0.18;
const boundaries = new THREE.Group();
boundaries.add(mpMesh, bsMesh);
{
const th = 38 * DEG, r = shue(Math.cos(th), cfg.mp, MP_ALPHA);
const l1 = makeLabel('lbl.mp', 'mp'); l1.position.set(r * Math.cos(th), r * Math.sin(th), 0); boundaries.add(l1);
const th2 = 30 * DEG, r2 = shue(Math.cos(th2), cfg.mp * BS_SCALE, BS_ALPHA);
const l2 = makeLabel('lbl.bs', 'bs'); l2.position.set(r2 * Math.cos(th2), -r2 * Math.sin(th2), 0); boundaries.add(l2);
const l3 = makeLabel('lbl.tail', 'tail'); l3.position.set(-cfg.mp * 2.4, cfg.mp * 0.25, 0); boundaries.add(l3);
}
root.add(boundaries);
// Solar wind particles
const N = 4200;
const wpos = new Float32Array(N * 3), wcol = new Float32Array(N * 3), wvel = new Float32Array(N);
const spawnX = cfg.mp * 3.2, spawnR = cfg.mp * 2.6, endX = -tailLen * 0.9;
const respawn = (i, anywhere) => {
const a = Math.random() * Math.PI * 2, rr = Math.sqrt(Math.random()) * spawnR;
wpos[i * 3] = anywhere ? endX + Math.random() * (spawnX - endX) : spawnX + Math.random() * 2;
wpos[i * 3 + 1] = Math.cos(a) * rr; wpos[i * 3 + 2] = Math.sin(a) * rr;
wvel[i] = 0.8 + Math.random() * 0.4;
};
for (let i = 0; i < N; i++) respawn(i, true);
const wg = new THREE.BufferGeometry();
wg.setAttribute('position', new THREE.BufferAttribute(wpos, 3));
wg.setAttribute('color', new THREE.BufferAttribute(wcol, 3));
const wind = new THREE.Points(wg, new THREE.PointsMaterial({ size: cfg.mp * 0.045, map: dotTex, vertexColors: true, transparent: true, depthWrite: false, blending: THREE.AdditiveBlending }));
wind.frustumCulled = false;
const windLabel = makeLabel('lbl.wind', 'wind');
windLabel.position.set(spawnX * 0.8, cfg.mp * 1.15, 0);
wind.add(windLabel);
root.add(wind);
// CME shock front (hidden until launched)
const cmeR = cfg.mp * 3.2, cmeCap = Math.cos(42 * DEG);
const cme = new THREE.Mesh(new THREE.SphereGeometry(cmeR, 64, 24, 0, Math.PI * 2, 0, 42 * DEG), cmeMaterial(cmeR, cmeCap));
cme.rotation.z = Math.PI / 2; // cap apex points at the planet (−x)
cme.renderOrder = 4; cme.visible = false; cme.frustumCulled = false;
cme.userData.R = cmeR;
root.add(cme);
state.cme = null;
scene.add(root);
state.root = root;
state.objs = { tilt, spin, mag, planet, clouds, field, auroraGroup, auroraMats, rings, torus, moons, boundaries, mpMesh, bsMesh, wind, cme, wpos, wcol, wvel, respawn, spawnX, endX, north, south };
state.time = 0;
applyLayers();
refreshLabels();
onPlanetChange(name);
}
/* ------------------------------------------------------------ update */
const tmpV = new THREE.Vector3(), tmpW = new THREE.Vector3(), magInv = new THREE.Matrix4();
function updateMoons(dt = 0, tsec = 0) {
const { moons, mag, spin, auroraMats } = state.objs;
const feet = [], weights = [];
mag.updateWorldMatrix(true, false);
magInv.copy(mag.matrixWorld).invert();
moons.forEach(mo => {
const m = mo.cfg;
const ang = m.phase + (2 * Math.PI / (m.period * 24)) * state.time;
mo.mesh.position.set(m.dist * Math.cos(ang), 0, -m.dist * Math.sin(ang));
mo.mesh.rotation.y = ang + Math.PI; // tidally locked: the same face always looks at the planet
if (mo.fx && state.layers.moons) {
mo.mesh.getWorldPosition(tmpW);
mo.fx.update(dt, ang, tsec, { aurora: state.layers.aurora, speed: state.speed, camDist: camera.position.distanceTo(tmpW) / m.size });
}
if (!mo.tube) return;
mo.mesh.getWorldPosition(tmpW);
const local = tmpV.copy(tmpW).applyMatrix4(magInv);
const r = local.length();
const th = Math.acos(THREE.MathUtils.clamp(local.y / r, -1, 1));
const s = Math.sin(th);
const L = r / Math.max(s * s, 1e-3);
const phi = Math.atan2(local.z, local.x);
const th0 = Math.asin(Math.min(1, Math.sqrt(1 / L)));
const arr = mo.tube.geometry.attributes.position.array;
const n = arr.length / 3;
for (let i = 0; i < n; i++) {
const tt = th0 + (Math.PI - 2 * th0) * (i / (n - 1));
const ss = Math.sin(tt), rr = L * ss * ss;
const p = new THREE.Vector3(rr * ss * Math.cos(phi), rr * Math.cos(tt), rr * ss * Math.sin(phi)).applyMatrix4(mag.matrixWorld);
arr[i * 3] = p.x; arr[i * 3 + 1] = p.y; arr[i * 3 + 2] = p.z;
}
mo.tube.geometry.attributes.position.needsUpdate = true;
// Footprints on the surface, expressed in the spin frame (aurora shells live there)
[th0, Math.PI - th0].forEach(tf => {
const p = new THREE.Vector3(Math.sin(tf) * Math.cos(phi), Math.cos(tf), Math.sin(tf) * Math.sin(phi)).applyMatrix4(mag.matrixWorld);
spin.worldToLocal(p); p.normalize();
feet.push(p); weights.push(m.key === 'io' || m.key === 'enceladus' ? 1.0 : 0.6);
});
});
auroraMats.forEach(mat => {
for (let i = 0; i < 6; i++) {
if (feet[i]) { mat.uniforms.uFoot.value[i].copy(feet[i]); mat.uniforms.uFootW.value[i] = state.layers.moons ? weights[i] : 0; }
else mat.uniforms.uFootW.value[i] = 0;
}
});
}
function updateWind(dt) {
if (!state.layers.wind) return;
const { wpos, wcol, wvel, respawn, endX } = state.objs;
const kb = state.windK, base = state.cfg.mp;
const step = base * 0.55 * dt * Math.max(0.25, Math.min(state.speed, 3));
const n = wvel.length;
for (let i = 0; i < n; i++) {
const ix = i * 3;
let x = wpos[ix], y = wpos[ix + 1], z = wpos[ix + 2];
// local solar wind strength: the slider value, plus the CME's pressure if the cloud has reached this point
const k = kb + cmeAmt(x, Math.hypot(y, z)) * (state.cme ? state.cme.P : 0);
const mp = base * scaleOf(k);
let r = Math.hypot(x, y, z);
let c = x / r;
const rbs = shue(c, mp * BS_SCALE, BS_ALPHA);
const inSheath = r < rbs;
x -= step * (0.55 + 0.45 * k) * wvel[i] * (inSheath ? 0.5 : 1);
r = Math.hypot(x, y, z); c = x / r;
const rmp = shue(c, mp * 1.03, MP_ALPHA);
if (r < rmp) {
// small penetrations snap to the boundary; big ones (boundary expanding after a storm) ease out
const kk = rmp * 1.01 / r, f = kk < 1.05 ? 1 : Math.min(1, dt * 6);
const m = 1 + (kk - 1) * f;
x *= m; y *= m; z *= m;
if (Math.abs(y) + Math.abs(z) < 0.05 * mp) { y += (Math.random() - 0.5) * 0.2; z += (Math.random() - 0.5) * 0.2; }
}
wpos[ix] = x; wpos[ix + 1] = y; wpos[ix + 2] = z;
if (x < endX) respawn(i, false);
// denser, brighter, redder where the wind is stronger; each particle fades around its own threshold
const dens = Math.min(1, Math.max(0.15, 0.2 + 0.45 * k));
const thr = (i * 0.6180339887) % 1;
const w = Math.min(1, Math.max(0, (dens - thr) / 0.12 + 0.5));
const b = Math.min(1.6, Math.max(0.6, 0.75 + 0.25 * k)) * w;
const u = Math.min(1, Math.max(0, (k - 0.3) / 0.7)), v = Math.min(1, Math.max(0, (k - 1) / 2.5));
if (inSheath) { wcol[ix] = b; wcol[ix + 1] = b * (0.55 - 0.25 * v); wcol[ix + 2] = b * (0.25 + 0.1 * v); }
else { wcol[ix] = b; wcol[ix + 1] = b * (0.85 + 0.05 * u - 0.45 * v); wcol[ix + 2] = b * (1.0 - 0.4 * u - 0.3 * v); }
}
state.objs.wind.geometry.attributes.position.needsUpdate = true;
state.objs.wind.geometry.attributes.color.needsUpdate = true;
}
// Stand-off distance scales roughly as (dynamic pressure)^(-1/6); exaggerated a little so the change is easy to see.
function scaleOf(k) { return THREE.MathUtils.clamp(Math.pow(k, -0.22), 0.7, 1.35); }
function windScale() { return scaleOf(state.windK); }
// how far the CME front has swept past a point (0 = not reached, 1 = inside the cloud); smooth over ~1 mp
function cmeAmt(x, rho) {
const c = state.cme; if (!c) return 0;
const d = x - (c.x + rho * rho / (2 * c.R));
const w = c.W, t = Math.min(1, Math.max(0, (d + w) / (2 * w)));
return t * t * (3 - 2 * t);
}
// effective strength felt at the magnetopause nose: drives field lines, aurora and the meters
function noseK() {
const kb = state.windK; if (!state.cme) return kb;
return kb + cmeAmt(state.cfg.mp * windScale(), 0) * state.cme.P;
}
function windBoost() { return THREE.MathUtils.clamp(0.45 + 0.55 * noseK(), 0.5, 2.6); }
function applyWind() {
const o = state.objs, cfg = state.cfg, s = windScale(), k = noseK(), sk = scaleOf(k);
o.boundaries.scale.setScalar(s);
const glow = THREE.MathUtils.clamp(0.65 + 0.35 * k, 0.6, 3);
const c = state.cme;
[o.mpMesh, o.bsMesh].forEach(m => {
const u = m.material.uniforms;
u.uStrength.value = m.userData.base * glow;
u.uKb.value = state.windK;
u.uFrontX.value = c ? c.x : 1e6; u.uCR.value = c ? c.R : 1; u.uCP.value = c ? c.P : 0; u.uCW.value = c ? c.W : 1;
});
o.field.material.uniforms.uMp.value = cfg.mp * sk;
o.moons.forEach(m => { if (m.tube) m.tube.material.uniforms.uMp.value = cfg.mp * sk; });
// a stronger wind pushes the auroral oval towards the equator and widens it
const a = cfg.aurora;
const colat = a.colat * THREE.MathUtils.clamp(1 + 0.13 * (k - 1), 0.88, 1.42);
const width = a.width * THREE.MathUtils.clamp(1 + 0.3 * (k - 1), 0.8, 2.0);
o.auroraMats.forEach(m => { m.uniforms.uColat.value = colat; m.uniforms.uWidth.value = width; });
}
function launchCME(x0) {
const o = state.objs; if (!o.cme) return;
const mp = state.cfg.mp;
// P = extra pressure carried by the cloud (in units of normal solar wind); W = thickness of the front
state.cme = { x: x0 ? x0 * mp : o.spawnX * 1.25, R: o.cme.userData.R, P: 3, W: mp * 0.45, passed: 0 };
o.cme.visible = true;
}
function updateCME(dt, tsec) {
const o = state.objs, c = state.cme;
if (!c) return;
const mp = state.cfg.mp;
c.x -= mp * 0.9 * dt;
// once the front is well past the planet, the cloud thins out and the magnetosphere recovers
if (c.x < -mp * 1.2) { c.passed += dt; c.P = 3 * Math.exp(-c.passed / 3.5); }
if (o.cme.visible) {
o.cme.position.set(c.x + o.cme.userData.R, 0, 0);
const u = o.cme.material.uniforms;
u.uTime.value = tsec;
// fade in after launch, fade out once it has swept past the planet
u.uFade.value = THREE.MathUtils.clamp((o.spawnX * 1.25 - c.x) / (mp * 0.6), 0, 1) * THREE.MathUtils.clamp((c.x - o.endX) / (mp * 2.5), 0, 1);
if (c.x < o.endX) o.cme.visible = false;
}
if (c.P < 0.01) { state.cme = null; o.cme.visible = false; }
}
function applyLayers() {
const o = state.objs, L = state.layers;
if (!o.field) return;
o.field.visible = L.field;
o.wind.visible = L.wind;
o.boundaries.visible = L.mp;
o.auroraGroup.visible = L.aurora;
if (o.torus) o.torus.userData.pivot.visible = L.torus;
o.moons.forEach(m => { m.holder.visible = L.moons; if (m.tube) m.tube.visible = L.moons && L.field; });
labelRenderer.domElement.style.display = L.labels ? '' : 'none';
// CSS2D labels only honour their own visibility flag, so mirror the parent's layer state.
const showIf = (obj, v) => obj.traverse(x => { if (x.isCSS2DObject) x.visible = v; });
showIf(o.boundaries, L.mp);
showIf(o.wind, L.wind);
if (o.torus) showIf(o.torus.userData.pivot, L.torus);
o.moons.forEach(m => showIf(m.holder, L.moons));
}
function refreshLabels() {
if (!state.root) return;
state.root.traverse(o => { if (o.isCSS2DObject) o.element.textContent = t(o.userData.labelKey); });
}
/* ----------------------------------------------------------- camera */
function presetFor(view) {
const mp = state.cfg.mp;
if (view === 'overview') return { pos: new THREE.Vector3(mp * 0.7, mp * 1.1, mp * 2.9), target: new THREE.Vector3(-mp * 0.3, 0, 0) };
if (view === 'mid') return { pos: new THREE.Vector3(3.5, 4.2, 9.5), target: new THREE.Vector3(0, 0, 0) };
if (view === 'close') return { pos: new THREE.Vector3(2.6, 1.3, 4.6), target: new THREE.Vector3(0, 0, 0) };
const { spin } = state.objs;
const pole = (view === 'south' ? state.objs.south : state.objs.north).clone();
spin.updateWorldMatrix(true, false);
pole.applyMatrix3(new THREE.Matrix3().setFromMatrix4(spin.matrixWorld)).normalize();
// look at the pole from above, slightly from the night side so the oval stands out
const side = new THREE.Vector3(-1, 0, 0.35).normalize();
const pos = pole.clone().multiplyScalar(3.6).add(side.multiplyScalar(1.1));
return { pos, target: pole.clone().multiplyScalar(0.25) };
}
function view(name, instant = false) {
state.follow = null;
controls.minDistance = 1.5;
const p = presetFor(name);
state.auroraBoost = (name === 'aurora' || name === 'south') ? 1.25 : 1;
if (instant) { camera.position.copy(p.pos); controls.target.copy(p.target); controls.update(); return; }
state.tween = { from: camera.position.clone(), fromT: controls.target.clone(), to: p.pos, toT: p.target, t: 0, dur: 1.8 };
}
/* --------------------------------------------------- moons: focus/pick */
const followPos = new THREE.Vector3();
function moonEntry(key) { return state.objs.moons?.find(m => m.cfg.key === key); }
function moonOffset(mo) {
// look at the moon from its sunlit side, a little above the orbit plane, with the planet in view
mo.mesh.getWorldPosition(followPos);
const out = followPos.clone().normalize();
const d = Math.max(mo.cfg.size * 15, 0.85);
return out.multiplyScalar(0.55).add(new THREE.Vector3(0.45, 0.4, 0.5)).normalize().multiplyScalar(d);
}
function focusMoon(key, instant = false) {
const mo = moonEntry(key);
if (!mo) return false;
if (!state.layers.moons) { state.layers.moons = true; applyLayers(); }
state.follow = mo;
controls.minDistance = 0.15;
state.auroraBoost = 1;
if (instant) {
mo.mesh.getWorldPosition(followPos); const tgt = followPos.clone();
camera.position.copy(tgt).add(moonOffset(mo)); controls.target.copy(tgt); mo.last = tgt.clone(); controls.update(); return true;
}
state.tween = { from: camera.position.clone(), fromT: controls.target.clone(), t: 0, dur: 2.0,
dyn: () => { mo.mesh.getWorldPosition(followPos); const tgt = followPos.clone(); return { toT: tgt, to: tgt.clone().add(moonOffset(mo)) }; } };
return true;
}
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let downAt = null;
renderer.domElement.addEventListener('pointerdown', e => { downAt = [e.clientX, e.clientY]; });
renderer.domElement.addEventListener('pointerup', e => {
if (!downAt || Math.hypot(e.clientX - downAt[0], e.clientY - downAt[1]) > 6 || !state.root) return;
const r = renderer.domElement.getBoundingClientRect();
pointer.set(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1);
raycaster.setFromCamera(pointer, camera);
const targets = [state.objs.planet];
if (state.layers.moons) state.objs.moons.forEach(m => targets.push(m.mesh));
const hit = raycaster.intersectObjects(targets, true).find(h => h.object.userData.pick);
if (hit) onSelect(hit.object.userData.pick);
});
renderer.domElement.addEventListener('pointermove', e => {
if (e.buttons || !state.root) return;
const r = renderer.domElement.getBoundingClientRect();
pointer.set(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1);
raycaster.setFromCamera(pointer, camera);
const targets = state.layers.moons ? state.objs.moons.map(m => m.mesh) : [];
renderer.domElement.style.cursor = raycaster.intersectObjects(targets, true).some(h => h.object.userData.pick) ? 'pointer' : '';
});
/* ------------------------------------------------------------- loop */
function resize() {
const w = container.clientWidth, h = container.clientHeight;
if (!w || !h) return;
renderer.setSize(w, h, false);
labelRenderer.setSize(w, h);
composer.setSize(w, h);
bloom.setSize(w / 2, h / 2);
camera.aspect = w / h;
camera.updateProjectionMatrix();
}
new ResizeObserver(resize).observe(container);
let visible = true;
new IntersectionObserver(es => { visible = es[0].isIntersecting; }).observe(container);
const clock = new THREE.Clock();
function frame() {
requestAnimationFrame(frame);
const dt = Math.min(clock.getDelta(), 0.05);
if (!visible || !state.root) return;
const cfg = state.cfg, o = state.objs;
// simulated hours advance: one Jupiter day ≈ 24 s at speed 1
const dtHours = dt * 0.42 * state.speed;
state.time += dtHours;
o.spin.rotation.y = (2 * Math.PI / cfg.period) * state.time;
updateCME(dt, clock.elapsedTime);
state.windK += (state.wind - state.windK) * Math.min(1, dt * 2.5);
applyWind();
const tsec = clock.elapsedTime;
o.field.material.uniforms.uTime.value = tsec;
o.auroraMats.forEach(m => { m.uniforms.uTime.value = tsec; m.uniforms.uBoost.value += (state.auroraBoost * windBoost() - m.uniforms.uBoost.value) * 0.05; });
if (o.clouds) o.clouds.rotation.y += dt * 0.004 * state.speed;
o.mpMesh.material.uniforms.uTime.value = tsec;
o.bsMesh.material.uniforms.uTime.value = tsec;
if (o.torus) o.torus.material.uniforms.uTime.value = tsec;
o.moons.forEach(m => { if (m.tube) m.tube.material.uniforms.uTime.value = tsec; });
updateMoons(dt, tsec);
// feature labels around a moon appear only while the camera is following it
o.moons.forEach(mo => mo.fxLabels.forEach(l => {
l.visible = state.follow === mo && state.layers.labels && state.layers.moons && (!l.userData.aurora || state.layers.aurora) && (!l.userData.cond || l.userData.cond());
}));
updateWind(dt);
if (state.follow && !state.tween) {
// keep the camera locked to a moving moon
const prev = state.follow.last || followPos.clone();
state.follow.mesh.getWorldPosition(followPos);
const delta = followPos.clone().sub(prev);
camera.position.add(delta); controls.target.add(delta);
state.follow.last = followPos.clone();
}
if (state.tween) {
const tw = state.tween;
if (tw.dyn) { const d = tw.dyn(); tw.to = d.to; tw.toT = d.toT; }
tw.t = Math.min(1, tw.t + dt / tw.dur);
const e = tw.t < 0.5 ? 4 * tw.t ** 3 : 1 - Math.pow(-2 * tw.t + 2, 3) / 2;
camera.position.lerpVectors(tw.from, tw.to, e);
controls.target.lerpVectors(tw.fromT, tw.toT, e);
if (tw.t >= 1) { state.tween = null; if (state.follow) { state.follow.mesh.getWorldPosition(followPos); state.follow.last = followPos.clone(); } }
}
controls.update();
composer.render();
labelRenderer.render(scene, camera);
}
resize();
frame();
return {
setPlanet(name, { keepView = false, instant = false } = {}) { state.follow = null; controls.minDistance = 1.5; build(name); if (!keepView) view('overview', instant); },
focusMoon,
setLayer(k, v) { state.layers[k] = v; applyLayers(); },
setLayers(obj) { Object.assign(state.layers, obj); applyLayers(); },
getLayers() { return { ...state.layers }; },
setSpeed(s) { state.speed = s; },
// Earth's Moon: is it inside Earth's magnetotail right now?
moonInTail(key) { return !!moonEntry(key)?.fx?.inTail; },
// move a moon along its orbit to the night side (directly behind the planet)
moonToNight(key) {
const mo = moonEntry(key); if (!mo) return;
const m = mo.cfg, w = 2 * Math.PI / (m.period * 24);
m.phase = Math.PI - w * state.time;
mo.fx?.snapTail?.();
},
launchCME,
windInfo() { const k = noseK(); return { k, boost: windBoost(), scale: scaleOf(k), cme: !!state.cme, kick: Math.max(0, (k - state.windK) / 3) }; },
setWind(k, instant = false) { state.wind = THREE.MathUtils.clamp(k, 0.2, 5); if (instant) state.windK = state.wind; },
view,
refreshLabels,
get planet() { return state.name; },
deformMagJS
};
}
// 3D magnetosphere scene: planet, dipole field lines, magnetopause, bow shock,
// solar wind, plasma torus, moons with flux tubes, and layered aurora shells.
// The Sun is always in the +X direction. Distances are compressed (not to scale).
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { CSS2DRenderer, CSS2DObject } from 'three/addons/renderers/CSS2DRenderer.js';
import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';
import { createMoonFX } from './moonfx.js';
THREE.ColorManagement.enabled = false;
const DEG = Math.PI / 180;
const SUN_DIR = new THREE.Vector3(1, 0, 0);
const MP_ALPHA = 0.6; // magnetopause flaring
const BS_SCALE = 1.35; // bow-shock stand-off relative to magnetopause
const BS_ALPHA = 0.8;
// mp = visual magnetopause stand-off distance in planet radii (compressed).
// Moon fields: dist = visual orbit radius (compressed), realDist = real orbit radius in planet radii,
// period = orbital period in days (negative = retrograde), dia = diameter in km,
// foot = draw the flux tube and auroral footprint.
export const PLANET_CFG = {
earth: {
style: 0, tex: 'earth', radiusKm: 6371, obliquity: 23.4, dipoleTilt: 11, offset: [0, 0, 0], period: 24, mp: 4.5,
atmo: [0.35, 0.6, 1.0], field: [0.45, 0.8, 1.0], disc: 0,
aurora: { colat: 20, width: 2.6, c1: [0.15, 1.0, 0.45], c2: [1.0, 0.2, 0.35], patchy: 0.15, intensity: 1.5, height: 0.07 },
rings: null, torus: null,
moons: [
{ key: 'moon', dist: 6.8, realDist: 60.3, period: 27.32, dia: 3474, incl: 5.1 }
]
},
jupiter: {
style: 1, tex: 'jupiter', radiusKm: 69911, obliquity: 3.1, dipoleTilt: 9.6, offset: [0, 0, 0], period: 9.93, mp: 10,
atmo: [0.9, 0.8, 0.65], field: [0.55, 0.75, 1.0], disc: 0.55,
aurora: { colat: 16, width: 2.0, c1: [0.75, 0.45, 1.0], c2: [1.0, 0.35, 0.85], patchy: 0.05, intensity: 1.9, height: 0.09 },
rings: null,
torus: { r: 3.2, tube: 0.32, color: [1.0, 0.45, 0.25], label: 'lbl.torusJ' },
moons: [
{ key: 'io', dist: 3.2, realDist: 5.9, period: 1.769, dia: 3643, foot: true },
{ key: 'europa', dist: 4.1, realDist: 9.4, period: 3.551, dia: 3122, foot: true },
{ key: 'ganymede', dist: 5.2, realDist: 15.0, period: 7.155, dia: 5268, foot: true },
{ key: 'callisto', dist: 6.6, realDist: 26.3, period: 16.69, dia: 4821 }
]
},
saturn: {
style: 2, tex: 'saturn', radiusKm: 58232, obliquity: 26.7, dipoleTilt: 0.0, offset: [0, 0.04, 0], period: 10.6, mp: 7.5,
atmo: [0.95, 0.85, 0.6], field: [0.5, 0.8, 1.0], disc: 0.25,
aurora: { colat: 15, width: 2.0, c1: [0.45, 0.6, 1.0], c2: [0.85, 0.4, 1.0], patchy: 0.35, intensity: 1.6, height: 0.08 },
rings: { inner: 1.24, outer: 2.27, style: 0 },
torus: { r: 2.9, tube: 0.42, color: [0.35, 0.6, 1.0], label: 'lbl.torusS' },
moons: [
{ key: 'mimas', dist: 2.5, realDist: 3.08, period: 0.942, dia: 396 },
{ key: 'enceladus', dist: 2.9, realDist: 3.95, period: 1.370, dia: 504, foot: true },
{ key: 'tethys', dist: 3.35, realDist: 4.89, period: 1.888, dia: 1062 },
{ key: 'dione', dist: 3.85, realDist: 6.26, period: 2.737, dia: 1123 },
{ key: 'rhea', dist: 4.55, realDist: 8.74, period: 4.518, dia: 1527 },
{ key: 'titan', dist: 6.0, realDist: 20.3, period: 15.945, dia: 5149 },
{ key: 'iapetus', dist: 8.8, realDist: 59.1, period: 79.32, dia: 1469, incl: 15 }
]
},
uranus: {
style: 3, tex: 'uranus', radiusKm: 25362, obliquity: 97.8, dipoleTilt: 59, offset: [0.05, -0.3, 0.0], period: 17.24, mp: 6.5,
atmo: [0.6, 0.9, 1.0], field: [0.45, 0.95, 0.9], disc: 0,
aurora: { colat: 18, width: 3.0, c1: [0.4, 1.0, 0.9], c2: [1.0, 0.45, 0.8], patchy: 0.8, intensity: 1.6, height: 0.07 },
rings: { inner: 1.6, outer: 2.0, style: 1 },
torus: null,
moons: [
{ key: 'miranda', dist: 2.4, realDist: 5.08, period: 1.413, dia: 472, incl: 4.3 },
{ key: 'ariel', dist: 2.9, realDist: 7.47, period: 2.520, dia: 1158 },
{ key: 'umbriel', dist: 3.5, realDist: 10.4, period: 4.144, dia: 1169 },
{ key: 'titania', dist: 4.4, realDist: 17.1, period: 8.706, dia: 1577 },
{ key: 'oberon', dist: 5.4, realDist: 22.8, period: 13.46, dia: 1523 }
]
},
neptune: {
style: 4, tex: 'neptune', radiusKm: 24622, obliquity: 28.3, dipoleTilt: 46.9, offset: [0.17, -0.5, 0.1], period: 16.1, mp: 6.5,
atmo: [0.35, 0.55, 1.0], field: [0.45, 0.75, 1.0], disc: 0,
aurora: { colat: 18, width: 3.0, c1: [0.4, 0.85, 1.0], c2: [0.7, 0.5, 1.0], patchy: 0.85, intensity: 1.5, height: 0.07 },
rings: { inner: 1.7, outer: 2.55, style: 2 },
torus: null,
moons: [
{ key: 'triton', dist: 4.2, realDist: 14.4, period: -5.877, dia: 2707, incl: 23 }
]
}
};
// Visual moon radius in planet radii: square-root scaling keeps small moons visible.
export function moonSize(planetCfg, m) {
return Math.max(0.035, 0.5 * Math.sqrt((m.dia / 2) / planetCfg.radiusKm));
}
// Featured moons for the page section (order matters).
export const FEATURED_MOONS = ['io', 'europa', 'ganymede', 'callisto', 'enceladus', 'titan', 'ariel', 'triton'];
export function moonHost(key) {
return Object.keys(PLANET_CFG).find(p => PLANET_CFG[p].moons.some(m => m.key === key));