A spy satellite simulator in your browser, except the data is real. Live open source spatial intelligence on a photorealistic 3D globe.
JavaScript 3d-globecesiumflight-trackinggeospatialgeospatial-intelligencegisosintphotogrammetrysatellite-trackingspatial-intelligencewebglworldview
fix(sky): preserve dark model lighting and address review
German Khokhlov27d4c0ba9c83
diff --cc docs/CURRENT-STATE.mdindex 9cafb15bf,eacfa1147..d3d037a74--- a/docs/CURRENT-STATE.md+++ b/docs/CURRENT-STATE.md@@@ -1137,6 -1179,6 +1179,24 @@@ snapshots, lifecycle actions and row delisteners and row subscriptions; obsolete completions do not repaint old rows.The clear control presents busy state while its existing action owns the transaction.++## Sky background++++`src/sky/starrySky.js` fills Cesium's `Scene#skyBox` slot with 9,096 Yale++Bright Star Catalogue stars and a soft ESO/S. Brunier Milky Way. Both layers++rotate from ICRF/J2000 into the Earth-fixed frame at the scene clock, with++a TEME fallback while Cesium's IAU 2006 tables load. Bundled assets and++their provenance are documented in `src/data/local_data/sky/README.md`.++++Anime fades out the Milky Way with its style intensity to avoid cel-shaded++bands; the catalogue stars remain. A separate black 1×1 cube map preserves++model environment lighting independently of the visible sky. The adapter++is validated against Cesium 1.138.0 and must be revalidated on upgrades.++++`scripts/qa-anime-sky.mjs` checks asset readiness, visible Normal sky and++Anime band coverage against a Vite dev server.++`scripts/qa-sky-model-lighting.mjs` compares a lit `airplane.glb` against++black and white environment maps in isolated scenes.++## Model atmosphere on Apple MetalCesium's per-vertex model atmosphere is kept out of the pipeline on devicesdiff --cc scripts/format-scope.jsonindex 6d93c9e41,83e961d8b..fc913b277--- a/scripts/format-scope.json+++ b/scripts/format-scope.json@@@ -1070,12 -1063,6 +1063,14 @@@"scripts/assemble-changelog.mjs","src/tooling/changelogFragments.test.mjs","src/data/gbfsProxyRateLimit.test.mjs",+ "src/data/routeSegment.test.mjs",- "src/terrainHeightsBounds.test.mjs"+ "src/terrainHeightsBounds.test.mjs",+ "scripts/build-bright-stars.mjs",+ "scripts/build-milky-way.mjs",+ "src/sky/stars.test.mjs",+ "src/sky/starrySky.test.mjs",+ "src/tooling/skyAssets.test.mjs",+ "src/tooling/skyAssets.paintOut.test.mjs",- "scripts/qa-anime-sky.mjs"++ "scripts/qa-anime-sky.mjs",++ "scripts/qa-sky-model-lighting.mjs"]diff --cc scripts/qa-anime-sky.mjsindex b3ac1cf2d,000000000..a0a0c9935mode 100644,000000..100644--- a/scripts/qa-anime-sky.mjs+++ b/scripts/qa-anime-sky.mjs@@@ -1,121 -1,0 +1,160 @@@+#!/usr/bin/env node+/**+ * qa-anime-sky — the anime style must leave the sky without bands.+ *+ * Anime's luminance bands turn the faint Milky Way into blotches, so+ * src/ui/visualEffects.js fades the glow out with the style. Headless against- * a Vite dev server, the real anime style looks away from the Earth at the- * Galactic Centre: at most 0.5 % of the sky (the stars) may reach the first- * band.++ * a Vite dev server, both sky assets must be ready. Normal must show the++ * Galactic Centre glow (at least 2 % of pixels at luma >= 10/255), then++ * Anime must retain stars while at most 0.5 % reaches the first cel band.++ * The Normal baseline measured 43 % in headless Chromium at 1000×700;++ * the 2 % floor leaves room for GPU differences while rejecting a black sky.+ *+ * Usage: node scripts/qa-anime-sky.mjs [--url http://localhost:4333/]+ * Exit: 0 pass, 1 fail, 2 the anime style was not reached.+ */+import puppeteer from 'puppeteer';++const i = process.argv.indexOf('--url');+const URL_ =+ i > 0 && process.argv[i + 1] ? process.argv[i + 1] : 'http://localhost:4333/';++const browser = await puppeteer.launch({+ headless: 'new',+ args: ['--no-sandbox', '--ignore-gpu-blocklist'],+});+try {+ const page = await browser.newPage();++ await page.setRequestInterception(true);++ page.on('request', (request) => {++ const host = new URL(request.url()).hostname;++ if (host.endsWith('halfpixel.ai') || host.includes('worldfx'))++ request.abort();++ else request.continue();++ });+ page.on('pageerror', (e) => console.log('PAGEERR', String(e).slice(0, 300)));+ await page.setViewport({ width: 1000, height: 700 });+ await page.evaluateOnNewDocument(() =>+ localStorage.setItem('gev:first-run-mission:v1', 'suppressed'),+ );+ await page.goto(URL_, { waitUntil: 'domcontentloaded' });+ await page.waitForFunction(() => window.__godsEyeView?.viewer?.scene, {+ timeout: 120000,+ });- await new Promise((r) => setTimeout(r, 12000));++ await page.waitForFunction(++ () => {++ const sky = window.__godsEyeView.viewer.scene.skyBox;++ return (++ sky?._milkyWayCubeMap &&++ sky?._starCommand &&++ document.getElementById('loading-screen')?.classList.contains('hidden')++ );++ },++ { timeout: 60000 },++ );+ const r = await page.evaluate(async () => {+ const entry = performance+ .getEntriesByType('resource')+ .map((e) => e.name)+ .find((n) => /\.vite\/deps\/cesium\.js/.test(n));+ if (!entry)+ throw new Error(+ 'run against the Vite dev server (needs .vite/deps/cesium.js)',+ );+ const C = await import(entry),+ g = window.__godsEyeView,+ v = g.viewer,+ s = v.scene;- g.styleManager.setStyle('anime', { userInitiated: true });++ g.styleManager.setStyle('normal', { userInitiated: true });+ const t = v.clock.currentTime;+ await C.Transforms.preloadIcrfFixed(+ new C.TimeInterval({+ start: C.JulianDate.addDays(t, -1, new C.JulianDate()),+ stop: C.JulianDate.addDays(t, 1, new C.JulianDate()),+ }),+ );+ const m = C.Transforms.computeIcrfToFixedMatrix(t);+ const ra = C.Math.toRadians(266.4),+ dec = C.Math.toRadians(-29);+ const look = C.Matrix3.multiplyByVector(+ m,+ new C.Cartesian3(+ Math.cos(dec) * Math.cos(ra),+ Math.cos(dec) * Math.sin(ra),+ Math.sin(dec),+ ),+ new C.Cartesian3(),+ );+ const north = C.Matrix3.multiplyByVector(+ m,+ C.Cartesian3.UNIT_Z,+ new C.Cartesian3(),+ );+ const right = C.Cartesian3.normalize(+ C.Cartesian3.cross(look, north, new C.Cartesian3()),+ new C.Cartesian3(),+ );+ s.camera.cancelFlight();++ s.tweens.removeAll();+ s.camera.setView({+ destination: C.Cartesian3.multiplyByScalar(look, 3e7, new C.Cartesian3()),+ orientation: {+ direction: look,+ up: C.Cartesian3.cross(right, look, new C.Cartesian3()),+ },+ });- await new Promise((res) => setTimeout(res, 2500));- s.requestRender();- s.render();+ const gl = s.context._gl,+ w = gl.drawingBufferWidth,+ h = gl.drawingBufferHeight,+ px = new Uint8Array(w * h * 4);- gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, px);- let banded = 0;- for (let i = 0; i < px.length; i += 4)- if (0.299 * px[i] + 0.587 * px[i + 1] + 0.114 * px[i + 2] >= 51) banded++;++ const measure = async () => {++ await new Promise((res) => setTimeout(res, 2500));++ s.requestRender();++ s.render();++ gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, px);++ let banded = 0;++ let visible = 0;++ for (let i = 0; i < px.length; i += 4) {++ const luma = 0.299 * px[i] + 0.587 * px[i + 1] + 0.114 * px[i + 2];++ if (luma >= 51) banded++;++ if (luma >= 10) visible++;++ }++ return { banded, visible };++ };++ const normal = await measure();++ g.styleManager.setStyle('anime', { userInitiated: true });++ const anime = await measure();+ let animeOn = false;+ for (let i = 0; i < s.postProcessStages.length; i++) {+ const stage = s.postProcessStages.get(i);+ if (stage.name === 'godsEyeView_anime')+ animeOn = stage.enabled && stage.uniforms.intensity > 0.99;+ }+ return {+ total: px.length / 4,- banded,++ normal,++ ...anime,++ assetsReady: Boolean(s.skyBox._milkyWayCubeMap && s.skyBox._starCommand),+ visibility: s.skyBox.milkyWayVisibility,+ animeOn,+ };+ });- const tag = !r.animeOn- ? 'UNREACHED'- : r.banded <= 0.005 * r.total- ? 'PASS'- : 'FAIL';++ const tag =++ !r.animeOn || !r.assetsReady++ ? 'UNREACHED'++ : r.normal.visible >= 0.02 * r.total &&++ r.banded > 0 &&++ r.banded <= 0.005 * r.total &&++ r.visibility === 0++ ? 'PASS'++ : 'FAIL';+ console.log(+ `${tag}: ${r.banded} of ${r.total} sky pixels at or above the first cel band (luma >= 0.2)\n ${JSON.stringify(r)}`,+ );+ process.exitCode = tag === 'PASS' ? 0 : tag === 'FAIL' ? 1 : 2;++} catch (error) {++ console.error(`UNREACHED: ${error.message}`);++ process.exitCode = 2;+} finally {+ await browser.close();+}diff --cc scripts/qa-sky-model-lighting.mjsindex 000000000,000000000..2f401506bnew file mode 100644--- /dev/null+++ b/scripts/qa-sky-model-lighting.mjs@@@ -1,0 -1,0 +1,147 @@@++#!/usr/bin/env node++/**++ * Lit airplane regression: StarrySky must match a black environment baseline.++ * A white environment is a positive control: it must visibly brighten the++ * same model. Each case uses a fresh scene and dynamic environment map.++ * Usage: node scripts/qa-sky-model-lighting.mjs [--url http://localhost:4333/]++ */++import assert from 'node:assert/strict';++import puppeteer from 'puppeteer';++++const i = process.argv.indexOf('--url');++const base = i > 0 ? process.argv[i + 1] : 'http://localhost:4333/';++const url = new URL('/__qa_sky_model__', base);++const browser = await puppeteer.launch({++ headless: true,++ args: ['--no-sandbox', '--ignore-gpu-blocklist'],++});++try {++ const page = await browser.newPage();++ page.on('pageerror', (error) => console.log('PAGEERR', error.message));++ await page.setRequestInterception(true);++ page.on('request', (request) => {++ if (request.url() === url.href)++ request.respond({++ contentType: 'text/html',++ body: '<!doctype html><html><body></body></html>',++ });++ else if (new URL(request.url()).origin !== url.origin) request.abort();++ else request.continue();++ });++ await page.goto(url.href);++ const results = await page.evaluate(async () => {++ window.CESIUM_BASE_URL = '/cesium/';++ // Use StarrySky's exact Vite dependency URL, including its version query.++ const source = await fetch('/src/sky/starrySky.js').then((r) => r.text());++ const cesiumUrl = source.match(++ /from ["']([^"']*\/cesium\.js[^"']*)["']/,++ )?.[1];++ if (!cesiumUrl) throw new Error('run against the Vite dev server');++ const C = await import(cesiumUrl);++ const { StarrySky } = await import('/src/sky/starrySky.js');++ const time = C.JulianDate.fromIso8601('2026-10-19T00:00:00Z');++ const results = {};++ for (const kind of ['black', 'starry', 'white']) {++ const canvas = document.createElement('canvas');++ canvas.width = 400;++ canvas.height = 300;++ document.body.append(canvas);++ const scene = new C.Scene({ canvas });++ scene.rethrowRenderErrors = true;++ let cubeMap;++ try {++ scene.backgroundColor = C.Color.BLACK;++ scene.light = new C.DirectionalLight({++ direction: new C.Cartesian3(1, 0, 0),++ intensity: 0.2,++ });++ if (kind === 'starry') {++ scene.skyBox = new StarrySky({ requestRender() {} });++ scene.skyBox._loading = true; // visible sky is outside this probe++ } else {++ const value = kind === 'white' ? 255 : 0;++ const face = {++ width: 1,++ height: 1,++ arrayBufferView: new Uint8Array([value, value, value, 255]),++ };++ cubeMap = new C.CubeMap({++ context: scene.context,++ source: Object.fromEntries(++ [...C.CubeMap.faceNames()].map((name) => [name, face]),++ ),++ });++ scene.skyBox = { _cubeMap: cubeMap, update() {}, destroy() {} };++ }++ const position = C.Cartesian3.fromDegrees(0, 0, 10000);++ const model = await C.Model.fromGltfAsync({++ url: '/models/airplane.glb',++ modelMatrix: C.Transforms.eastNorthUpToFixedFrame(position),++ });++ scene.primitives.add(model);++ scene.camera.lookAt(position, new C.HeadingPitchRange(0.4, -0.5, 45));++ let framed = false;++ for (let frame = 0; frame < 240; frame++) {++ scene.initializeFrame();++ scene.render(time);++ if (model.ready && !framed) {++ scene.camera.viewBoundingSphere(++ model.boundingSphere,++ new C.HeadingPitchRange(++ 0.4,++ -0.5,++ model.boundingSphere.radius * 3,++ ),++ );++ framed = true;++ }++ await new Promise(requestAnimationFrame);++ }++ if (!model.ready || !model.environmentMapManager.radianceCubeMap)++ throw new Error(`${kind}: model or dynamic lighting did not load`);++ scene.initializeFrame();++ scene.render(time);++ const gl = scene.context._gl;++ const px = new Uint8Array(canvas.width * canvas.height * 4);++ gl.readPixels(++ 0,++ 0,++ canvas.width,++ canvas.height,++ gl.RGBA,++ gl.UNSIGNED_BYTE,++ px,++ );++ let total = 0;++ let visible = 0;++ for (let p = 0; p < px.length; p += 4) {++ const luma = 0.299 * px[p] + 0.587 * px[p + 1] + 0.114 * px[p + 2];++ total += luma;++ if (luma > 1) visible++;++ }++ results[kind] = { total, visible };++ } finally {++ scene.destroy();++ cubeMap?.destroy();++ canvas.remove();++ }++ }++ return results;++ });++ console.log(JSON.stringify(results));++ assert.ok(results.black.visible > 100, 'the lit model must be visible');++ assert.ok(++ Math.abs(results.starry.total - results.black.total) <=++ results.black.total * 0.01,++ 'StarrySky must match black environment lighting within 1%',++ );++ assert.ok(++ results.white.total > results.black.total * 1.03,++ 'white environment control must brighten the model by at least 3%',++ );++ console.log(++ 'PASS: lit airplane matches black sky; white control is brighter',++ );++} finally {++ await browser.close();++}diff --cc src/sky/starrySky.jsindex 8cd7f5d58,000000000..02e5c7ee3mode 100644,000000..100644--- a/src/sky/starrySky.js+++ b/src/sky/starrySky.js@@@ -1,431 -1,0 +1,451 @@@+import * as Cesium from 'cesium';+import { loadBundledJson } from '../data/bundledJson.js';+import { governorRequestRender } from '../renderGovernor.js';+import { buildStarVertices, STAR_VERTEX_FLOATS } from './stars.js';++/**+ * Space background in the `Scene#skyBox` slot: catalogue stars as point+ * sprites over a soft Milky Way cube map, both turned by one ICRF→fixed+ * rotation at the scene clock (TEME until Cesium's tables load). Scene runs+ * the command from `update()` first in the environment pass, so the sky+ * stays behind everything without depth. Revalidate on engine upgrades.+ */+export const STARRY_SKY_CESIUM_VERSION = '1.138.0';++/** Brightness of the Milky Way glow; the stars carry the sky. */+export const MILKY_WAY_INTENSITY = 0.4;+/** Clock change, in seconds, below which the sky rotation is reused. */+export const SKY_ROTATION_EPSILON_SECONDS = 1;++const STAR_PACK_URL = new URL(+ '../data/local_data/sky/bright_stars.json',+ import.meta.url,+);+const MILKY_WAY_FACE_URLS = Object.freeze({+ positiveX: new URL(+ '../data/local_data/sky/milkyway_px.webp',+ import.meta.url,+ ),+ negativeX: new URL(+ '../data/local_data/sky/milkyway_nx.webp',+ import.meta.url,+ ),+ positiveY: new URL(+ '../data/local_data/sky/milkyway_py.webp',+ import.meta.url,+ ),+ negativeY: new URL(+ '../data/local_data/sky/milkyway_ny.webp',+ import.meta.url,+ ),+ positiveZ: new URL(+ '../data/local_data/sky/milkyway_pz.webp',+ import.meta.url,+ ),+ negativeZ: new URL(+ '../data/local_data/sky/milkyway_nz.webp',+ import.meta.url,+ ),+});++// Directions, not points: w = 0 drops the camera translation, and z just+// under w keeps every fragment at the far plane, inside any frustum.+const SKY_DIRECTION_GLSL = `+uniform mat3 u_icrfToFixed;+vec4 skyClipPosition(vec3 icrfDirection)+{+ vec3 eye = czm_viewRotation * (u_icrfToFixed * icrfDirection);+ vec4 clip = czm_projection * vec4(eye, 0.0);+ clip.z = clip.w * 0.99999;+ return clip;+}+`;++const MILKY_WAY_VS = `${SKY_DIRECTION_GLSL}+in vec3 position;+out vec3 v_direction;+void main()+{+ gl_Position = skyClipPosition(position);+ v_direction = position;+}+`;++const MILKY_WAY_FS = `+uniform samplerCube u_milkyWay;+uniform float u_intensity;+in vec3 v_direction;+void main()+{+ vec3 color = czm_textureCube(u_milkyWay, normalize(v_direction)).rgb * u_intensity;+ // Interleaved-gradient dither: the dim glow spans only a few 8-bit steps.+ float noise = fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715))));+ color = max(color + (noise - 0.5) / 255.0, 0.0);+ out_FragColor = vec4(czm_gammaCorrect(color), 1.0);+}+`;++const STAR_VS = `${SKY_DIRECTION_GLSL}+in vec3 position;+in float sigma;+in vec4 color;+out vec4 v_color;+out float v_sigma;+out float v_radius;+void main()+{+ gl_Position = skyClipPosition(position);+ // σ is in CSS pixels; the sprite holds ±3σ plus a pixel of margin.+ v_sigma = sigma * czm_pixelRatio;+ v_radius = ceil(3.0 * v_sigma) + 1.0;+ gl_PointSize = 2.0 * v_radius;+ v_color = color;+}+`;++const STAR_FS = `+in vec4 v_color;+in float v_sigma;+in float v_radius;+void main()+{+ vec2 offset = (gl_PointCoord - 0.5) * (2.0 * v_radius);+ float alpha = v_color.a *+ exp(-0.5 * dot(offset, offset) / (v_sigma * v_sigma));+ if (alpha < 1.0 / 512.0) discard;+ out_FragColor = vec4(czm_gammaCorrect(v_color.rgb) * alpha, alpha);+}+`;++/** Pick the ICRF→fixed rotation for `time`, or TEME while tables load. */+export function computeSkyRotation(time, result) {+ const { Transforms } = Cesium;+ const icrf = Transforms.computeIcrfToFixedMatrix(time, result);+ if (icrf) return { matrix: icrf, precise: true };+ return {+ matrix: Transforms.computeTemeToPseudoFixedMatrix(time, result),+ precise: false,+ };+}++/** Whether a cached rotation at `cachedTime` still serves `time`. */+export function isSkyRotationCurrent(cachedTime, time) {+ return (+ cachedTime !== undefined &&+ Math.abs(Cesium.JulianDate.secondsDifference(time, cachedTime)) <+ SKY_ROTATION_EPSILON_SECONDS+ );+}++export class StarrySky {+ /**+ * @param {object} [options]+ * @param {() => void} [options.requestRender] renders one frame when an+ * asset or the precise rotation arrives; the idle governor by default.+ */+ constructor({+ requestRender = () => governorRequestRender('sky-assets'),+ } = {}) {+ /** Matches `SkyBox#show`. */+ this.show = true;+ this.milkyWayIntensity = MILKY_WAY_INTENSITY;+ /** 0..1 multiplier a style sets to hide the glow (see visualEffects.js). */+ this.milkyWayVisibility = 1;+ this._requestRender = requestRender;+ this._rotation = Cesium.Matrix3.clone(Cesium.Matrix3.IDENTITY);+ this._rotationTime = undefined;+ this._rotationPrecise = false;+ this._icrfRequest = undefined;+ this._icrfUnavailable = false;+ this._icrfMissing = undefined;+ this._loading = false;+ this._starData = undefined;+ this._faceImages = undefined;- // Not `_cubeMap`: Scene reads `skyBox._cubeMap` as the environment map- // that lights models, in the TEME, flipY layout of its own sky box. This- // ICRF map would light them rotated, so models keep Cesium's default.++ // Scene reads `_cubeMap` for model lighting. Keep it dark as on main;++ // Cesium's fallback is white, and the ICRF glow is only a background.++ this._cubeMap = undefined;+ this._milkyWayCubeMap = undefined;+ this._milkyWayCommand = undefined;+ this._milkyWayAttributes = undefined;+ this._starCommand = undefined;+ this._useHdr = undefined;+ this._destroyed = false;+ const uniforms = {+ u_icrfToFixed: () => this._rotation,+ };+ this._milkyWayUniforms = {+ ...uniforms,+ u_milkyWay: () => this._milkyWayCubeMap,+ u_intensity: () => this.milkyWayIntensity * this.milkyWayVisibility,+ };+ this._starUniforms = uniforms;+ const commands = [];+ this._commands = commands;+ // The environment pass reads `derivedCommands` (log depth, HDR, picking)+ // before calling `execute`; none apply to a far-plane background.+ this._compositeCommand = {+ derivedCommands: {},+ execute(context, passState) {+ for (const command of commands) command.execute(context, passState);+ },+ };+ }++ /** Start loading assets; failures leave a plain black sky. */+ _load() {+ if (this._loading) return;+ this._loading = true;+ loadBundledJson(STAR_PACK_URL)+ .then((pack) => {+ if (this._destroyed) return;+ this._starData = buildStarVertices(pack);+ this._requestRender();+ })+ .catch((error) =>+ console.warn('[sky] star catalogue unavailable', error),+ );+ const faces = Object.entries(MILKY_WAY_FACE_URLS);+ Promise.all(+ faces.map(([, url]) => Cesium.Resource.fetchImage({ url: url.href })),+ )+ .then((images) => {+ if (this._destroyed) return;+ this._faceImages = Object.fromEntries(+ faces.map(([face], index) => [face, images[index]]),+ );+ this._requestRender();+ })+ .catch((error) => console.warn('[sky] Milky Way unavailable', error));+ }++ _updateRotation(time) {+ // An approximate rotation is final only while nothing better can come.+ const settled =+ this._rotationPrecise || this._icrfRequest || !this._canPreloadIcrf(time);+ if (settled && isSkyRotationCurrent(this._rotationTime, time)) return;+ const { precise } = computeSkyRotation(time, this._rotation);+ this._rotationPrecise = precise;+ this._rotationTime = Cesium.JulianDate.clone(time, this._rotationTime);+ if (!precise) this._preloadIcrf(time);+ }++ /** Whether loading Cesium's IAU 2006 tables could still help at `time`. */+ _canPreloadIcrf(time) {+ return (+ !this._icrfUnavailable &&+ !(+ this._icrfMissing &&+ Cesium.TimeInterval.contains(this._icrfMissing, time)+ )+ );+ }++ /** Fetch Cesium's IAU 2006 tables around `time` once per span. */+ _preloadIcrf(time) {+ if (this._icrfRequest || !this._canPreloadIcrf(time)) return;+ const interval = new Cesium.TimeInterval({+ start: Cesium.JulianDate.addDays(time, -1, new Cesium.JulianDate()),+ stop: Cesium.JulianDate.addDays(time, 1, new Cesium.JulianDate()),+ });+ this._icrfRequest = Promise.resolve(+ Cesium.Transforms.preloadIcrfFixed(interval),+ )+ .then(+ () => {+ // The tables cover roughly 1975–2050; outside them the preload+ // resolves with nothing, and TEME stays for this span.+ if (!Cesium.Transforms.computeIcrfToFixedMatrix(time)) {+ this._icrfMissing = interval;+ return;+ }+ this._rotationTime = undefined;+ if (!this._destroyed) this._requestRender();+ },+ (error) => {+ // TEME is within a fraction of a degree; do not retry every frame.+ this._icrfUnavailable = true;+ console.warn('[sky] ICRF tables unavailable, using TEME', error);+ },+ )+ .finally(() => {+ this._icrfRequest = undefined;+ });+ }++ _createMilkyWayCommand(context) {+ const cubeMap = new Cesium.CubeMap({+ context,+ source: this._faceImages,+ flipY: false,+ });+ cubeMap.generateMipmap();+ cubeMap.sampler = new Cesium.Sampler({+ minificationFilter: Cesium.TextureMinificationFilter.LINEAR_MIPMAP_LINEAR,+ });+ this._milkyWayCubeMap = cubeMap;+ this._faceImages = undefined;+ const geometry = Cesium.BoxGeometry.createGeometry(+ Cesium.BoxGeometry.fromDimensions({+ dimensions: new Cesium.Cartesian3(2, 2, 2),+ vertexFormat: Cesium.VertexFormat.POSITION_ONLY,+ }),+ );+ const attributeLocations =+ Cesium.GeometryPipeline.createAttributeLocations(geometry);+ this._milkyWayCommand = new Cesium.DrawCommand({+ owner: this,+ vertexArray: Cesium.VertexArray.fromGeometry({+ context,+ geometry,+ attributeLocations,+ bufferUsage: Cesium.BufferUsage.STATIC_DRAW,+ }),+ renderState: Cesium.RenderState.fromCache({}),+ uniformMap: this._milkyWayUniforms,+ });+ this._milkyWayAttributes = attributeLocations;+ }++ _createStarCommand(context) {+ const { count, vertices } = this._starData;+ this._starData = undefined;+ if (count === 0) return;+ const vertexBuffer = Cesium.Buffer.createVertexBuffer({+ context,+ typedArray: vertices,+ usage: Cesium.BufferUsage.STATIC_DRAW,+ });+ const stride = STAR_VERTEX_FLOATS * Float32Array.BYTES_PER_ELEMENT;+ const attribute = (index, components, offsetFloats) => ({+ index,+ vertexBuffer,+ componentsPerAttribute: components,+ componentDatatype: Cesium.ComponentDatatype.FLOAT,+ offsetInBytes: offsetFloats * Float32Array.BYTES_PER_ELEMENT,+ strideInBytes: stride,+ });+ this._starCommand = new Cesium.DrawCommand({+ owner: this,+ primitiveType: Cesium.PrimitiveType.POINTS,+ count,+ vertexArray: new Cesium.VertexArray({+ context,+ attributes: [+ attribute(0, 3, 0),+ attribute(1, 1, 3),+ attribute(2, 4, 4),+ ],+ }),+ // Premultiplied additive: starlight adds to the Milky Way glow and+ // leaves the framebuffer alpha alone.+ renderState: Cesium.RenderState.fromCache({+ blending: {+ enabled: true,+ equationRgb: Cesium.BlendEquation.ADD,+ equationAlpha: Cesium.BlendEquation.ADD,+ functionSourceRgb: Cesium.BlendFunction.ONE,+ functionDestinationRgb: Cesium.BlendFunction.ONE,+ functionSourceAlpha: Cesium.BlendFunction.ZERO,+ functionDestinationAlpha: Cesium.BlendFunction.ONE,+ },+ }),+ uniformMap: this._starUniforms,+ });+ }++ _updateShaders(context, useHdr) {+ if (this._useHdr === useHdr) return;+ this._useHdr = useHdr;+ const defines = useHdr ? ['HDR'] : [];+ for (const [command, vs, fs, attributeLocations] of [+ [+ this._milkyWayCommand,+ MILKY_WAY_VS,+ MILKY_WAY_FS,+ this._milkyWayAttributes,+ ],+ [+ this._starCommand,+ STAR_VS,+ STAR_FS,+ { position: 0, sigma: 1, color: 2 },+ ],+ ]) {+ if (!command) continue;+ command.shaderProgram?.destroy();+ command.shaderProgram = Cesium.ShaderProgram.fromCache({+ context,+ vertexShaderSource: vs,+ fragmentShaderSource: new Cesium.ShaderSource({+ defines,+ sources: [fs],+ }),+ attributeLocations,+ });+ }+ }++ /** `Scene#skyBox` contract: the command to draw this frame, if any. */+ update(frameState, useHdr) {+ if (!this.show) return undefined;+ const { mode, passes, context } = frameState;+ if (mode !== Cesium.SceneMode.SCENE3D) return undefined;+ if (!passes.render) return undefined;++ if (!this._cubeMap) {++ const face = {++ width: 1,++ height: 1,++ arrayBufferView: new Uint8Array([0, 0, 0, 255]),++ };++ this._cubeMap = new Cesium.CubeMap({++ context,++ source: {++ positiveX: face,++ negativeX: face,++ positiveY: face,++ negativeY: face,++ positiveZ: face,++ negativeZ: face,++ },++ flipY: false,++ });++ }+ this._load();+ let rebuilt = false;+ if (this._faceImages && !this._milkyWayCommand) {+ this._createMilkyWayCommand(context);+ rebuilt = true;+ }+ if (this._starData && !this._starCommand) {+ this._createStarCommand(context);+ rebuilt = true;+ }+ if (rebuilt) this._useHdr = undefined;+ this._updateShaders(context, Boolean(useHdr));+ this._commands.length = 0;+ if (this._milkyWayCommand) this._commands.push(this._milkyWayCommand);+ if (this._starCommand) this._commands.push(this._starCommand);+ if (this._commands.length === 0) return undefined;+ this._updateRotation(frameState.time);+ return this._compositeCommand;+ }++ isDestroyed() {+ return this._destroyed;+ }++ destroy() {+ for (const command of [this._milkyWayCommand, this._starCommand]) {+ if (!command) continue;+ command.vertexArray?.destroy();+ command.shaderProgram?.destroy();+ }+ this._milkyWayCubeMap = this._milkyWayCubeMap?.destroy();++ this._cubeMap = this._cubeMap?.destroy();+ this._milkyWayCommand = undefined;+ this._starCommand = undefined;+ this._commands.length = 0;+ this._destroyed = true;+ return undefined;+ }+}diff --cc src/sky/starrySky.test.mjsindex c6e318519,000000000..4febeb255mode 100644,000000..100644--- a/src/sky/starrySky.test.mjs+++ b/src/sky/starrySky.test.mjs@@@ -1,135 -1,0 +1,200 @@@+import test from 'node:test';+import assert from 'node:assert/strict';+import * as Cesium from 'cesium';+import {+ MILKY_WAY_INTENSITY,+ STARRY_SKY_CESIUM_VERSION,+ SKY_ROTATION_EPSILON_SECONDS,+ StarrySky,+ computeSkyRotation,+ isSkyRotationCurrent,+} from './starrySky.js';++const close = (actual, expected, epsilon = 1e-9) =>+ assert.ok(Math.abs(actual - expected) <= epsilon, `${actual} vs ${expected}`);++test('the sky-box adapter was validated against this engine version', () => {+ assert.equal(+ Cesium.VERSION,+ STARRY_SKY_CESIUM_VERSION,+ 'engine upgrades require revalidating the Scene#skyBox contract',+ );+});++test('the ICRF rotation is preferred and TEME fills in while tables load', () => {+ const time = Cesium.JulianDate.fromIso8601('2026-10-19T00:00:00Z');+ const icrf = Cesium.Matrix3.fromRotationZ(0.3);+ const teme = Cesium.Matrix3.fromRotationZ(0.2);+ const { Transforms } = Cesium;+ const original = { ...Transforms };+ try {+ Transforms.computeIcrfToFixedMatrix = (_, result) =>+ Cesium.Matrix3.clone(icrf, result);+ Transforms.computeTemeToPseudoFixedMatrix = () =>+ assert.fail('TEME not needed');+ const precise = computeSkyRotation(time, new Cesium.Matrix3());+ assert.equal(precise.precise, true);+ assert.ok(Cesium.Matrix3.equals(precise.matrix, icrf));+ Transforms.computeIcrfToFixedMatrix = () => undefined;+ Transforms.computeTemeToPseudoFixedMatrix = (_, result) =>+ Cesium.Matrix3.clone(teme, result);+ const approximate = computeSkyRotation(time, new Cesium.Matrix3());+ assert.equal(approximate.precise, false);+ assert.ok(Cesium.Matrix3.equals(approximate.matrix, teme));+ } finally {+ Object.assign(Transforms, original);+ }+});++test('the TEME fallback keeps the celestial pole on the Earth axis', () => {+ // TEME only spins about Z; ICRF differs from it by precession (~0.36° by+ // 2026), so the fallback sky is right up to a fraction of a degree.+ const time = Cesium.JulianDate.fromIso8601('2026-10-19T00:00:00Z');+ const teme = Cesium.Transforms.computeTemeToPseudoFixedMatrix(time);+ const pole = Cesium.Matrix3.multiplyByVector(+ teme,+ Cesium.Cartesian3.UNIT_Z,+ new Cesium.Cartesian3(),+ );+ assert.ok(Math.abs(pole.z - 1) < 1e-9);+});++test('the rotation is reused only within the clock epsilon', () => {+ const time = Cesium.JulianDate.fromIso8601('2026-10-19T00:00:00Z');+ const later = (seconds) =>+ Cesium.JulianDate.addSeconds(time, seconds, new Cesium.JulianDate());+ assert.equal(isSkyRotationCurrent(undefined, time), false);+ assert.equal(isSkyRotationCurrent(time, later(0.5)), true);+ assert.equal(isSkyRotationCurrent(time, later(-0.5)), true);+ assert.equal(+ isSkyRotationCurrent(time, later(SKY_ROTATION_EPSILON_SECONDS)),+ false,+ );+});++test('the sky draws nothing when hidden, outside 3D, or in a pick pass', () => {+ const sky = new StarrySky({ requestRender: () => {} });+ const frameState = (overrides) => ({+ mode: Cesium.SceneMode.SCENE3D,+ passes: { render: true },+ ...overrides,+ });+ sky._loading = true; // keep the test off the network+ sky.show = false;+ assert.equal(sky.update(frameState()), undefined);+ sky.show = true;+ assert.equal(+ sky.update(frameState({ mode: Cesium.SceneMode.SCENE2D })),+ undefined,+ );+ assert.equal(+ sky.update(frameState({ passes: { render: false, pick: true } })),+ undefined,+ );+ // Nothing has loaded yet, so even a render pass has no command.++ sky._cubeMap = { destroy() {} }; // no WebGL context in this unit test+ assert.equal(sky.update(frameState()), undefined);+ assert.equal(sky.isDestroyed(), false);+ assert.equal(sky.destroy(), undefined);+ assert.equal(sky.isDestroyed(), true);+});++const frame = () => new Promise((resolve) => setImmediate(resolve));++for (const iso of ['1970-01-01T00:00:00Z', '2060-01-01T00:00:00Z']) {+ test(`a clock outside the IAU 2006 tables (${iso}) settles on TEME instead of re-rendering every frame`, async () => {+ const time = Cesium.JulianDate.fromIso8601(iso);+ let renders = 0;+ let preloads = 0;+ const original = Cesium.Transforms.preloadIcrfFixed;+ Cesium.Transforms.preloadIcrfFixed = (interval) => {+ preloads += 1;+ return original(interval);+ };+ try {+ const sky = new StarrySky({ requestRender: () => (renders += 1) });+ for (let i = 0; i < 20; i += 1) {+ sky._updateRotation(time); // what update() does once per frame+ await frame();+ }+ assert.ok(+ renders <= 1 && preloads <= 1,+ `20 frames at a frozen clock -> ${preloads} preloads, ${renders} render requests (expected <= 1 each)`,+ );+ } finally {+ Cesium.Transforms.preloadIcrfFixed = original;+ }+ });+}++test('the Milky Way glow scales with its visibility, for styles that hide it', () => {+ const sky = new StarrySky({ requestRender: () => {} });+ close(sky._milkyWayUniforms.u_intensity(), MILKY_WAY_INTENSITY);+ sky.milkyWayVisibility = 0;+ assert.equal(sky._milkyWayUniforms.u_intensity(), 0);+ sky.destroy();+});++++test('destroy releases both the background and model environment maps', () => {++ const sky = new StarrySky({ requestRender: () => {} });++ let destroyed = 0;++ sky._cubeMap = {++ destroy: () => {++ destroyed++;++ },++ };++ sky._milkyWayCubeMap = {++ destroy: () => {++ destroyed++;++ },++ };++ sky.destroy();++ assert.equal(destroyed, 2);++ assert.equal(sky._cubeMap, undefined);++ assert.equal(sky._milkyWayCubeMap, undefined);++ sky.destroy();++ assert.equal(destroyed, 2);++});++++test('a render update uploads six opaque black environment faces only once', () => {++ const uploads = [];++ const gl = {++ ...Cesium.WebGLConstants,++ createTexture: () => ({}),++ activeTexture() {},++ bindTexture() {},++ texParameteri() {},++ pixelStorei() {},++ texImage2D: (...args) => uploads.push(args),++ deleteTexture() {},++ };++ const previous = Cesium.ContextLimits._maximumCubeMapSize;++ Cesium.ContextLimits._maximumCubeMapSize = 16;++ const sky = new StarrySky({ requestRender: () => {} });++ sky._loading = true;++ const state = {++ context: { _gl: gl },++ mode: Cesium.SceneMode.SCENE3D,++ passes: { render: true },++ };++ try {++ sky.update(state);++ const environment = sky._cubeMap;++ assert.ok(environment instanceof Cesium.CubeMap);++ assert.equal(uploads.length, 6);++ assert.equal(new Set(uploads.map((args) => args[0])).size, 6);++ for (const args of uploads) {++ assert.equal(args[3], 1);++ assert.equal(args[4], 1);++ assert.deepEqual([...args[8]], [0, 0, 0, 255]);++ }++ sky.update(state);++ assert.equal(sky._cubeMap, environment);++ assert.equal(uploads.length, 6);++ sky.destroy();++ assert.equal(environment.isDestroyed(), true);++ } finally {++ if (!sky.isDestroyed()) sky.destroy();++ Cesium.ContextLimits._maximumCubeMapSize = previous;++ }++});diff --cc src/ui/visualEffects.jsindex 24cff6189,6533bb748..8b5234ef2--- a/src/ui/visualEffects.js+++ b/src/ui/visualEffects.js@@@ -112,10 -112,6 +112,13 @@@ export class VisualEffectsif (this.stopped || !stage) return;stage.uniforms.intensity = value;stage.enabled = value > 0.001;+ // Anime's bands turn the faint Milky Way into blotches, and depth cannot+ // tell the sky from far geometry, so the glow fades with the style.- if (stage === this.stages.anime)++ if (++ stage === this.stages.anime &&++ this.viewer.scene.skyBox?.milkyWayVisibility !== undefined++ )+ this.viewer.scene.skyBox.milkyWayVisibility = 1 - value;if (stage.enabled && stage.uniforms.time !== undefined)this.startAnimationLoop();this.requestRender('style-stage');diff --cc src/ui/visualEffects.test.mjsindex e2abbc35c,76615d0e8..68fa45962--- a/src/ui/visualEffects.test.mjs+++ b/src/ui/visualEffects.test.mjs@@@ -161,24 -158,6 +161,38 @@@ test('direct Cockpit intensity writes af.effects.destroy();});+test('the anime stage fades the Milky Way out with its own intensity', () => {+ const f = fixture();+ const sky = new StarrySky({ requestRender: () => {} });+ const glow = () => sky._milkyWayUniforms.u_intensity();+ f.effects.viewer.scene.skyBox = sky;+ f.effects.initStyles();+ f.effects.setStageIntensity(f.effects.stages.thermal, 1);+ assert.equal(glow(), MILKY_WAY_INTENSITY, 'other styles keep the glow');+ f.effects.setStageIntensity(f.effects.stages.anime, 0.25);+ assert.equal(glow(), MILKY_WAY_INTENSITY * 0.75);+ f.effects.setStageIntensity(f.effects.stages.anime, 1);+ assert.equal(glow(), 0);+ f.effects.setStageIntensity(f.effects.stages.anime, 0);+ assert.equal(glow(), MILKY_WAY_INTENSITY);+ sky.destroy();+ f.effects.destroy();+});+++for (const skyBox of [undefined, null, {}]) {++ test(`anime works without StarrySky (${JSON.stringify(skyBox)})`, () => {++ const f = fixture();++ f.effects.viewer.scene.skyBox = skyBox;++ f.effects.initStyles();++ f.effects.setStageIntensity(f.effects.stages.anime, 1);++ assert.equal(f.effects.stages.anime.enabled, true);++ f.effects.setStageIntensity(f.effects.stages.anime, 0);++ assert.equal(f.effects.stages.anime.enabled, false);++ if (skyBox) assert.equal('milkyWayVisibility' in skyBox, false);++ f.effects.destroy();++ });++}++test('bloom retains its dead zone, normalized intensity and independent toggle', () => {const f = fixture();f.effects.initPostProcess();