Compare commits

...
Sign in to create a new pull request.
Author SHA1 Message Date
d851a5fca9 Merge pull request 'Sky menu: Auto, six named moments and a free moment, in the place's local time' (#176) from void/sky-menu-moments into dev
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 3m55s
2026-11-20 23:12:54 +00:00
Meta Vens
cd81f85d05 Sky menu fixes: one owner of the drawn place, Night is tonight's, named moments roll
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m32s
- skyPlace.ts is the only writer of the sky's place: the manifest's when the cards load, FALLBACK_VIEW's
  when the manifest or cards fail; the scene draws the view it told the store, so sky, weather, ink and
  Auto agree on every drawn state (Auto ticks on the fallback).
- useSkyPlace removed: only a scene start fetches the manifest.
- Old-key migration writes the new key first; a refused write keeps the pick for the page load.
- A named moment re-resolves when the place-local day rolls over (the one timer); Night is the nearest
  solar midnight (before the day's noon the one just passed or coming), keyed by the instant drawn.
- Baker validate/schema check place.tz as load_preset does; Vienna manifest baker_version 3 (it carries tz).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-21 00:07:01 +01:00
Meta Vens
3269250d19 Scene README: the sky choice, the moment authority and place.tz
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 23:42:49 +01:00
Meta Vens
e948f99f9e Sky menu: Auto, six named moments and a free moment picker
Seven radio items plus Pick a moment, which opens a date input and a 5-minute time slider that show the
place-local time and zone and commit on the native change event (slider release), never per input tick.
The picker opens from the moment being drawn, in the place zone (seedFree).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 23:42:48 +01:00
Meta Vens
4597539976 Tests and look sheet follow the moment authority
Tests move to SkyChoice and the sun-taking makePhysicalSky; the harness sheet takes the six named moments
on both solstices (?named=1).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 23:36:08 +01:00
Meta Vens
ca77bacb4a Sky choice store: Auto, named or free moment resolved at the loaded place
skyState.ts holds the choice, the place and the lines and resolves the band through momentFor and skyBand;
resolveSkyState, LAT and the page-zone clock approximation are deleted. skyPlace.ts shares the manifest with
the scene; hooks, theme and ink take an undefined sky until a place is known. Old 'ratatoskr.skyState' is read
once and removed; the choice persists as 'ratatoskr.skyChoice'.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 23:36:06 +01:00
Meta Vens
8e44479792 Place carries its time zone: baker writes place.tz, manifest parses it
places.json tz per preset, load_preset refuses a missing or unknown zone, schema regenerated,
BAKER_VERSION 3; runtime rejects a zone Intl does not know; Vienna manifest gains the one line.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 23:23:26 +01:00
Meta Vens
fbe9c9a930 Sky moment authority: skyMoment.ts decides the drawn instant; sunForState deleted
momentFor(choice, place, now) and skyBand are the one owner of the instant and the band.
sunAt.ts loses STATE_ELEVATION, solarNoon and sunForState; makePhysicalSky takes the sun it is given.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 23:23:24 +01:00
41 changed files with 1835 additions and 517 deletions

View file

@ -46,4 +46,4 @@ Presets (`PRESETS` in `ridgeSheet.ts`; swiss and poster take every key not named
| painterly | DEFAULT_LOOK: groundNoise 0.35, cloudShadows 0.5, nearWarm 0.6, hazeScale 2, inkScale 0.4, celBands 3, celSoftness 0.05, celAmbientAway 0.7 | | painterly | DEFAULT_LOOK: groundNoise 0.35, cloudShadows 0.5, nearWarm 0.6, hazeScale 2, inkScale 0.4, celBands 3, celSoftness 0.05, celAmbientAway 0.7 |
| painterly-cel-2 / -3 / -4 | painterly with celBands 2 / 3 / 4 | | painterly-cel-2 / -3 / -4 | painterly with celBands 2 / 3 / 4 |
Night sets (`ridgeSheet.html`): `?moments=2026-11-24T22:00Z,2026-12-09T20:00Z` pins explicit UTC moments (the sun, moon and stars are those of the moment); `?night=1` renders the next new moon, first quarter and full moon from today (`&from=YYYY-MM-DD`) at four hours each (`&hours=18,21,0,4`, UTC) plus deep dusk of the full-moon evening; `&lines=1` draws the constellation lines (the Sky menu's hidden toggle). Use `&w=300` for the 13-column set. The night look's knobs: `NIGHT_LOOK` in `ridge/nightSky.ts` (star point spread, contrast exponents, moon size, earthshine, line opacity), `NIGHT_CEILING` and `SCOTOPIC` in `ridge/toneMap.ts`, the night `Budget` (key, targets, partial adaptation). Named moments (`ridgeSheet.html?named=1`): the six moments of the Sky menu (dawn, morning, noon, golden hour, dusk, night) at the baked place on the December and June solstices, drawn from `momentFor` as the app draws them (`SKY_MOMENTS` in `ridge/skyMoment.ts` is the table tuned by eye from this sheet). Night sets (`ridgeSheet.html`): `?moments=2026-11-24T22:00Z,2026-12-09T20:00Z` pins explicit UTC moments (the sun, moon and stars are those of the moment); `?night=1` renders the next new moon, first quarter and full moon from today (`&from=YYYY-MM-DD`) at four hours each (`&hours=18,21,0,4`, UTC) plus deep dusk of the full-moon evening; `&lines=1` draws the constellation lines (the Sky menu's hidden toggle). Use `&w=300` for the 13-column set. The night look's knobs: `NIGHT_LOOK` in `ridge/nightSky.ts` (star point spread, contrast exponents, moon size, earthshine, line opacity), `NIGHT_CEILING` and `SCOTOPIC` in `ridge/toneMap.ts`, the night `Budget` (key, targets, partial adaptation).

View file

@ -17,8 +17,7 @@ import { nightBodies, onScreen, paintNightBodies } from '../../src/app/features/
import { sunAt } from '../../src/app/features/scene/ridge/sunAt'; import { sunAt } from '../../src/app/features/scene/ridge/sunAt';
import { linesAt } from '../../src/app/features/scene/ridge/starCatalogue'; import { linesAt } from '../../src/app/features/scene/ridge/starCatalogue';
import { moonPhase } from '../../src/sky/moon.js'; import { moonPhase } from '../../src/sky/moon.js';
import { DAY_FROM } from '../../src/app/features/scene/skyState'; import { MOMENT_IDS, momentFor } from '../../src/app/features/scene/ridge/skyMoment';
import type { FixedSkyState } from '../../src/app/features/scene/skyState';
const DIR = '/public/ridge/vienna-6815bb9dca99/'; const DIR = '/public/ridge/vienna-6815bb9dca99/';
@ -38,7 +37,7 @@ interface Column {
time?: Date; time?: Date;
} }
/** Sun elevation and compass azimuth of each column; the cards look at 214 +- 36. Elevation picks the display budget (day from DAY_FROM, night below its negative). */ /** Sun elevation and compass azimuth of each column; the cards look at 214 +- 36. The band of the elevation (`skyBand`) picks the display budget. */
const SKIES: Column[] = [ const SKIES: Column[] = [
{ label: 'dawn 2 deg', elevation: 2, azimuth: 100 }, { label: 'dawn 2 deg', elevation: 2, azimuth: 100 },
{ label: 'morning 15 deg', elevation: 15, azimuth: 135 }, { label: 'morning 15 deg', elevation: 15, azimuth: 135 },
@ -138,6 +137,14 @@ function momentsFrom(params: URLSearchParams, place: Parameters<typeof sunAt>[0]
if (Number.isNaN(time.getTime())) throw new Error(`moments=: ${iso} is not a date`); if (Number.isNaN(time.getTime())) throw new Error(`moments=: ${iso} is not a date`);
return { label: fmt(time), time }; return { label: fmt(time), time };
}); });
// `named=1`: the six named moments of the sky menu (`momentFor`, as the app draws them) on both solstices at the place: the look sheet the elevation table is tuned from.
if (params.get('named'))
return ['2026-12-21', '2026-06-21'].flatMap((day) =>
MOMENT_IDS.map((id) => {
const time = momentFor({ kind: 'named', id }, place, new Date(`${day}T12:00:00Z`));
return { label: `${id} ${day.slice(5)} ${fmt(time)}`, time };
})
);
if (!params.get('night')) return undefined; if (!params.get('night')) return undefined;
const from = params.get('from') ? new Date(`${params.get('from')}T00:00:00Z`) : new Date(); const from = params.get('from') ? new Date(`${params.get('from')}T00:00:00Z`) : new Date();
const hours = (params.get('hours') ?? '18,21,0,4').split(',').map(Number); const hours = (params.get('hours') ?? '18,21,0,4').split(',').map(Number);
@ -176,9 +183,6 @@ const W = Number(q.get('w') ?? 480);
const H = q.get('h') ? Number(q.get('h')) : Math.round((W * 9) / 16); const H = q.get('h') ? Number(q.get('h')) : Math.round((W * 9) / 16);
const root = document.getElementById('sheet') as HTMLElement; const root = document.getElementById('sheet') as HTMLElement;
const stateOf = (el: number): FixedSkyState =>
el >= DAY_FROM ? 'day' : el <= -DAY_FROM ? 'night' : 'dusk';
async function main() { async function main() {
const manifest = parseManifest(await (await fetch(`${DIR}manifest.json`)).json(), DIR); const manifest = parseManifest(await (await fetch(`${DIR}manifest.json`)).json(), DIR);
const blobs = await Promise.all( const blobs = await Promise.all(
@ -213,7 +217,7 @@ async function main() {
col.time !== undefined col.time !== undefined
? sunAt(view.place, col.time) ? sunAt(view.place, col.time)
: { elevation: col.elevation as number, azimuth: col.azimuth as number, time }; : { elevation: col.elevation as number, azimuth: col.azimuth as number, time };
const physical = makePhysicalSky(stateOf(sun.elevation), time, 0, view, sun); const physical = makePhysicalSky(sun, 0, view);
const px = paintSky(physical, W, H, win.camera); const px = paintSky(physical, W, H, win.camera);
const bodies = nightBodies(physical, px, withLines); const bodies = nightBodies(physical, px, withLines);
const small = document.createElement('canvas'); const small = document.createElement('canvas');

View file

@ -1,6 +1,6 @@
{ {
"schema": 2, "schema": 2,
"baker_version": 2, "baker_version": 3,
"bake_id": "6815bb9dca99", "bake_id": "6815bb9dca99",
"place": { "place": {
"id": "vienna", "id": "vienna",
@ -8,7 +8,8 @@
"lat": 48.1929826, "lat": 48.1929826,
"lon": 16.3534237, "lon": 16.3534237,
"altitude_km": 0.18330000000000002, "altitude_km": 0.18330000000000002,
"eye_m": 213.3 "eye_m": 213.3,
"tz": "Europe/Vienna"
}, },
"view": { "view": {
"look_az_deg": 214.0, "look_az_deg": 214.0,

View file

@ -7,11 +7,12 @@ The runtime reads manifest.json (SCHEMA is its contract) and nothing else about
import no baker; bake_place imports ridge, which needs RIDGE_TILES and RIDGE_WORK (main sets them from --tiles / --work).""" import no baker; bake_place imports ridge, which needs RIDGE_TILES and RIDGE_WORK (main sets them from --tiles / --work)."""
import os, sys, json, math, shutil, hashlib, argparse, tempfile import os, sys, json, math, shutil, hashlib, argparse, tempfile
from pathlib import Path from pathlib import Path
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
HERE = Path(__file__).resolve().parent HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE)) sys.path.insert(0, str(HERE))
import numpy as np, imagecodecs import numpy as np, imagecodecs
BAKER_VERSION = 2 BAKER_VERSION = 3
WINDOW_DEG = 72 WINDOW_DEG = 72
PLANE_W = 1280 # every card is the whole 72 deg window wide PLANE_W = 1280 # every card is the whole 72 deg window wide
PLANE_W_MAX = 4096 PLANE_W_MAX = 4096
@ -35,11 +36,12 @@ ATTRIBUTION = dict(
# ------------------------------------------------------------------------------------ schema (the one dict the schema file and the validator both come from) # ------------------------------------------------------------------------------------ schema (the one dict the schema file and the validator both come from)
_num, _int, _str = {'type': 'number'}, {'type': 'integer'}, {'type': 'string'} _num, _int, _str = {'type': 'number'}, {'type': 'integer'}, {'type': 'string'}
_numnull = {'type': ['number', 'null']} _numnull = {'type': ['number', 'null']}
_tz = {'type': 'string', 'format': 'iana-tz'} # an IANA zone the system knows, as ridge.load_preset requires; validate() checks it
def _obj(**props): return {'type': 'object', 'required': list(props), 'additionalProperties': False, 'properties': props} def _obj(**props): return {'type': 'object', 'required': list(props), 'additionalProperties': False, 'properties': props}
_file = _obj(file=_str, bytes=_int) _file = _obj(file=_str, bytes=_int)
SCHEMA = {'$schema': 'https://json-schema.org/draft/2020-12/schema', 'title': 'ridge-bake manifest v2 and index v1', '$defs': { SCHEMA = {'$schema': 'https://json-schema.org/draft/2020-12/schema', 'title': 'ridge-bake manifest v2 and index v1', '$defs': {
'manifest': _obj(schema={'const': 2}, baker_version=_int, bake_id=_str, 'manifest': _obj(schema={'const': 2}, baker_version=_int, bake_id=_str,
place=_obj(id=_str, name=_str, lat=_num, lon=_num, altitude_km=_num, eye_m=_num), place=_obj(id=_str, name=_str, lat=_num, lon=_num, altitude_km=_num, eye_m=_num, tz=_tz),
view=_obj(look_az_deg=_num, window_deg={'const': WINDOW_DEG}, plane_w={'type': 'integer', 'maximum': PLANE_W_MAX}, plane_h=_int, px_per_deg_h=_num, px_per_deg_v=_num, exaggeration=_num, horizon_row=_num, sky_row=_num, near_row=_num), view=_obj(look_az_deg=_num, window_deg={'const': WINDOW_DEG}, plane_w={'type': 'integer', 'maximum': PLANE_W_MAX}, plane_h=_int, px_per_deg_h=_num, px_per_deg_v=_num, exaggeration=_num, horizon_row=_num, sky_row=_num, near_row=_num),
curvature=_obj(r_earth_m=_num, k_ref=_num), curvature=_obj(r_earth_m=_num, k_ref=_num),
encoding=_obj(log_d_min=_num, log_d_max=_num, normal={'const': 'rt8'}), encoding=_obj(log_d_min=_num, log_d_max=_num, normal={'const': 'rt8'}),
@ -55,6 +57,9 @@ def validate(x, s, path='$'):
if '$ref' in s: return validate(x, SCHEMA['$defs'][s['$ref'].split('/')[-1]], path) if '$ref' in s: return validate(x, SCHEMA['$defs'][s['$ref'].split('/')[-1]], path)
tys = s.get('type'); tys = [tys] if isinstance(tys, str) else tys; py = {'object': dict, 'array': list, 'string': str, 'number': (int, float), 'integer': int, 'null': type(None)} tys = s.get('type'); tys = [tys] if isinstance(tys, str) else tys; py = {'object': dict, 'array': list, 'string': str, 'number': (int, float), 'integer': int, 'null': type(None)}
if tys and not any(isinstance(x, py[t]) and not (isinstance(x, bool) and t != 'null') for t in tys): raise ValueError(f'{path}: not a {"/".join(tys)}') if tys and not any(isinstance(x, py[t]) and not (isinstance(x, bool) and t != 'null') for t in tys): raise ValueError(f'{path}: not a {"/".join(tys)}')
if s.get('format') == 'iana-tz':
try: ZoneInfo(x)
except (ZoneInfoNotFoundError, ValueError, OSError): raise ValueError(f'{path}: {x!r} is not a time zone the system knows')
if 'const' in s and x != s['const']: raise ValueError(f"{path}: must be {s['const']!r}") if 'const' in s and x != s['const']: raise ValueError(f"{path}: must be {s['const']!r}")
if 'enum' in s and x not in s['enum']: raise ValueError(f'{path}: not one of {s["enum"]}') if 'enum' in s and x not in s['enum']: raise ValueError(f'{path}: not one of {s["enum"]}')
if 'maximum' in s and x > s['maximum']: raise ValueError(f'{path}: above {s["maximum"]}') if 'maximum' in s and x > s['maximum']: raise ValueError(f'{path}: above {s["maximum"]}')
@ -153,7 +158,7 @@ def bake_place(pid):
assert ridge.WIN == PLANE_W and ridge.H > 0 assert ridge.WIN == PLANE_W and ridge.H > 0
p = ridge.configure(ridge.load_preset(pid)); ridge.mosaic(p); d, _, Hh, _ = ridge.stage0(False); a, h = ridge.prefilter(d, Hh, p.get('prefilter_m', 0)); v = ridge.set_view(a.max(0)) p = ridge.configure(ridge.load_preset(pid)); ridge.mosaic(p); d, _, Hh, _ = ridge.stage0(False); a, h = ridge.prefilter(d, Hh, p.get('prefilter_m', 0)); v = ridge.set_view(a.max(0))
nrm = tuple(ridge.win(x) for x in ridge.normals(d, h)); aw, hw = ridge.win(a), ridge.win(h); cov = ridge.coverage(d, aw); sm = ridge.seams(cov, [k * 1000.0 for k in p['card_split_km']], d) nrm = tuple(ridge.win(x) for x in ridge.normals(d, h)); aw, hw = ridge.win(a), ridge.win(h); cov = ridge.coverage(d, aw); sm = ridge.seams(cov, [k * 1000.0 for k in p['card_split_km']], d)
place = dict(id=p['id'], name=p['name'], lat=p['lat'], lon=p['lon'], altitude_km=p['ground_m'] / 1000.0, eye_m=p['eye_m']) place = dict(id=p['id'], name=p['name'], lat=p['lat'], lon=p['lon'], altitude_km=p['ground_m'] / 1000.0, eye_m=p['eye_m'], tz=p['tz'])
view = dict(look_az_deg=p['az_center'], plane_h=ridge.H, px_per_deg_h=ridge.HPX_DEG, px_per_deg_v=v['px_per_deg'], exaggeration=v['exaggeration'], horizon_row=v['horizon_row'], sky_row=v['sky_row'] * ridge.H, near_row=v['near_row'] * ridge.H) view = dict(look_az_deg=p['az_center'], plane_h=ridge.H, px_per_deg_h=ridge.HPX_DEG, px_per_deg_v=v['px_per_deg'], exaggeration=v['exaggeration'], horizon_row=v['horizon_row'], sky_row=v['sky_row'] * ridge.H, near_row=v['near_row'] * ridge.H)
meta = dict(curvature=dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF), encoding=dict(log_d_min=math.log(d[0]), log_d_max=math.log(d[-1])), camera=dict(r_m=float(p.get('camera_r_m', CAMERA_R_M)), heading_max_deg=HEADING_MAX_DEG)) meta = dict(curvature=dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF), encoding=dict(log_d_min=math.log(d[0]), log_d_max=math.log(d[-1])), camera=dict(r_m=float(p.get('camera_r_m', CAMERA_R_M)), heading_max_deg=HEADING_MAX_DEG))
return dict(place=place, view=view, meta=meta, cards=ridge.cards(d, aw, hw, sm, nrm), splits_km=list(p['card_split_km']), seams=sm, cov=cov, opaque=ridge.opaque(aw), edges=ridge.log_edges(d)) return dict(place=place, view=view, meta=meta, cards=ridge.cards(d, aw, hw, sm, nrm), splits_km=list(p['card_split_km']), seams=sm, cov=cov, opaque=ridge.opaque(aw), edges=ridge.log_edges(d))

View file

@ -1,8 +1,9 @@
{ {
"_doc": "Place presets for the A+D baker (ridge.py). eye = observer lat/lon; eye_h_m = eye above the local DEM surface (ground_override_m replaces the DEM ground elevation, used for Vienna to keep round 1's 183.3 m); look_at = target lat/lon whose bearing centres the 72 deg window (or az_deg); rmax_km = ring radius (decides the tile list: every 1x1 deg GLO-30 tile whose rectangle intersects the circle); card_split_km = the ordered list of 1 to MAX_CARDS - 1 authored seam depths in km (the seam search refines each per column; K splits make K+1 cards; required, never defaulted); prefilter_m = Gaussian sigma in metres of the height low-pass before the cards are cut (default 0).", "_doc": "Place presets for the A+D baker (ridge.py). eye = observer lat/lon; eye_h_m = eye above the local DEM surface (ground_override_m replaces the DEM ground elevation, used for Vienna to keep round 1's 183.3 m); look_at = target lat/lon whose bearing centres the 72 deg window (or az_deg); tz = the place's IANA time zone (required, never defaulted: the runtime draws named sky moments in the place's local day); rmax_km = ring radius (decides the tile list: every 1x1 deg GLO-30 tile whose rectangle intersects the circle); card_split_km = the ordered list of 1 to MAX_CARDS - 1 authored seam depths in km (the seam search refines each per column; K splits make K+1 cards; required, never defaulted); prefilter_m = Gaussian sigma in metres of the height low-pass before the cards are cut (default 0).",
"presets": [ "presets": [
{ {
"id": "vienna", "id": "vienna",
"tz": "Europe/Vienna",
"name": "Vienna, looking SW to Rax/Schneeberg", "name": "Vienna, looking SW to Rax/Schneeberg",
"kind": "far range over a flat foreground", "kind": "far range over a flat foreground",
"lat": 48.1929826, "lat": 48.1929826,
@ -22,6 +23,7 @@
}, },
{ {
"id": "matterhorn", "id": "matterhorn",
"tz": "Europe/Zurich",
"name": "Matterhorn from the Gornergrat (photo cell, 9.7 km)", "name": "Matterhorn from the Gornergrat (photo cell, 9.7 km)",
"kind": "lone horn, close, 27 deg of relief", "kind": "lone horn, close, 27 deg of relief",
"lat": 45.983139, "lat": 45.983139,
@ -151,6 +153,7 @@
}, },
{ {
"id": "fuji", "id": "fuji",
"tz": "Asia/Tokyo",
"name": "Fuji from the Shiraito Falls side, 13.8 km WSW (photo cell)", "name": "Fuji from the Shiraito Falls side, 13.8 km WSW (photo cell)",
"kind": "lone cone, smooth", "kind": "lone cone, smooth",
"lat": 35.312467222222494, "lat": 35.312467222222494,
@ -297,6 +300,7 @@
}, },
{ {
"id": "halfdome", "id": "halfdome",
"tz": "America/Los_Angeles",
"name": "Half Dome from the Yosemite Valley floor (Sentinel Bridge photo cell)", "name": "Half Dome from the Yosemite Valley floor (Sentinel Bridge photo cell)",
"kind": "granite wall across a valley", "kind": "granite wall across a valley",
"lat": 37.745833333333, "lat": 37.745833333333,
@ -454,6 +458,7 @@
}, },
{ {
"id": "amadablam", "id": "amadablam",
"tz": "Asia/Kathmandu",
"name": "Ama Dablam and the Everest massif, 4 km WSW of Tengboche near Khumjung (photo cell)", "name": "Ama Dablam and the Everest massif, 4 km WSW of Tengboche near Khumjung (photo cell)",
"kind": "far high range behind a near spire", "kind": "far high range behind a near spire",
"lat": 27.822000000000003, "lat": 27.822000000000003,
@ -528,6 +533,7 @@
}, },
{ {
"id": "trecime", "id": "trecime",
"tz": "Europe/Rome",
"name": "Tre Cime di Lavaredo from the Dreizinnenhuette area, 2.4 km N (photo cell)", "name": "Tre Cime di Lavaredo from the Dreizinnenhuette area, 2.4 km N (photo cell)",
"kind": "cirque wall, spires", "kind": "cirque wall, spires",
"lat": 46.636906, "lat": 46.636906,

View file

@ -38,7 +38,8 @@
"lat", "lat",
"lon", "lon",
"altitude_km", "altitude_km",
"eye_m" "eye_m",
"tz"
], ],
"additionalProperties": false, "additionalProperties": false,
"properties": { "properties": {
@ -59,6 +60,10 @@
}, },
"eye_m": { "eye_m": {
"type": "number" "type": "number"
},
"tz": {
"type": "string",
"format": "iana-tz"
} }
} }
}, },

View file

@ -10,6 +10,7 @@ Offline baker for the ridge backdrop (scripts/ridge-bake); export.py drives it.
Vertical exaggeration is AUTHORED and derived per view by set_view (printed on the page). The client owns lighting, haze and ink (ruling ridge-cards-runtime-lit).""" Vertical exaggeration is AUTHORED and derived per view by set_view (printed on the page). The client owns lighting, haze and ink (ruling ridge-cards-runtime-lit)."""
import sys, time, math, json import sys, time, math, json
import os, hashlib import os, hashlib
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
from pathlib import Path from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent)) sys.path.insert(0, str(Path(__file__).resolve().parent))
import numpy as np, tifffile import numpy as np, tifffile
@ -31,11 +32,15 @@ P = {} # configured preset
rowang = np.zeros(H); PXDEG_V = 100.0; TOP_DEG = 2.6; BOTTOM_DEG = -3.4 rowang = np.zeros(H); PXDEG_V = 100.0; TOP_DEG = 2.6; BOTTOM_DEG = -3.4
def load_preset(pid, path=Path(__file__).resolve().parent / 'places.json'): def load_preset(pid, path=Path(__file__).resolve().parent / 'places.json'):
"""The preset dict. card_split_km is the ordered list of authored seam depths (km): required, strictly increasing, at most export.MAX_CARDS - 1 (the cap is export's, which owns the budget); refused here, before any march.""" """The preset dict. tz is required, an IANA zone the system knows (the runtime draws named sky moments in the place's local day). card_split_km is the ordered list of authored seam depths (km): required, strictly increasing, at most export.MAX_CARDS - 1 (the cap is export's, which owns the budget); refused here, before any march."""
d = json.load(open(path)); p = dict(next(x for x in d['presets'] if x['id'] == pid)); sp = p.get('card_split_km') d = json.load(open(path)); p = dict(next(x for x in d['presets'] if x['id'] == pid)); sp = p.get('card_split_km')
from export import MAX_CARDS from export import MAX_CARDS
if not sp: raise ValueError(f"preset {pid}: card_split_km is required (an ordered list of 1 to {MAX_CARDS - 1} depths in km)") if not sp: raise ValueError(f"preset {pid}: card_split_km is required (an ordered list of 1 to {MAX_CARDS - 1} depths in km)")
if len(sp) > MAX_CARDS - 1 or any(b <= a for a, b in zip(sp, sp[1:])): raise ValueError(f"preset {pid}: card_split_km {sp} must be strictly increasing with at most {MAX_CARDS - 1} entries") if len(sp) > MAX_CARDS - 1 or any(b <= a for a, b in zip(sp, sp[1:])): raise ValueError(f"preset {pid}: card_split_km {sp} must be strictly increasing with at most {MAX_CARDS - 1} entries")
tz = p.get('tz')
if not isinstance(tz, str) or not tz: raise ValueError(f"preset {pid}: tz is required (an IANA time zone name such as Europe/Vienna)")
try: ZoneInfo(tz)
except (ZoneInfoNotFoundError, ValueError, OSError): raise ValueError(f"preset {pid}: tz {tz!r} is not a time zone the system knows")
return p return p
# ====================================================================== configuration, DEM # ====================================================================== configuration, DEM

View file

@ -49,7 +49,7 @@ def _bake(hfun, splits_km, sigma=0.0):
"""prefilter, set_view, coverage, seams, cards on synthetic rays (window = columns 0..WIN, i.e. azimuth 0..72): the dict bake_place returns.""" """prefilter, set_view, coverage, seams, cards on synthetic rays (window = columns 0..WIN, i.e. azimuth 0..72): the dict bake_place returns."""
A, Hh = rays(hfun); ridge.P.update(win0=0, eye_m=EYE); a, h = ridge.prefilter(D, Hh, sigma); v = ridge.set_view(a.max(0)) A, Hh = rays(hfun); ridge.P.update(win0=0, eye_m=EYE); a, h = ridge.prefilter(D, Hh, sigma); v = ridge.set_view(a.max(0))
nrm = tuple(ridge.win(x) for x in ridge.normals(D, h)); aw, hw = ridge.win(a), ridge.win(h); cov = ridge.coverage(D, aw); sm = ridge.seams(cov, [k * 1000.0 for k in splits_km], D) nrm = tuple(ridge.win(x) for x in ridge.normals(D, h)); aw, hw = ridge.win(a), ridge.win(h); cov = ridge.coverage(D, aw); sm = ridge.seams(cov, [k * 1000.0 for k in splits_km], D)
place = dict(id='synthetic', name='Synthetic', lat=48.0, lon=16.0, altitude_km=0.05, eye_m=EYE) place = dict(id='synthetic', name='Synthetic', lat=48.0, lon=16.0, altitude_km=0.05, eye_m=EYE, tz='Europe/Vienna')
view = dict(look_az_deg=36.0, plane_h=H, px_per_deg_h=ridge.HPX_DEG, px_per_deg_v=v['px_per_deg'], exaggeration=v['exaggeration'], horizon_row=v['horizon_row'], sky_row=v['sky_row'] * H, near_row=v['near_row'] * H) view = dict(look_az_deg=36.0, plane_h=H, px_per_deg_h=ridge.HPX_DEG, px_per_deg_v=v['px_per_deg'], exaggeration=v['exaggeration'], horizon_row=v['horizon_row'], sky_row=v['sky_row'] * H, near_row=v['near_row'] * H)
meta = dict(curvature=dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF), encoding=dict(log_d_min=math.log(D[0]), log_d_max=math.log(D[-1])), camera=dict(r_m=export.CAMERA_R_M, heading_max_deg=17.0)) meta = dict(curvature=dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF), encoding=dict(log_d_min=math.log(D[0]), log_d_max=math.log(D[-1])), camera=dict(r_m=export.CAMERA_R_M, heading_max_deg=17.0))
return dict(place=place, view=view, meta=meta, cards=ridge.cards(D, aw, hw, sm, nrm, ), splits_km=list(splits_km), seams=sm, cov=cov, opaque=ridge.opaque(aw), edges=ridge.log_edges(D), a=aw, h=hw, v=v) return dict(place=place, view=view, meta=meta, cards=ridge.cards(D, aw, hw, sm, nrm, ), splits_km=list(splits_km), seams=sm, cov=cov, opaque=ridge.opaque(aw), edges=ridge.log_edges(D), a=aw, h=hw, v=v)
@ -189,6 +189,9 @@ def test_manifest_v2_writer():
assert m['cards'][0]['near_m'] is None and m['cards'][-1]['far_m'] is None and m['cards'][0]['far_m'] == m['cards'][1]['near_m'] and m['cards'][0]['median_m'] < m['cards'][1]['median_m'] < m['cards'][2]['median_m'] assert m['cards'][0]['near_m'] is None and m['cards'][-1]['far_m'] is None and m['cards'][0]['far_m'] == m['cards'][1]['near_m'] and m['cards'][0]['median_m'] < m['cards'][1]['median_m'] < m['cards'][2]['median_m']
for c in m['cards']: for c in m['cards']:
for kind in ('colour', 'geometry'): f = a / c[kind]['file']; assert f.stat().st_size == c[kind]['bytes'] and export.decode(f.read_bytes()).shape[:2] == (c['h'], WIN), c for kind in ('colour', 'geometry'): f = a / c[kind]['file']; assert f.stat().st_size == c[kind]['bytes'] and export.decode(f.read_bytes()).shape[:2] == (c['h'], WIN), c
bad = json.loads(json.dumps(m)); bad['place']['tz'] = 'Mars/Olympus'
try: export.validate(bad, export.SCHEMA['$defs']['manifest']); raise AssertionError('a zone the system does not know validated')
except ValueError as e: assert 'time zone' in str(e), e
assert m['bytes'] == sum(c[k]['bytes'] for c in m['cards'] for k in ('colour', 'geometry')) and m['encoding']['normal'] == 'rt8' and m['curvature'] == dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF) assert m['bytes'] == sum(c[k]['bytes'] for c in m['cards'] for k in ('colour', 'geometry')) and m['encoding']['normal'] == 'rt8' and m['curvature'] == dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF)
idx = json.load(open(d + '/a/index.json')); export.validate(idx, export.SCHEMA['$defs']['index']); assert idx == dict(schema=1, default='synthetic', places={'synthetic': a.name}) idx = json.load(open(d + '/a/index.json')); export.validate(idx, export.SCHEMA['$defs']['index']); assert idx == dict(schema=1, default='synthetic', places={'synthetic': a.name})
pk3 = [dict(c) for c in pk]; pk3[1]['geometry'] = pk3[1]['geometry'] + b'x'; assert export.bake_id([(c['colour'], c['geometry']) for c in pk3]) != export.bake_id([(c['colour'], c['geometry']) for c in pk]), 'a changed byte kept the bake_id' pk3 = [dict(c) for c in pk]; pk3[1]['geometry'] = pk3[1]['geometry'] + b'x'; assert export.bake_id([(c['colour'], c['geometry']) for c in pk3]) != export.bake_id([(c['colour'], c['geometry']) for c in pk]), 'a changed byte kept the bake_id'
@ -233,8 +236,13 @@ def test_card_cap_refusals():
try: ridge.load_preset('x', os.path.join(d, 'q.json')) try: ridge.load_preset('x', os.path.join(d, 'q.json'))
except ValueError: pass except ValueError: pass
else: assert False, 'a preset without card_split_km was defaulted' else: assert False, 'a preset without card_split_km was defaulted'
json.dump(dict(presets=[dict(id='x', card_split_km=[1, 2, 3, 4, 5])]), open(os.path.join(d, 'r.json'), 'w')); assert ridge.load_preset('x', os.path.join(d, 'r.json'))['card_split_km'] == [1, 2, 3, 4, 5] json.dump(dict(presets=[dict(id='x', tz='Europe/Vienna', card_split_km=[1, 2, 3, 4, 5])]), open(os.path.join(d, 'r.json'), 'w')); assert ridge.load_preset('x', os.path.join(d, 'r.json'))['card_split_km'] == [1, 2, 3, 4, 5]
place = dict(id='synthetic', name='S', lat=0.0, lon=0.0, altitude_km=0.0, eye_m=1.0); meta = dict(curvature=dict(r_earth_m=1.0, k_ref=0.1), encoding=dict(log_d_min=0.0, log_d_max=1.0), camera=dict(r_m=0.0, heading_max_deg=1.0)); view = dict(look_az_deg=0.0, plane_h=H, px_per_deg_h=1.0, px_per_deg_v=1.0, exaggeration=1.0, horizon_row=1.0, sky_row=1.0, near_row=1.0) for bad_tz in (None, '', 'Not/AZone'):
p = os.path.join(d, 'tz.json'); json.dump(dict(presets=[dict(id='x', card_split_km=[6], **({} if bad_tz is None else dict(tz=bad_tz)))]), open(p, 'w'))
try: ridge.load_preset('x', p)
except ValueError: pass
else: assert False, ('a preset with tz', bad_tz, 'was accepted')
place = dict(id='synthetic', name='S', lat=0.0, lon=0.0, altitude_km=0.0, eye_m=1.0, tz='UTC'); meta = dict(curvature=dict(r_earth_m=1.0, k_ref=0.1), encoding=dict(log_d_min=0.0, log_d_max=1.0), camera=dict(r_m=0.0, heading_max_deg=1.0)); view = dict(look_az_deg=0.0, plane_h=H, px_per_deg_h=1.0, px_per_deg_v=1.0, exaggeration=1.0, horizon_row=1.0, sky_row=1.0, near_row=1.0)
full = np.ones((H, WIN)) full = np.ones((H, WIN))
_refuses(d + '/four', dict(place=place, view=view, meta=meta, opaque=full), [_flat_card(0, H) for _ in range(4)], 'four full-frame cards (24.6 MB decoded) were written') _refuses(d + '/four', dict(place=place, view=view, meta=meta, opaque=full), [_flat_card(0, H) for _ in range(4)], 'four full-frame cards (24.6 MB decoded) were written')
ok = [_flat_card(0, H)] + [_flat_card(0, 150, seed=i) for i in range(1, 6)]; dest = export.write_bake(d + '/six', place, view, meta, ok, full); assert len(json.load(open(dest / 'manifest.json'))['cards']) == 6 ok = [_flat_card(0, H)] + [_flat_card(0, 150, seed=i) for i in range(1, 6)]; dest = export.write_bake(d + '/six', place, view, meta, ok, full); assert len(json.load(open(dest / 'manifest.json'))['cards']) == 6

View file

@ -50,8 +50,24 @@ callbacks and the creature sizing rule. Nothing has drawn a creature.
## Ridge scene: Vienna and the weather ## Ridge scene: Vienna and the weather
The ridge sky is the physical atmosphere (`ridge/earthAtmosphere.ts`) lit by the real sun over the viewpoint, 48.1929826 N, 16.3534237 E The ridge sky is the physical atmosphere (`ridge/earthAtmosphere.ts`) lit by the sun over the viewpoint (Vienna's is 48.1929826 N, 16.3534237 E, from the manifest).
(`ridge/vienna.ts`).
### The sky choice
The viewer's choice is Auto, one of six named moments (Dawn, Morning, Noon, Golden hour, Dusk, Night) or a free moment (a place-local date and
minute of the day). `ridge/skyMoment.ts` is the one owner of what it draws: `momentFor(choice, place, now)` returns the instant and `skyBand(elevation)`
turns the sun at that instant into day, dusk or night (day from 6 degrees up, night from 6 down), which the ink theme (`skyTheme.ts`, `skyInk.ts`), the
display budget (`ridge/toneMap.ts`) and the rebuild key (`skyForState.ts`) all read. Auto is the real sun over the loaded place now. A named moment is
today's at the place (Night tonight's: the solar midnight nearest, before the day's noon the one just passed or coming, after it the one coming), from the sun's elevation crossings of the place-local day (`SKY_MOMENTS`, one row each: dawn and dusk at -3 degrees, golden hour at
+4, morning at the lesser of 15 degrees and half the noon elevation, noon the day's maximum, night solar midnight). Place-local time comes only from
`place.tz`, the IANA zone the baker writes into the manifest (`scripts/ridge-bake/places.json`); the viewer's own zone decides nothing. Auto and the
named moments draw today's weather; a free moment draws a clear sky.
`skyState.ts` holds the stores (choice, place, constellation lines) and tells listeners; the choice persists in `ratatoskr.skyChoice`. The key
of the old four-state menu is read once by `skyState.ts` (Day became Noon) and removed. `skyPlace.ts` is the one writer of the place: a scene start loads the manifest of the configured place (nothing else fetches it, so a page with no scene fetches nothing) and the build
settles what it draws, the manifest's place when the cards load, `FALLBACK_VIEW`'s when they do not (a failed manifest, a card that will not decode), so the sky, the weather, the ink and the Auto
timer read the place that is drawn. Until a scene has settled it no sky is drawn for ink and the theme's own ink stands. The one timer (Auto, a named moment) tells listeners when the band
changes or a named moment's place-local day rolls over.
The weather is one number (`ridge/weather.ts`), from the page URL's `?weather=`, else `weather.json` beside `config.json`, else clear. The weather is one number (`ridge/weather.ts`), from the page URL's `?weather=`, else `weather.json` beside `config.json`, else clear.
The browser never calls a weather service. `weather.json` is written by Eureka's refresher (gamecult-ops `docs/weather-feed.md`, a 5-minute timer; the only writer) from GeoSphere Austria's TAWES station 11035 (Wien Hohe Warte), credit The browser never calls a weather service. `weather.json` is written by Eureka's refresher (gamecult-ops `docs/weather-feed.md`, a 5-minute timer; the only writer) from GeoSphere Austria's TAWES station 11035 (Wien Hohe Warte), credit

View file

@ -0,0 +1,173 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { SkyChoice } from './ridge/skyMoment';
import { FALLBACK_VIEW } from './ridge/view';
import {
MENU_CHOICES,
SkyMomentPicker,
SkyStateControl,
choiceLabel,
useNativeChange,
} from './SkyStateControl';
// The component's hooks are held still, as in RoomOutbox.actions.test.tsx: state is its initial value, refs are plain boxes, effects are
// kept to be run once the test has put an element in each ref. The element tree it returns is read and its native events are dispatched
// on a fake input, so no DOM is needed.
const held = vi.hoisted(() => ({
effects: [] as Array<() => unknown>,
choice: { kind: 'auto' } as unknown,
}));
vi.mock('react', async (importOriginal) => {
const actual = await importOriginal<typeof import('react')>();
const useState = (init: unknown) => [
typeof init === 'function' ? (init as () => unknown)() : init,
() => undefined,
];
const useRef = (init: unknown) => ({ current: init });
const useEffect = (fn: () => unknown) => {
held.effects.push(fn);
};
return {
...actual,
default: { ...actual, useState, useRef, useEffect },
useState,
useRef,
useEffect,
};
});
vi.mock('../../hooks/useSkyState', () => ({
useSkyChoice: () => held.choice,
useDrawnPlace: () => FALLBACK_VIEW.place,
}));
vi.mock('../../hooks/useClientConfig', () => ({ useClientConfig: () => ({}) }));
type El = { type?: unknown; ref?: unknown; props?: Record<string, unknown> };
/** Every element reachable through any prop (children, `content`, `after`). */
const walk = (node: unknown): El[] => {
if (Array.isArray(node)) return node.flatMap(walk);
if (node && typeof node === 'object' && 'props' in node) {
const el = node as El;
return [el, ...Object.values(el.props ?? {}).flatMap(walk)];
}
return [];
};
const textOf = (node: unknown): string => {
if (typeof node === 'string' || typeof node === 'number') return String(node);
if (Array.isArray(node)) return node.map(textOf).join('');
if (node && typeof node === 'object' && 'props' in node) {
return textOf((node as El).props?.children);
}
return '';
};
/** A stand-in input: a real EventTarget with a value. */
const fakeInput = (value: string) => Object.assign(new EventTarget(), { value });
const fire = (el: EventTarget, type: 'input' | 'change') => el.dispatchEvent(new Event(type));
beforeEach(() => {
held.effects.length = 0;
held.choice = { kind: 'auto' };
});
describe('the sky menu choices', () => {
const tree = () => walk(SkyStateControl());
const radios = () => tree().filter((e) => e.props?.role === 'menuitemradio');
it('lists Auto and the six named moments, then Pick a moment', () => {
expect(MENU_CHOICES.map(choiceLabel)).toEqual([
'Auto',
'Dawn',
'Morning',
'Noon',
'Golden hour',
'Dusk',
'Night',
]);
expect(radios().map((e) => textOf(e))).toEqual([
'Auto',
'Dawn',
'Morning',
'Noon',
'Golden hour',
'Dusk',
'Night',
'Pick a moment',
]);
});
it.each([
[{ kind: 'auto' }, 0],
[{ kind: 'named', id: 'dawn' }, 1],
[{ kind: 'named', id: 'night' }, 6],
[{ kind: 'free', date: '2026-12-21', minutes: 400 }, 7],
] as Array<[SkyChoice, number]>)('aria-checked follows the choice %j', (choice, checked) => {
held.choice = choice;
radios().forEach((e, i) => expect(e.props?.['aria-checked'], `item ${i}`).toBe(i === checked));
});
it("the button reads 'Sky: Auto', 'Sky: Dawn' or 'Sky: <date> <time>'", () => {
const label = () =>
tree().find((e) => e.props?.['aria-haspopup'] === 'menu')?.props?.['aria-label'];
expect(label()).toBe('Sky: Auto');
held.choice = { kind: 'named', id: 'dawn' };
expect(label()).toBe('Sky: Dawn');
held.choice = { kind: 'free', date: '2026-12-21', minutes: 6 * 60 + 40 };
expect(label()).toBe('Sky: 2026-12-21 06:40');
});
});
describe('committing on change, not on input', () => {
it('a native input event commits nothing and the change event commits once', () => {
const commits: string[] = [];
const ref = useNativeChange<HTMLInputElement>((el) => commits.push(el.value));
const target = fakeInput('600');
(ref as { current: unknown }).current = target;
held.effects.forEach((run) => run());
for (let i = 0; i < 5; i += 1) fire(target, 'input');
expect(commits).toEqual([]);
fire(target, 'change');
expect(commits).toEqual(['600']);
});
it('the picker commits the slider on release only, with the date it holds, and the date on change when it is a date in range', () => {
const commits: unknown[] = [];
const tree = walk(
SkyMomentPicker({
seed: { kind: 'free', date: '2026-12-21', minutes: 600 },
tz: 'Europe/Vienna',
onCommit: (c) => commits.push(c),
})
);
const input = (type: string) => tree.find((e) => e.type === 'input' && e.props?.type === type);
const date = fakeInput('2026-12-21');
const slider = fakeInput('600');
(input('date')?.ref as { current: unknown }).current = date;
(input('range')?.ref as { current: unknown }).current = slider;
held.effects.forEach((run) => run());
slider.value = '735';
fire(slider, 'input');
fire(slider, 'input');
expect(commits).toEqual([]);
fire(slider, 'change');
expect(commits).toEqual([{ kind: 'free', date: '2026-12-21', minutes: 735 }]);
date.value = '2026-07-15';
fire(date, 'change');
expect(commits[1]).toEqual({ kind: 'free', date: '2026-07-15', minutes: 735 });
date.value = '1800-01-01';
fire(date, 'change');
date.value = '';
fire(date, 'change');
expect(commits).toHaveLength(2);
expect(input('range')?.props).toMatchObject({ min: 0, max: 1439, step: 5 });
expect(input('date')?.props).toMatchObject({ min: '1900-01-01', max: '2100-12-31' });
});
it('the picker shows the place-local time and the zone beside the slider', () => {
const tree = SkyMomentPicker({
seed: { kind: 'free', date: '2026-12-21', minutes: 400 },
tz: 'Europe/Vienna',
onCommit: () => undefined,
});
expect(textOf(tree)).toMatch(/^06:40 \S+/);
});
});

View file

@ -1,4 +1,4 @@
import React, { MouseEventHandler, useEffect, useState } from 'react'; import React, { MouseEventHandler, useEffect, useRef, useState } from 'react';
import { import {
Box, Box,
config, config,
@ -13,8 +13,19 @@ import {
} from 'folds'; } from 'folds';
import FocusTrap from 'focus-trap-react'; import FocusTrap from 'focus-trap-react';
import { stopPropagation } from '../../utils/keyboard'; import { stopPropagation } from '../../utils/keyboard';
import { useSkyState } from '../../hooks/useSkyState'; import { useDrawnPlace, useSkyChoice } from '../../hooks/useSkyState';
import { SKY_STATES, pickSkyState, type SkyState } from './skyState'; import { pickSkyChoice, skyNow } from './skyState';
import {
FREE_DATE_MAX,
FREE_DATE_MIN,
MOMENT_IDS,
isDate,
seedFree,
zoneName,
zonedInstant,
} from './ridge/skyMoment';
import type { MomentId, SkyChoice } from './ridge/skyMoment';
import { FALLBACK_VIEW } from './ridge/view';
import { loadManifest } from './ridge/manifest'; import { loadManifest } from './ridge/manifest';
import { import {
LINES_CREDIT, LINES_CREDIT,
@ -27,36 +38,129 @@ import {
import { useClientConfig } from '../../hooks/useClientConfig'; import { useClientConfig } from '../../hooks/useClientConfig';
import { PhoneHit } from '../../styles/PhoneHit.css'; import { PhoneHit } from '../../styles/PhoneHit.css';
const LABEL: Record<SkyState, string> = { export const MOMENT_LABEL: Record<MomentId, string> = {
auto: 'Auto', dawn: 'Dawn',
day: 'Day', morning: 'Morning',
noon: 'Noon',
golden: 'Golden hour',
dusk: 'Dusk', dusk: 'Dusk',
night: 'Night', night: 'Night',
}; };
const hhmm = (minutes: number): string =>
`${String(Math.floor(minutes / 60)).padStart(2, '0')}:${String(minutes % 60).padStart(2, '0')}`;
/** What the button and the menu call a choice: Auto, the moment's name, or the free moment's place-local date and time. */
export const choiceLabel = (c: SkyChoice): string =>
c.kind === 'auto'
? 'Auto'
: c.kind === 'named'
? MOMENT_LABEL[c.id]
: `${c.date} ${hhmm(c.minutes)}`;
/** The choices the menu lists, in order. */
export const MENU_CHOICES: readonly SkyChoice[] = [
{ kind: 'auto' },
...MOMENT_IDS.map((id): SkyChoice => ({ kind: 'named', id })),
];
const sameChoice = (a: SkyChoice, b: SkyChoice): boolean => JSON.stringify(a) === JSON.stringify(b);
/** /**
* One title-bar button that opens the four sky states. A single button, not a row, so the bar * Run `onChange` on the element's native `change` event: for a slider, its release, not every `input` tick (React's onChange is the
* still fits a 320 px phone beside the search button; the menu items carry the state names. * input event). Each commit rebuilds the scene, so a drag must commit once.
*/
export function useNativeChange<T extends HTMLElement>(onChange: (el: T) => void) {
const ref = useRef<T>(null);
const latest = useRef(onChange);
latest.current = onChange;
useEffect(() => {
const el = ref.current;
if (!el) return undefined;
const handler = () => latest.current(el);
el.addEventListener('change', handler);
return () => el.removeEventListener('change', handler);
}, []);
return ref;
}
type Free = Extract<SkyChoice, { kind: 'free' }>;
/** A date and a time of day at the place, committed when each input changes (the slider on release), never per `input` tick. */
export function SkyMomentPicker({
seed,
tz,
onCommit,
}: {
seed: Free;
tz: string;
onCommit: (c: Free) => void;
}) {
const [minutes, setMinutes] = useState(seed.minutes);
const at = useRef({ date: seed.date, minutes: seed.minutes });
const dateRef = useNativeChange<HTMLInputElement>((el) => {
if (!isDate(el.value) || el.value < FREE_DATE_MIN || el.value > FREE_DATE_MAX) return;
at.current.date = el.value;
onCommit({ kind: 'free', ...at.current });
});
const sliderRef = useNativeChange<HTMLInputElement>((el) => {
at.current.minutes = Number(el.value);
onCommit({ kind: 'free', ...at.current });
});
const zone = zoneName(zonedInstant(at.current.date, minutes, tz), tz);
return (
<Box direction="Column" gap="100" style={{ padding: config.space.S200 }}>
<input
ref={dateRef}
type="date"
aria-label="Date"
min={FREE_DATE_MIN}
max={FREE_DATE_MAX}
defaultValue={seed.date}
/>
<input
ref={sliderRef}
type="range"
aria-label="Time of day"
min={0}
max={1439}
step={5}
defaultValue={seed.minutes}
onInput={(evt) => setMinutes(Number(evt.currentTarget.value))}
/>
<Text size="T200" priority="300">
{hhmm(minutes)} {zone}
</Text>
</Box>
);
}
/**
* One title-bar button that opens the sky choices: Auto, the six named moments of today at the place, and a free date and time. A single
* button, not a row, so the bar still fits a 320 px phone beside the search button; the menu items carry the names.
*/ */
export function SkyStateControl() { export function SkyStateControl() {
const state = useSkyState(); const choice = useSkyChoice();
const drawn = useDrawnPlace();
const [picking, setPicking] = useState(false);
const [cords, setCords] = useState<RectCords>(); const [cords, setCords] = useState<RectCords>();
const backgroundScene = useClientConfig().backgroundScene; const backgroundScene = useClientConfig().backgroundScene;
const place = backgroundScene?.place; const placeId = backgroundScene?.place;
const place = drawn ?? FALLBACK_VIEW.place;
const [credit, setCredit] = useState<string>(); const [credit, setCredit] = useState<string>();
const ridgeOn = !!backgroundScene && backgroundScene.style !== 'raymarch'; const ridgeOn = !!backgroundScene && backgroundScene.style !== 'raymarch';
useEffect(() => { useEffect(() => {
if (!ridgeOn) return undefined; if (!ridgeOn) return undefined;
let live = true; let live = true;
loadManifest(import.meta.env.BASE_URL, place).then( loadManifest(import.meta.env.BASE_URL, placeId).then(
(m) => live && setCredit(terrainCredit(m)), (m) => live && setCredit(terrainCredit(m)),
() => live && setCredit(undefined) () => live && setCredit(undefined)
); );
return () => { return () => {
live = false; live = false;
}; };
}, [ridgeOn, place]); }, [ridgeOn, placeId]);
const open: MouseEventHandler<HTMLButtonElement> = (evt) => { const open: MouseEventHandler<HTMLButtonElement> = (evt) => {
setCords(evt.currentTarget.getBoundingClientRect()); setCords(evt.currentTarget.getBoundingClientRect());
}; };
@ -71,34 +175,63 @@ export function SkyStateControl() {
focusTrapOptions={{ focusTrapOptions={{
initialFocus: '[aria-checked="true"]', initialFocus: '[aria-checked="true"]',
returnFocusOnDeactivate: true, returnFocusOnDeactivate: true,
onDeactivate: () => setCords(undefined), onDeactivate: () => {
setCords(undefined);
setPicking(false);
},
clickOutsideDeactivates: true, clickOutsideDeactivates: true,
isKeyForward: (evt: KeyboardEvent) => evt.key === 'ArrowDown', isKeyForward: (evt: KeyboardEvent) =>
isKeyBackward: (evt: KeyboardEvent) => evt.key === 'ArrowUp', evt.key === 'ArrowDown' && !(evt.target instanceof HTMLInputElement),
isKeyBackward: (evt: KeyboardEvent) =>
evt.key === 'ArrowUp' && !(evt.target instanceof HTMLInputElement),
escapeDeactivates: stopPropagation, escapeDeactivates: stopPropagation,
}} }}
> >
<Menu role="menu" aria-label="Sky"> <Menu role="menu" aria-label="Sky">
<Box direction="Column" gap="100" style={{ padding: config.space.S100 }}> <Box direction="Column" gap="100" style={{ padding: config.space.S100 }}>
{SKY_STATES.map((s) => ( {MENU_CHOICES.map((c) => {
const checked = sameChoice(c, choice);
return (
<MenuItem <MenuItem
key={s} key={choiceLabel(c)}
size="300" size="300"
variant="Surface" variant="Surface"
radii="300" radii="300"
role="menuitemradio" role="menuitemradio"
aria-checked={state === s} aria-checked={checked}
onClick={() => { onClick={() => {
pickSkyState(s); pickSkyChoice(c);
setCords(undefined); setCords(undefined);
}} }}
after={state === s ? <Icon size="100" src={Icons.Check} /> : undefined} after={checked ? <Icon size="100" src={Icons.Check} /> : undefined}
> >
<Box grow="Yes"> <Box grow="Yes">
<Text size="T300">{LABEL[s]}</Text> <Text size="T300">{choiceLabel(c)}</Text>
</Box> </Box>
</MenuItem> </MenuItem>
))} );
})}
<MenuItem
size="300"
variant="Surface"
radii="300"
role="menuitemradio"
aria-checked={choice.kind === 'free'}
aria-expanded={picking}
onClick={() => setPicking(!picking)}
after={choice.kind === 'free' ? <Icon size="100" src={Icons.Check} /> : undefined}
>
<Box grow="Yes">
<Text size="T300">Pick a moment</Text>
</Box>
</MenuItem>
{picking && (
<SkyMomentPicker
seed={seedFree(choice, place, skyNow())}
tz={place.tz}
onCommit={pickSkyChoice}
/>
)}
{ridgeOn && ( {ridgeOn && (
<Box <Box
direction="Column" direction="Column"
@ -136,8 +269,8 @@ export function SkyStateControl() {
<IconButton <IconButton
className={PhoneHit} className={PhoneHit}
variant="Background" variant="Background"
aria-label={`Sky: ${LABEL[state]}`} aria-label={`Sky: ${choiceLabel(choice)}`}
title={`Sky: ${LABEL[state]}`} title={`Sky: ${choiceLabel(choice)}`}
aria-haspopup="menu" aria-haspopup="menu"
aria-expanded={!!cords} aria-expanded={!!cords}
onClick={open} onClick={open}

View file

@ -1,8 +1,10 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { atStandardTime } from './standardTime.testkit'; import { atSolarTime } from './ridge/skyTestkit';
import type { Scene } from './Scene'; import type { Scene } from './Scene';
import { startBackgroundScene } from './index'; import { startBackgroundScene } from './index';
import { pickSkyState, setSkyClock, setSkyState } from './skyState'; import { getResolvedSkyState, getSkyPlace, pickSkyChoice, setSkyChoice, setSkyClock, setSkyPlace, subscribe } from './skyState';
import { skyBand } from './ridge/skyMoment';
import type { SkyChoice } from './ridge/skyMoment';
import { ridgeSkyFor } from './skyForState'; import { ridgeSkyFor } from './skyForState';
import { forgetManifests } from './ridge/manifest'; import { forgetManifests } from './ridge/manifest';
import { wireIndex, wireManifest } from './ridge/manifest.fixture'; import { wireIndex, wireManifest } from './ridge/manifest.fixture';
@ -30,14 +32,19 @@ vi.mock('./skyForState', async (importOriginal) => {
...actual, ...actual,
ridgeSkyFor: (...args: Parameters<typeof actual.ridgeSkyFor>) => { ridgeSkyFor: (...args: Parameters<typeof actual.ridgeSkyFor>) => {
const [state, view] = args; const [state, view] = args;
// One bake per state and place; the view is the one owner of the place, so it is part of what a sky is. // One bake per choice and place; the view is the one owner of the place, so it is part of what a sky is.
const key = `${state}@${JSON.stringify(view.place)}`; const key = `${JSON.stringify(state)}@${JSON.stringify(view.place)}`;
if (!baked.has(key)) baked.set(key, actual.ridgeSkyFor(...args)); if (!baked.has(key)) baked.set(key, actual.ridgeSkyFor(...args));
return baked.get(key) as ReturnType<typeof actual.ridgeSkyFor>; return baked.get(key) as ReturnType<typeof actual.ridgeSkyFor>;
}, },
}; };
}); });
const AUTO: SkyChoice = { kind: 'auto' };
const NOON: SkyChoice = { kind: 'named', id: 'noon' };
const DUSK: SkyChoice = { kind: 'named', id: 'dusk' };
const NIGHT: SkyChoice = { kind: 'named', id: 'night' };
const canvas = {} as HTMLCanvasElement; const canvas = {} as HTMLCanvasElement;
const config = { tier: 'low' as const }; const config = { tier: 'low' as const };
const caps = { hardwareConcurrency: 8 }; const caps = { hardwareConcurrency: 8 };
@ -84,17 +91,22 @@ const fakeScene = () => ({ login: vi.fn(), dispose: vi.fn() });
const hex = (c: readonly number[]) => `#${c.map((v) => v.toString(16).padStart(2, '0')).join('')}`; const hex = (c: readonly number[]) => `#${c.map((v) => v.toString(16).padStart(2, '0')).join('')}`;
beforeEach(() => { beforeEach(() => {
vi.stubGlobal('localStorage', { getItem: () => null, setItem: () => undefined }); vi.stubGlobal('localStorage', {
getItem: () => null,
setItem: () => undefined,
removeItem: () => undefined,
});
// Local midnight: 'auto' resolves to night. // Local midnight: 'auto' resolves to night.
setSkyClock(() => atStandardTime(0, 0)); setSkyClock(() => atSolarTime(0, 0));
setSkyState('auto'); setSkyChoice(AUTO);
setSkyPlace(FALLBACK_VIEW.place);
createRidgeScene.mockReset(); createRidgeScene.mockReset();
createScene.mockReset(); createScene.mockReset();
loadBackdrop.mockReset(); loadBackdrop.mockReset();
}); });
afterEach(() => { afterEach(() => {
setSkyClock(); setSkyClock();
setSkyState('auto'); setSkyChoice(AUTO);
vi.unstubAllGlobals(); vi.unstubAllGlobals();
}); });
@ -104,28 +116,31 @@ describe('startBackgroundScene follows the sky state', () => {
const scene = await startBackgroundScene(config, caps, { canvas }); const scene = await startBackgroundScene(config, caps, { canvas });
expect(createRidgeScene).toHaveBeenCalledOnce(); expect(createRidgeScene).toHaveBeenCalledOnce();
expect(hex(createRidgeScene.mock.calls[0][0].sky.top)).toBe( expect(hex(createRidgeScene.mock.calls[0][0].sky.top)).toBe(
hex(ridgeSkyFor('night', FALLBACK_VIEW).top) hex(ridgeSkyFor(AUTO, FALLBACK_VIEW).top)
); );
scene?.dispose(); scene?.dispose();
}); });
it('does not rebuild when auto is replaced by the explicit state it already resolves to', async () => { it('rebuilds when Auto is replaced by the named moment of the same band: live and frozen are different skies, and the same pick again is not a rebuild', async () => {
const a = fakeScene(); const [a, b] = [fakeScene(), fakeScene()];
createRidgeScene.mockReturnValueOnce(a); createRidgeScene.mockReturnValueOnce(a).mockReturnValueOnce(b);
const scene = await startBackgroundScene(config, caps, { canvas }); const scene = await startBackgroundScene(config, caps, { canvas });
setSkyState('night'); setSkyChoice(NIGHT);
await flush(); await flush();
expect(a.dispose).not.toHaveBeenCalled(); expect(a.dispose).toHaveBeenCalledOnce();
expect(createRidgeScene).toHaveBeenCalledOnce(); expect(createRidgeScene).toHaveBeenCalledTimes(2);
setSkyChoice(NIGHT);
await flush();
expect(createRidgeScene).toHaveBeenCalledTimes(2);
scene?.dispose(); scene?.dispose();
}); });
it('starts on the stored state', async () => { it('starts on the stored state', async () => {
setSkyState('night'); setSkyChoice(NIGHT);
createRidgeScene.mockReturnValue(fakeScene()); createRidgeScene.mockReturnValue(fakeScene());
const scene = await startBackgroundScene(config, caps, { canvas }); const scene = await startBackgroundScene(config, caps, { canvas });
expect(hex(createRidgeScene.mock.calls[0][0].sky.top)).toBe( expect(hex(createRidgeScene.mock.calls[0][0].sky.top)).toBe(
hex(ridgeSkyFor('night', FALLBACK_VIEW).top) hex(ridgeSkyFor(NIGHT, FALLBACK_VIEW).top)
); );
scene?.dispose(); scene?.dispose();
}); });
@ -135,11 +150,11 @@ describe('startBackgroundScene follows the sky state', () => {
const second = fakeScene(); const second = fakeScene();
createRidgeScene.mockReturnValueOnce(first).mockReturnValueOnce(second); createRidgeScene.mockReturnValueOnce(first).mockReturnValueOnce(second);
const scene = await startBackgroundScene(config, caps, { canvas }); const scene = await startBackgroundScene(config, caps, { canvas });
setSkyState('day'); setSkyChoice(NOON);
await flush(); await flush();
expect(first.dispose).toHaveBeenCalledOnce(); expect(first.dispose).toHaveBeenCalledOnce();
expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe( expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe(
hex(ridgeSkyFor('day', FALLBACK_VIEW).top) hex(ridgeSkyFor(NOON, FALLBACK_VIEW).top)
); );
scene?.dispose(); scene?.dispose();
expect(second.dispose).toHaveBeenCalledOnce(); expect(second.dispose).toHaveBeenCalledOnce();
@ -149,12 +164,12 @@ describe('startBackgroundScene follows the sky state', () => {
const [a, b] = [fakeScene(), fakeScene()]; const [a, b] = [fakeScene(), fakeScene()];
createRidgeScene.mockReturnValueOnce(a).mockReturnValueOnce(b); createRidgeScene.mockReturnValueOnce(a).mockReturnValueOnce(b);
const started = startBackgroundScene(config, caps, { canvas }); const started = startBackgroundScene(config, caps, { canvas });
setSkyState('day'); setSkyChoice(NOON);
const scene = await started; const scene = await started;
await flush(); await flush();
expect(createRidgeScene).toHaveBeenCalledTimes(2); expect(createRidgeScene).toHaveBeenCalledTimes(2);
expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe( expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe(
hex(ridgeSkyFor('day', FALLBACK_VIEW).top) hex(ridgeSkyFor(NOON, FALLBACK_VIEW).top)
); );
expect(a.dispose).toHaveBeenCalledOnce(); expect(a.dispose).toHaveBeenCalledOnce();
scene?.dispose(); scene?.dispose();
@ -165,12 +180,12 @@ describe('startBackgroundScene follows the sky state', () => {
const [a, b, c] = [fakeScene(), fakeScene(), fakeScene()]; const [a, b, c] = [fakeScene(), fakeScene(), fakeScene()];
createRidgeScene.mockReturnValueOnce(a).mockReturnValueOnce(b).mockReturnValueOnce(c); createRidgeScene.mockReturnValueOnce(a).mockReturnValueOnce(b).mockReturnValueOnce(c);
const scene = await startBackgroundScene(config, caps, { canvas }); const scene = await startBackgroundScene(config, caps, { canvas });
setSkyState('day'); setSkyChoice(NOON);
await flush(); await flush();
expect(b.login).not.toHaveBeenCalled(); expect(b.login).not.toHaveBeenCalled();
scene?.login(); scene?.login();
expect(b.login).toHaveBeenCalledOnce(); expect(b.login).toHaveBeenCalledOnce();
setSkyState('dusk'); setSkyChoice(DUSK);
await flush(); await flush();
expect(c.login).toHaveBeenCalledOnce(); expect(c.login).toHaveBeenCalledOnce();
scene?.dispose(); scene?.dispose();
@ -183,11 +198,11 @@ describe('startBackgroundScene follows the sky state', () => {
const onActive = vi.fn(); const onActive = vi.fn();
const scene = await startBackgroundScene(config, caps, { canvas, onInactive, onActive }); const scene = await startBackgroundScene(config, caps, { canvas, onInactive, onActive });
expect(onInactive).not.toHaveBeenCalled(); expect(onInactive).not.toHaveBeenCalled();
setSkyState('day'); setSkyChoice(NOON);
await flush(); await flush();
expect(onInactive).toHaveBeenCalledOnce(); expect(onInactive).toHaveBeenCalledOnce();
expect(onActive).not.toHaveBeenCalled(); expect(onActive).not.toHaveBeenCalled();
setSkyState('dusk'); setSkyChoice(DUSK);
await flush(); await flush();
expect(onActive).toHaveBeenCalledOnce(); expect(onActive).toHaveBeenCalledOnce();
expect(onInactive).toHaveBeenCalledOnce(); expect(onInactive).toHaveBeenCalledOnce();
@ -198,7 +213,7 @@ describe('startBackgroundScene follows the sky state', () => {
createRidgeScene.mockReturnValueOnce(fakeScene()).mockReturnValueOnce(null); createRidgeScene.mockReturnValueOnce(fakeScene()).mockReturnValueOnce(null);
const onInactive = vi.fn(); const onInactive = vi.fn();
const scene = await startBackgroundScene(config, caps, { canvas, onInactive }); const scene = await startBackgroundScene(config, caps, { canvas, onInactive });
setSkyState('day'); setSkyChoice(NOON);
scene?.dispose(); scene?.dispose();
await flush(); await flush();
expect(onInactive).not.toHaveBeenCalled(); expect(onInactive).not.toHaveBeenCalled();
@ -210,7 +225,7 @@ describe('startBackgroundScene follows the sky state', () => {
const scene = await startBackgroundScene(config, caps, { canvas }); const scene = await startBackgroundScene(config, caps, { canvas });
scene?.dispose(); scene?.dispose();
scene?.dispose(); scene?.dispose();
setSkyState('day'); setSkyChoice(NOON);
await flush(); await flush();
expect(createRidgeScene).toHaveBeenCalledOnce(); expect(createRidgeScene).toHaveBeenCalledOnce();
expect(first.dispose).toHaveBeenCalledOnce(); expect(first.dispose).toHaveBeenCalledOnce();
@ -219,7 +234,7 @@ describe('startBackgroundScene follows the sky state', () => {
it('builds nothing for a rebuild that is disposed before it starts', async () => { it('builds nothing for a rebuild that is disposed before it starts', async () => {
createRidgeScene.mockReturnValueOnce(fakeScene()).mockReturnValueOnce(fakeScene()); createRidgeScene.mockReturnValueOnce(fakeScene()).mockReturnValueOnce(fakeScene());
const scene = await startBackgroundScene(config, caps, { canvas }); const scene = await startBackgroundScene(config, caps, { canvas });
setSkyState('day'); setSkyChoice(NOON);
scene?.dispose(); scene?.dispose();
await flush(); await flush();
expect(createRidgeScene).toHaveBeenCalledOnce(); expect(createRidgeScene).toHaveBeenCalledOnce();
@ -229,13 +244,13 @@ describe('startBackgroundScene follows the sky state', () => {
const scenes = [fakeScene(), fakeScene(), fakeScene()]; const scenes = [fakeScene(), fakeScene(), fakeScene()];
scenes.forEach((s) => createRidgeScene.mockReturnValueOnce(s)); scenes.forEach((s) => createRidgeScene.mockReturnValueOnce(s));
const scene = await startBackgroundScene(config, caps, { canvas }); const scene = await startBackgroundScene(config, caps, { canvas });
setSkyState('day'); setSkyChoice(NOON);
setSkyState('dusk'); setSkyChoice(DUSK);
await flush(); await flush();
// The sky last built is dusk's, and it is the live scene: a login reaches it and nothing else. // The sky last built is dusk's, and it is the live scene: a login reaches it and nothing else.
const built = createRidgeScene.mock.calls.length; const built = createRidgeScene.mock.calls.length;
expect(hex(createRidgeScene.mock.calls[built - 1][0].sky.top)).toBe( expect(hex(createRidgeScene.mock.calls[built - 1][0].sky.top)).toBe(
hex(ridgeSkyFor('dusk', FALLBACK_VIEW).top) hex(ridgeSkyFor(DUSK, FALLBACK_VIEW).top)
); );
const live = scenes[built - 1]; const live = scenes[built - 1];
scene?.login(); scene?.login();
@ -253,13 +268,13 @@ describe('startBackgroundScene follows the sky state', () => {
createRidgeScene.mockReturnValueOnce(fakeScene()).mockReturnValueOnce(fakeScene()); createRidgeScene.mockReturnValueOnce(fakeScene()).mockReturnValueOnce(fakeScene());
createRidgeScene.mockReturnValue(fakeScene()); createRidgeScene.mockReturnValue(fakeScene());
const scene = await startBackgroundScene(config, caps, { canvas }); const scene = await startBackgroundScene(config, caps, { canvas });
setSkyState('day'); setSkyChoice(NOON);
setSkyState('dusk'); setSkyChoice(DUSK);
await flush(); await flush();
// The initial build and one rebuild, for dusk; day's rebuild stood down before building anything. // The initial build and one rebuild, for dusk; day's rebuild stood down before building anything.
expect(createRidgeScene).toHaveBeenCalledTimes(2); expect(createRidgeScene).toHaveBeenCalledTimes(2);
expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe( expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe(
hex(ridgeSkyFor('dusk', FALLBACK_VIEW).top) hex(ridgeSkyFor(DUSK, FALLBACK_VIEW).top)
); );
scene?.dispose(); scene?.dispose();
}); });
@ -268,19 +283,19 @@ describe('startBackgroundScene follows the sky state', () => {
// change finished loading, was found stale and was never made (so it never showed or spoke), and only the newest sky was announced. // change finished loading, was found stale and was never made (so it never showed or spoke), and only the newest sky was announced.
const changeAfter = async (ticks: number) => { const changeAfter = async (ticks: number) => {
createRidgeScene.mockReset(); createRidgeScene.mockReset();
setSkyState('auto'); setSkyChoice(AUTO);
const [a, b, c] = [fakeScene(), fakeScene(), fakeScene()]; const [a, b, c] = [fakeScene(), fakeScene(), fakeScene()];
createRidgeScene.mockReturnValueOnce(a).mockReturnValueOnce(b).mockReturnValueOnce(c); createRidgeScene.mockReturnValueOnce(a).mockReturnValueOnce(b).mockReturnValueOnce(c);
const onActive = vi.fn(); const onActive = vi.fn();
const scene = await startBackgroundScene(config, caps, { canvas, onActive }); const scene = await startBackgroundScene(config, caps, { canvas, onActive });
setSkyState('day'); setSkyChoice(NOON);
await microtasks(ticks); await microtasks(ticks);
setSkyState('dusk'); setSkyChoice(DUSK);
await flush(); await flush();
const at = `at ${ticks} microtasks`; const at = `at ${ticks} microtasks`;
const built = createRidgeScene.mock.calls.length; const built = createRidgeScene.mock.calls.length;
expect(hex(createRidgeScene.mock.calls[built - 1][0].sky.top), at).toBe( expect(hex(createRidgeScene.mock.calls[built - 1][0].sky.top), at).toBe(
hex(ridgeSkyFor('dusk', FALLBACK_VIEW).top) hex(ridgeSkyFor(DUSK, FALLBACK_VIEW).top)
); );
// The newest build is live, every earlier one disposed exactly once, and only the live one is shown. // The newest build is live, every earlier one disposed exactly once, and only the live one is shown.
const live = [a, b, c][built - 1]; const live = [a, b, c][built - 1];
@ -313,7 +328,7 @@ describe('startBackgroundScene follows the sky state', () => {
createScene.mockReturnValue(inner); createScene.mockReturnValue(inner);
const scene = await startBackgroundScene({ ...config, style: 'raymarch' }, caps, { canvas }); const scene = await startBackgroundScene({ ...config, style: 'raymarch' }, caps, { canvas });
expect(scene).toBe(inner); expect(scene).toBe(inner);
setSkyState('day'); setSkyChoice(NOON);
await flush(); await flush();
expect(createScene).toHaveBeenCalledOnce(); expect(createScene).toHaveBeenCalledOnce();
}); });
@ -380,6 +395,89 @@ describe('the ridge planes', () => {
expect(createRidgeScene.mock.calls[1][0].backdrop.manifest.view.place.id).toBe('vienna'); expect(createRidgeScene.mock.calls[1][0].backdrop.manifest.view.place.id).toBe('vienna');
}); });
it("makes the manifest's place the sky's place, so the ink and the scene read one place; a failed load makes it the drawn fallback's", async () => {
served();
loader();
createRidgeScene.mockReturnValue(fakeScene());
setSkyPlace(undefined);
(await startBackgroundScene({ ...config, place: 'graz' }, caps, { canvas }))?.dispose();
expect(getSkyPlace()?.id).toBe('graz');
expect(getSkyPlace()?.tz).toBe('Europe/Vienna');
forgetManifests();
vi.stubGlobal(
'fetch',
vi.fn(async () => ({ ok: false, status: 404, json: async () => ({}) }))
);
setSkyPlace(undefined);
(await startBackgroundScene(config, caps, { canvas }))?.dispose();
expect(getSkyPlace()).toEqual(FALLBACK_VIEW.place);
});
it('a manifest that fails to load: the ink follows the drawn fallback sky, and Auto still ticks', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async () => ({ ok: false, status: 404, json: async () => ({}) }))
);
createRidgeScene.mockReturnValue(fakeScene());
setSkyPlace(undefined);
setSkyChoice(NOON);
const scene = await startBackgroundScene(config, caps, { canvas });
try {
const opts = createRidgeScene.mock.calls[0][0];
expect(opts.sky.physical.view).toBe(FALLBACK_VIEW);
expect(getSkyPlace()).toEqual(FALLBACK_VIEW.place);
expect(getResolvedSkyState()).toBe('day');
expect(getResolvedSkyState()).toBe(skyBand(opts.sky.physical.sun.elevation));
} finally {
scene?.dispose();
}
// Auto crosses dusk with the place the fallback scene drew.
setSkyChoice(AUTO);
vi.useFakeTimers();
try {
let now = atSolarTime(17, 0);
setSkyClock(() => now);
const heard = vi.fn();
const off = subscribe(heard);
now = atSolarTime(18, 10);
vi.advanceTimersByTime(60_000);
expect(heard).toHaveBeenCalledWith('dusk');
off();
} finally {
vi.useRealTimers();
}
});
it('cards that fail on a place that is not the fallback: the sky and the ink are at the one place, the fallback', async () => {
const fuji = {
...(wireManifest() as any).place,
id: 'fuji',
lat: 35.36,
lon: 138.73,
tz: 'Asia/Tokyo',
};
served({ '/public/ridge/vienna-abc123abc123/manifest.json': wireManifest({ place: fuji }) });
const { ctl } = loader();
ctl.fail = true;
createRidgeScene.mockReturnValue(fakeScene());
setSkyPlace(undefined);
setSkyChoice(NOON);
const scene = await startBackgroundScene(config, caps, { canvas });
try {
const opts = createRidgeScene.mock.calls[0][0];
expect(opts.backdrop).toBeUndefined();
expect(opts.sky.physical.view).toBe(FALLBACK_VIEW);
expect(getSkyPlace()).toEqual(FALLBACK_VIEW.place);
expect(getResolvedSkyState()).toBe(skyBand(opts.sky.physical.sun.elevation));
// The next key, made before the next build, is for the view that is drawn: the place does not flip back to the manifest's.
setSkyChoice(DUSK);
await flush();
expect(getSkyPlace()).toEqual(FALLBACK_VIEW.place);
} finally {
scene?.dispose();
}
});
const skyOnly = async (onPlanesFail = vi.fn(), onCompileFail = vi.fn()) => { const skyOnly = async (onPlanesFail = vi.fn(), onCompileFail = vi.fn()) => {
createRidgeScene.mockReturnValue(fakeScene()); createRidgeScene.mockReturnValue(fakeScene());
const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onCompileFail }); const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onCompileFail });
@ -420,7 +518,7 @@ describe('the ridge cards failing', () => {
const onCompileFail = vi.fn(); const onCompileFail = vi.fn();
const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onCompileFail }); const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onCompileFail });
expect(createRidgeScene.mock.calls[0][0].backdrop).toBeUndefined(); expect(createRidgeScene.mock.calls[0][0].backdrop).toBeUndefined();
setSkyState('day'); setSkyChoice(NOON);
await flush(); await flush();
expect(createRidgeScene).toHaveBeenCalledTimes(2); expect(createRidgeScene).toHaveBeenCalledTimes(2);
expect(onPlanesFail).toHaveBeenCalledOnce(); expect(onPlanesFail).toHaveBeenCalledOnce();
@ -448,7 +546,7 @@ describe('the ridge cards and the live scene', () => {
const onPlanesFail = vi.fn(); const onPlanesFail = vi.fn();
const onPlanesOk = vi.fn(); const onPlanesOk = vi.fn();
const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onPlanesOk }); const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onPlanesOk });
setSkyState('day'); setSkyChoice(NOON);
await flush(); await flush();
expect(createRidgeScene).toHaveBeenCalledTimes(2); expect(createRidgeScene).toHaveBeenCalledTimes(2);
expect(createRidgeScene.mock.calls.every((c) => c[0].backdrop)).toBe(true); expect(createRidgeScene.mock.calls.every((c) => c[0].backdrop)).toBe(true);
@ -463,12 +561,12 @@ describe('the ridge cards and the live scene', () => {
createRidgeScene.mockReturnValue(fakeScene()); createRidgeScene.mockReturnValue(fakeScene());
const scene = await startBackgroundScene(config, caps, { canvas }); const scene = await startBackgroundScene(config, caps, { canvas });
expect(ctl.calls.map((s) => s.state)).toEqual(['night']); expect(ctl.calls.map((s) => s.state)).toEqual(['night']);
setSkyState('night'); // the sky already drawn: no rebuild, no lighting setSkyChoice(NOON);
await flush();
expect(ctl.calls).toHaveLength(1);
setSkyState('day');
await flush(); await flush();
expect(ctl.calls.map((s) => s.state)).toEqual(['night', 'day']); expect(ctl.calls.map((s) => s.state)).toEqual(['night', 'day']);
setSkyChoice(NOON); // the sky already drawn: no rebuild, no lighting
await flush();
expect(ctl.calls).toHaveLength(2);
expect(createRidgeScene.mock.calls[1][0].sky.physical).toBe(ctl.calls[1]); expect(createRidgeScene.mock.calls[1][0].sky.physical).toBe(ctl.calls[1]);
expect(createRidgeScene.mock.calls[1][0].backdrop.manifest.view.place.id).toBe('vienna'); expect(createRidgeScene.mock.calls[1][0].backdrop.manifest.view.place.id).toBe('vienna');
scene?.dispose(); scene?.dispose();
@ -480,16 +578,17 @@ describe('the ridge cards and the live scene', () => {
createRidgeScene.mockReturnValue(fakeScene()); createRidgeScene.mockReturnValue(fakeScene());
const scene = await startBackgroundScene(config, caps, { canvas }); const scene = await startBackgroundScene(config, caps, { canvas });
expect(createRidgeScene.mock.calls[0][0].lines).toBe(false); expect(createRidgeScene.mock.calls[0][0].lines).toBe(false);
pickSkyState('night'); // from Auto: a choice, the same sky pickSkyChoice(NIGHT); // from Auto: a choice, a frozen sky
await flush();
expect(createRidgeScene).toHaveBeenCalledTimes(1);
pickSkyState('night'); // re-picked: the lines
await flush(); await flush();
expect(createRidgeScene).toHaveBeenCalledTimes(2); expect(createRidgeScene).toHaveBeenCalledTimes(2);
expect(createRidgeScene.mock.calls[1][0].lines).toBe(true); expect(createRidgeScene.mock.calls[1][0].lines).toBe(false);
pickSkyState('night'); pickSkyChoice(NIGHT); // re-picked: the lines
await flush(); await flush();
expect(createRidgeScene.mock.calls[2][0].lines).toBe(false); expect(createRidgeScene).toHaveBeenCalledTimes(3);
expect(createRidgeScene.mock.calls[2][0].lines).toBe(true);
pickSkyChoice(NIGHT);
await flush();
expect(createRidgeScene.mock.calls[3][0].lines).toBe(false);
scene?.dispose(); scene?.dispose();
}); });
@ -508,20 +607,21 @@ describe('the ridge cards and the live scene', () => {
scene?.dispose(); scene?.dispose();
}); });
it("keys a rebuild by the manifest's place: the same sky state over a rebaked place rebuilds", async () => { it("keys a rebuild by the manifest's place: the same sky over a rebaked place rebuilds", async () => {
serve(); serve();
loader(); loader();
const [a, b] = [fakeScene(), fakeScene()]; const [a, b] = [fakeScene(), fakeScene()];
createRidgeScene.mockReturnValueOnce(a).mockReturnValueOnce(b); createRidgeScene.mockReturnValueOnce(a).mockReturnValueOnce(b);
const w = wireManifest() as any; const w = wireManifest() as any;
setSkyChoice(NIGHT);
const scene = await startBackgroundScene(config, caps, { canvas }); const scene = await startBackgroundScene(config, caps, { canvas });
// 'auto' at midnight and 'night' are one sky: no rebuild, while the place is the one drawn. // The same choice, told again while the place is the one drawn: no rebuild.
setSkyState('night'); setSkyPlace(undefined);
await flush(); await flush();
expect(createRidgeScene).toHaveBeenCalledOnce(); expect(createRidgeScene).toHaveBeenCalledOnce();
forgetManifests(); forgetManifests();
serve({ ...w, place: { ...w.place, id: 'graz' } }); serve({ ...w, place: { ...w.place, id: 'graz' } });
setSkyState('auto'); setSkyPlace(undefined);
await flush(); await flush();
expect(createRidgeScene).toHaveBeenCalledTimes(2); expect(createRidgeScene).toHaveBeenCalledTimes(2);
expect(createRidgeScene.mock.calls[1][0].backdrop.manifest.view.place.id).toBe('graz'); expect(createRidgeScene.mock.calls[1][0].backdrop.manifest.view.place.id).toBe('graz');
@ -563,7 +663,7 @@ describe('the ridge cards and the live scene', () => {
const at = (p: { lat: number; lon: number }) => const at = (p: { lat: number; lon: number }) =>
weatherFromFile( weatherFromFile(
file, file,
sunAt({ id: 'x', altitudeKm: 0, ...p }, new Date(Date.parse(wx.observed_at) - 5 * 60_000)) sunAt({ id: 'x', altitudeKm: 0, tz: 'UTC', ...p }, new Date(Date.parse(wx.observed_at) - 5 * 60_000))
.elevation .elevation
); );
expect(at(FALLBACK_VIEW.place)).not.toBe(at(place)); expect(at(FALLBACK_VIEW.place)).not.toBe(at(place));
@ -591,7 +691,7 @@ describe('the ridge cards and the live scene', () => {
const onActive = vi.fn(); const onActive = vi.fn();
const scene = await startBackgroundScene(config, caps, { canvas, onActive }); const scene = await startBackgroundScene(config, caps, { canvas, onActive });
d.ctl.hold = true; d.ctl.hold = true;
setSkyState('day'); setSkyChoice(NOON);
await flush(); await flush();
expect(d.ctl.pending.length).toBeGreaterThan(0); expect(d.ctl.pending.length).toBeGreaterThan(0);
expect(first.dispose).not.toHaveBeenCalled(); expect(first.dispose).not.toHaveBeenCalled();
@ -616,7 +716,7 @@ describe('the ridge cards and the live scene', () => {
const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail }); const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail });
d.ctl.hold = true; d.ctl.hold = true;
d.ctl.fail = true; d.ctl.fail = true;
setSkyState('day'); setSkyChoice(NOON);
await flush(); await flush();
scene?.dispose(); scene?.dispose();
await d.release(); await d.release();
@ -632,10 +732,10 @@ describe('the ridge cards and the live scene', () => {
const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail }); const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail });
d.ctl.hold = true; d.ctl.hold = true;
d.ctl.fail = true; d.ctl.fail = true;
setSkyState('day'); // stale: its decodes will reject setSkyChoice(NOON); // stale: its decodes will reject
await flush(); await flush();
d.ctl.fail = false; d.ctl.fail = false;
setSkyState('dusk'); // the live one: its decodes will succeed setSkyChoice(DUSK); // the live one: its decodes will succeed
await flush(); await flush();
const stale = d.ctl.pending.splice(0, 1); const stale = d.ctl.pending.splice(0, 1);
d.ctl.pending.length = 0; d.ctl.pending.length = 0;
@ -657,10 +757,10 @@ describe('the ridge cards and the live scene', () => {
const onActive = vi.fn(); const onActive = vi.fn();
const scene = await startBackgroundScene(config, caps, { canvas, onActive }); const scene = await startBackgroundScene(config, caps, { canvas, onActive });
d.ctl.hold = true; d.ctl.hold = true;
setSkyState('day'); // stale: its decodes are held until after the newer build is live setSkyChoice(NOON); // stale: its decodes are held until after the newer build is live
await flush(); await flush();
const dayDecodes = d.ctl.pending.splice(0); const dayDecodes = d.ctl.pending.splice(0);
setSkyState('dusk'); setSkyChoice(DUSK);
await flush(); await flush();
const duskDecodes = d.ctl.pending.splice(0); const duskDecodes = d.ctl.pending.splice(0);
expect(dayDecodes.length).toBeGreaterThan(0); expect(dayDecodes.length).toBeGreaterThan(0);
@ -690,7 +790,7 @@ describe('the ridge cards and the live scene', () => {
const onActive = vi.fn(); const onActive = vi.fn();
const scene = await startBackgroundScene(config, caps, { canvas, onActive }); const scene = await startBackgroundScene(config, caps, { canvas, onActive });
d.ctl.hold = true; d.ctl.hold = true;
setSkyState('day'); setSkyChoice(NOON);
await flush(); await flush();
scene?.dispose(); scene?.dispose();
await d.release(); await d.release();
@ -707,7 +807,7 @@ describe('the ridge cards and the live scene', () => {
const onInactive = vi.fn(); const onInactive = vi.fn();
const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onInactive }); const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onInactive });
d.ctl.fail = true; d.ctl.fail = true;
setSkyState('day'); setSkyChoice(NOON);
await flush(); await flush();
expect(onInactive).toHaveBeenCalledOnce(); expect(onInactive).toHaveBeenCalledOnce();
expect(onPlanesFail).not.toHaveBeenCalled(); expect(onPlanesFail).not.toHaveBeenCalled();
@ -723,17 +823,17 @@ describe('the ridge cards and the live scene', () => {
const onPlanesOk = vi.fn(); const onPlanesOk = vi.fn();
const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onPlanesOk }); const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onPlanesOk });
expect(onPlanesFail).toHaveBeenCalledOnce(); expect(onPlanesFail).toHaveBeenCalledOnce();
setSkyState('day'); // still failing: the host is not told twice setSkyChoice(NOON); // still failing: the host is not told twice
await flush(); await flush();
expect(onPlanesFail).toHaveBeenCalledOnce(); expect(onPlanesFail).toHaveBeenCalledOnce();
expect(onPlanesOk).not.toHaveBeenCalled(); expect(onPlanesOk).not.toHaveBeenCalled();
d.ctl.fail = false; d.ctl.fail = false;
setSkyState('dusk'); setSkyChoice(DUSK);
await flush(); await flush();
expect(onPlanesOk).toHaveBeenCalledOnce(); expect(onPlanesOk).toHaveBeenCalledOnce();
expect(createRidgeScene.mock.calls[2][0].backdrop).toBeDefined(); expect(createRidgeScene.mock.calls[2][0].backdrop).toBeDefined();
d.ctl.fail = true; d.ctl.fail = true;
setSkyState('night'); setSkyChoice(NIGHT);
await flush(); await flush();
expect(onPlanesFail).toHaveBeenCalledTimes(2); expect(onPlanesFail).toHaveBeenCalledTimes(2);
scene?.dispose(); scene?.dispose();

View file

@ -1,12 +1,11 @@
import type { Scene, SceneOptions } from './Scene'; import type { Scene, SceneOptions } from './Scene';
import { BackgroundSceneConfig, Capabilities, SceneTier, resolveTier } from './tier'; import { BackgroundSceneConfig, Capabilities, SceneTier, resolveTier } from './tier';
import { debugOverlaysAllowed } from './debugOverlays'; import { debugOverlaysAllowed } from './debugOverlays';
import { getConstellationLines, getSkyState, subscribe } from './skyState'; import { getConstellationLines, getSkyChoice, subscribe } from './skyState';
import type { SkyState } from './skyState'; import type { SkyChoice } from './ridge/skyMoment';
import { drawnView, ensureSkyPlace, resetSkyPlanes } from './skyPlace';
import type { SkyColours } from './ridge/skyColour'; import type { SkyColours } from './ridge/skyColour';
import type { Backdrop } from './ridge/Backdrop'; import type { Backdrop } from './ridge/Backdrop';
import { loadManifest } from './ridge/manifest';
import type { RidgeManifest } from './ridge/manifest';
import { FALLBACK_VIEW } from './ridge/view'; import { FALLBACK_VIEW } from './ridge/view';
export type { Scene, SceneStats } from './Scene'; export type { Scene, SceneStats } from './Scene';
@ -15,7 +14,7 @@ export type { SceneStyle, SceneTier } from './tier';
export type StartOptions = Omit<SceneOptions, 'tier' | 'patchSource' | 'onCompileFail'> & { export type StartOptions = Omit<SceneOptions, 'tier' | 'patchSource' | 'onCompileFail'> & {
/** A shader failed to compile, or the scene chunk failed to load. The host keeps its ground. */ /** A shader failed to compile, or the scene chunk failed to load. The host keeps its ground. */
onCompileFail?: (e: Error) => void; onCompileFail?: (e: Error) => void;
/** A rebuild for a new sky state made no scene: the host puts the CSS ground back (as on a lost context). */ /** A rebuild for a new sky made no scene: the host puts the CSS ground back (as on a lost context). */
onInactive?: () => void; onInactive?: () => void;
/** A rebuild made a scene again: the host lets it show. */ /** A rebuild made a scene again: the host lets it show. */
onActive?: () => void; onActive?: () => void;
@ -28,20 +27,6 @@ export type StartOptions = Omit<SceneOptions, 'tier' | 'patchSource' | 'onCompil
/** The observation file the ridge sky reads: the page's own, beside config.json. The browser calls no weather service. */ /** The observation file the ridge sky reads: the page's own, beside config.json. The browser calls no weather service. */
const weatherUrl = (): string => `${import.meta.env.BASE_URL.replace(/\/$/, '')}/weather.json`; const weatherUrl = (): string => `${import.meta.env.BASE_URL.replace(/\/$/, '')}/weather.json`;
/**
* The baked place's manifest, or why there is none. Its View is the one owner of the sun's place and the camera for the weather, the sky,
* the rebuild key and the planes; a scene with no manifest has FALLBACK_VIEW.
*/
async function manifestOf(
config: BackgroundSceneConfig | undefined
): Promise<{ manifest: RidgeManifest | null; fail: Error | null }> {
try {
return { manifest: await loadManifest(import.meta.env.BASE_URL, config?.place), fail: null };
} catch (e) {
return { manifest: null, fail: e instanceof Error ? e : new Error(String(e)) };
}
}
/** A scene made ready: every await is done, so `make` is synchronous and a rebuild can keep the old scene until the instant it swaps. */ /** A scene made ready: every await is done, so `make` is synchronous and a rebuild can keep the old scene until the instant it swaps. */
interface Prepared { interface Prepared {
make: () => Scene | null; make: () => Scene | null;
@ -52,7 +37,7 @@ interface Prepared {
async function prepare( async function prepare(
config: BackgroundSceneConfig | undefined, config: BackgroundSceneConfig | undefined,
options: StartOptions & { tier: SceneTier; debug?: boolean }, options: StartOptions & { tier: SceneTier; debug?: boolean },
state: SkyState choice: SkyChoice
): Promise<Prepared> { ): Promise<Prepared> {
// Whatever throws in making the scene is a compile failure, as whatever throws in loading it. // Whatever throws in making the scene is a compile failure, as whatever throws in loading it.
const guarded = (make: () => Scene | null): Prepared => ({ const guarded = (make: () => Scene | null): Prepared => ({
@ -74,33 +59,35 @@ async function prepare(
return guarded(() => createScene(options)); return guarded(() => createScene(options));
} }
const { createRidgeScene } = await import('./ridge/Ridge'); const { createRidgeScene } = await import('./ridge/Ridge');
const { manifest, fail } = await manifestOf(config); const { manifest, fail } = await ensureSkyPlace(config);
await loadWeather(weatherUrl(), (manifest?.view ?? FALLBACK_VIEW).place); await loadWeather(weatherUrl(), (manifest?.view ?? FALLBACK_VIEW).place);
// The cards load with the scene chunk and the weather, and are lit here for this sky (once per build: a sky change comes through a rebuild, never per // The cards load with the scene chunk and the weather, and are lit here for this sky (once per build: a sky change comes through a rebuild, never per
// frame), so createRidgeScene stays synchronous. Any failure, a missing WebGL2 included, is the sky alone. // frame), so createRidgeScene stays synchronous. Any failure, a missing WebGL2 included, is the sky alone, over the view the store is told of.
let backdrop: Backdrop | null = null; let backdrop: Backdrop | null = null;
let sky: SkyColours | undefined; let lit: SkyColours | undefined;
let planesFail: Error | null = fail; let planesFail: Error | null = fail;
if (manifest) { if (manifest) {
try { try {
const manifestSky = ridgeSkyFor(state, manifest.view); const manifestSky = ridgeSkyFor(choice, manifest.view);
sky = manifestSky;
const { loadBackdrop } = await import('./ridge/Backdrop'); const { loadBackdrop } = await import('./ridge/Backdrop');
backdrop = await loadBackdrop( backdrop = await loadBackdrop(
manifest, manifest,
manifestSky.physical as NonNullable<typeof manifestSky.physical> manifestSky.physical as NonNullable<typeof manifestSky.physical>
); );
if (!backdrop) throw new Error('ridge cards did not load'); if (!backdrop) throw new Error('ridge cards did not load');
lit = manifestSky;
} catch (e) { } catch (e) {
backdrop = null; backdrop = null;
sky = undefined;
planesFail = e instanceof Error ? e : new Error(String(e)); planesFail = e instanceof Error ? e : new Error(String(e));
} }
} }
const view = drawnView(backdrop ? manifest : null);
if (!lit) await loadWeather(weatherUrl(), view.place);
const sky = lit ?? ridgeSkyFor(choice, view);
const made = guarded(() => const made = guarded(() =>
createRidgeScene({ createRidgeScene({
...options, ...options,
sky: sky ?? ridgeSkyFor(state, FALLBACK_VIEW), sky,
backdrop: backdrop ?? undefined, backdrop: backdrop ?? undefined,
lines: getConstellationLines(), lines: getConstellationLines(),
}) })
@ -114,17 +101,17 @@ async function prepare(
/** /**
* What a rebuild is for: the sky options the scene would be built from. A change of choice that draws the same sky * What a rebuild is for: the sky options the scene would be built from. A change of choice that draws the same sky
* (Day picked while the clock says day, 'auto' to the fixed state it resolves to) is not a rebuild. * (Auto picked as a named moment it already is drawing) is not a rebuild.
*/ */
async function skyKey( async function skyKey(
config: BackgroundSceneConfig | undefined, config: BackgroundSceneConfig | undefined,
state: SkyState choice: SkyChoice
): Promise<string | null> { ): Promise<string | null> {
try { try {
const { loadWeather, ridgeSkyKey } = await import('./skyForState'); const { loadWeather, ridgeSkyKey } = await import('./skyForState');
const view = (await manifestOf(config)).manifest?.view ?? FALLBACK_VIEW; const { view } = await ensureSkyPlace(config);
await loadWeather(weatherUrl(), view.place); await loadWeather(weatherUrl(), view.place);
return ridgeSkyKey(state, view); return ridgeSkyKey(choice, view);
} catch { } catch {
// The chunk failed to load: no key, so every change rebuilds (and `create` reports the failure). // The chunk failed to load: no key, so every change rebuilds (and `create` reports the failure).
return null; return null;
@ -138,7 +125,7 @@ async function skyKey(
* "keep the CSS ground", including when that chunk fails to load (offline, stale deploy): the * "keep the CSS ground", including when that chunk fails to load (offline, stale deploy): the
* failure goes to onCompileFail and nothing throws. * failure goes to onCompileFail and nothing throws.
* *
* The ridge scene bakes its sky once, so it follows the sky (`skyState.ts`: the choice, resolved, so 'auto' follows the clock) by * The ridge scene bakes its sky once, so it follows the sky (`skyState.ts`: the choice at the place, so Auto follows the clock) by
* being rebuilt on the same canvas when it changes: the door subscribes on start and the returned * being rebuilt on the same canvas when it changes: the door subscribes on start and the returned
* scene's `dispose` unsubscribes. The pull-back restarts from the tree; a later `login()` is * scene's `dispose` unsubscribes. The pull-back restarts from the tree; a later `login()` is
* replayed on the new scene. The ray-march scene has one fixed dusk and ignores the state. * replayed on the new scene. The ray-march scene has one fixed dusk and ignores the state.
@ -158,10 +145,11 @@ export async function startBackgroundScene(
if (!planesFail && planesFailed) options.onPlanesOk?.(); if (!planesFail && planesFailed) options.onPlanesOk?.();
planesFailed = planesFail !== null; planesFailed = planesFail !== null;
}; };
const prepared = (state: SkyState) => prepare(config, { ...options, tier, debug }, state); const prepared = (choice: SkyChoice) => prepare(config, { ...options, tier, debug }, choice);
const state = getSkyState(); resetSkyPlanes();
const key0 = config?.style === 'raymarch' ? null : await skyKey(config, state); const choice = getSkyChoice();
const firstReady = await prepared(state); const key0 = config?.style === 'raymarch' ? null : await skyKey(config, choice);
const firstReady = await prepared(choice);
const first = firstReady.make(); const first = firstReady.make();
if (!first || config?.style === 'raymarch') return first; if (!first || config?.style === 'raymarch') return first;
announce(firstReady.planesFail); announce(firstReady.planesFail);
@ -174,9 +162,9 @@ export async function startBackgroundScene(
// A rebuild is for a different sky ('auto' crossing a boundary, a new choice), not for a repeat of the one drawn. // A rebuild is for a different sky ('auto' crossing a boundary, a new choice), not for a repeat of the one drawn.
const rebuild = async () => { const rebuild = async () => {
// The choice can move while the key is awaited; that change has its own rebuild, so this one stands down. // The choice can move while the key is awaited; that change has its own rebuild, so this one stands down.
const next = getSkyState(); const next = getSkyChoice();
const key = await skyKey(config, next); const key = await skyKey(config, next);
if (getSkyState() !== next) return; if (getSkyChoice() !== next) return;
if ((key !== null && key === built) || disposed) return; if ((key !== null && key === built) || disposed) return;
generation += 1; generation += 1;
const mine = generation; const mine = generation;

View file

@ -6,6 +6,7 @@ import type { SkyColours } from './skyColour';
import { nightBodies } from './nightBodies'; import { nightBodies } from './nightBodies';
import { sunAt } from './sunAt'; import { sunAt } from './sunAt';
import { makePhysicalSky, paintSky as paintPhysicalSky } from './physicalSky'; import { makePhysicalSky, paintSky as paintPhysicalSky } from './physicalSky';
import { sunOfBand } from './skyTestkit';
import { startBackgroundScene } from '../index'; import { startBackgroundScene } from '../index';
import { parseManifest } from './manifest'; import { parseManifest } from './manifest';
import { ELSEWHERE_VIEW, wireManifest } from './manifest.fixture'; import { ELSEWHERE_VIEW, wireManifest } from './manifest.fixture';
@ -283,7 +284,7 @@ describe('createRidgeScene', () => {
it("paints the sky through the camera of the physical sky's own View, not a default one", () => { it("paints the sky through the camera of the physical sky's own View, not a default one", () => {
const { canvas } = host(); const { canvas } = host();
const physical = makePhysicalSky('day', new Date('2026-06-21T10:40:00Z'), 0, ELSEWHERE_VIEW); const physical = makePhysicalSky(sunOfBand(ELSEWHERE_VIEW.place, 'day', new Date('2026-06-21T10:40:00Z')), 0, ELSEWHERE_VIEW);
const s = createRidgeScene({ canvas, tier: 'full', sky: { ...DAY, physical } })!; const s = createRidgeScene({ canvas, tier: 'full', sky: { ...DAY, physical } })!;
const want = paintPhysicalSky(physical, 400, 800, windowFor(ELSEWHERE_VIEW, 400, 800).camera); const want = paintPhysicalSky(physical, 400, 800, windowFor(ELSEWHERE_VIEW, 400, 800).camera);
expect(painted).toHaveLength(1); expect(painted).toHaveLength(1);
@ -385,7 +386,7 @@ describe('the starfield in the scene', () => {
const count = (kind: string) => draws.filter((d) => d === kind).length; const count = (kind: string) => draws.filter((d) => d === kind).length;
// A moonless-horizon night over Vienna (the moon is 17 degrees below it): the real stars of that moment, and no moon to count as an arc. // A moonless-horizon night over Vienna (the moon is 17 degrees below it): the real stars of that moment, and no moon to count as an arc.
const t = new Date('2026-12-04T00:00:00Z'); const t = new Date('2026-12-04T00:00:00Z');
const physical = makePhysicalSky('night', t, 0, FALLBACK_VIEW, sunAt(FALLBACK_VIEW.place, t)); const physical = makePhysicalSky(sunAt(FALLBACK_VIEW.place, t), 0, FALLBACK_VIEW);
const night: SkyColours = { ...DAY, physical }; const night: SkyColours = { ...DAY, physical };
const N = nightBodies( const N = nightBodies(
physical, physical,
@ -503,7 +504,7 @@ describe('the starfield in the scene', () => {
describe('rain in the scene', () => { describe('rain in the scene', () => {
const rainy = (w: number): SkyColours => ({ const rainy = (w: number): SkyColours => ({
...DAY, ...DAY,
physical: makePhysicalSky('day', new Date('2026-06-21T10:40:00Z'), w, FALLBACK_VIEW), physical: makePhysicalSky(sunOfBand(FALLBACK_VIEW.place, 'day', new Date('2026-06-21T10:40:00Z')), w, FALLBACK_VIEW),
}); });
const rainEls = (parent: any) => parent.children.filter((c: any) => c.tag === 'div'); const rainEls = (parent: any) => parent.children.filter((c: any) => c.tag === 'div');
@ -558,7 +559,7 @@ describe('the ridge cards in the scene', () => {
top: [10, 14, 40], top: [10, 14, 40],
mid: [30, 34, 80], mid: [30, 34, 80],
horizon: [60, 50, 90], horizon: [60, 50, 90],
physical: makePhysicalSky('night', new Date('2026-06-21T22:40:00Z'), 1, FALLBACK_VIEW), physical: makePhysicalSky(sunOfBand(FALLBACK_VIEW.place, 'night', new Date('2026-06-21T22:40:00Z')), 1, FALLBACK_VIEW),
}; };
const rigOf = (parent: any) => const rigOf = (parent: any) =>
parent.children.find((c: any) => c.children.some((g: any) => g.anims.length)); parent.children.find((c: any) => c.children.some((g: any) => g.anims.length));

View file

@ -18,6 +18,7 @@ export const wireManifest = (
lat: 48.19, lat: 48.19,
lon: 16.35, lon: 16.35,
altitude_km: 0.183, altitude_km: 0.183,
tz: 'Europe/Vienna',
eye_m: 1.7, eye_m: 1.7,
}, },
view: { view: {
@ -66,7 +67,7 @@ export const wireIndex = {
/** A View that differs from FALLBACK_VIEW in every field the sky reads (place, altitude, look azimuth, window, horizon row), so a test can tell the two apart. */ /** A View that differs from FALLBACK_VIEW in every field the sky reads (place, altitude, look azimuth, window, horizon row), so a test can tell the two apart. */
export const ELSEWHERE_VIEW: View = { export const ELSEWHERE_VIEW: View = {
place: { id: 'elsewhere', lat: -33.9, lon: 151.2, altitudeKm: 1.5 }, place: { id: 'elsewhere', lat: -33.9, lon: 151.2, altitudeKm: 1.5, tz: 'Australia/Sydney' },
lookAzDeg: 20, lookAzDeg: 20,
windowDeg: 90, windowDeg: 90,
planeW: 1600, planeW: 1600,

View file

@ -15,7 +15,13 @@ describe('parseManifest', () => {
pxPerDegV: 177.8, // not px_per_deg_h: a real bake's two differ 10x pxPerDegV: 177.8, // not px_per_deg_h: a real bake's two differ 10x
horizonRow: 314.5, horizonRow: 314.5,
}); });
expect(m.view.place).toEqual({ id: 'vienna', lat: 48.19, lon: 16.35, altitudeKm: 0.183 }); expect(m.view.place).toEqual({
id: 'vienna',
lat: 48.19,
lon: 16.35,
altitudeKm: 0.183,
tz: 'Europe/Vienna',
});
expect(m.encoding).toEqual({ logDMin: 4.6, logDMax: 11.5 }); expect(m.encoding).toEqual({ logDMin: 4.6, logDMax: 11.5 });
expect(m.camera).toEqual({ headingMaxDeg: 23 }); expect(m.camera).toEqual({ headingMaxDeg: 23 });
expect(m.cards.map((c) => c.scale)).toEqual([1.2, 1.0167, 1.005]); expect(m.cards.map((c) => c.scale)).toEqual([1.2, 1.0167, 1.005]);
@ -70,6 +76,13 @@ describe('parseManifest', () => {
expect(() => parseManifest(null, '/')).toThrow(); expect(() => parseManifest(null, '/')).toThrow();
}); });
it('rejects a manifest without place.tz and one naming a zone Intl does not know', () => {
const w = wireManifest() as any;
expect(() => parseManifest({ ...w, place: { ...w.place, tz: undefined } }, '/')).toThrow(/place\.tz/);
expect(() => parseManifest({ ...w, place: { ...w.place, tz: 'Not/AZone' } }, '/')).toThrow(/place\.tz/);
expect(parseManifest({ ...w, place: { ...w.place, tz: 'Asia/Kathmandu' } }, '/').view.place.tz).toBe('Asia/Kathmandu');
});
it('never echoes a value it refused', () => { it('never echoes a value it refused', () => {
const w = wireManifest() as any; const w = wireManifest() as any;
const refusal = (bad: unknown) => { const refusal = (bad: unknown) => {

View file

@ -52,6 +52,17 @@ const num = (x: unknown, path: string): number =>
const str = (x: unknown, path: string): string => const str = (x: unknown, path: string): string =>
typeof x === 'string' ? x : fail(path, 'not a string'); typeof x === 'string' ? x : fail(path, 'not a string');
/** An IANA zone name Intl knows (the one place besides skyMoment.ts that touches Intl.DateTimeFormat). */
const zone = (x: unknown, path: string): string => {
const tz = str(x, path);
try {
new Intl.DateTimeFormat('en-US', { timeZone: tz });
} catch {
fail(path, `unknown time zone ${tz}`);
}
return tz;
};
export function parseIndex(raw: unknown): RidgeIndex { export function parseIndex(raw: unknown): RidgeIndex {
const r = rec(raw, 'index'); const r = rec(raw, 'index');
if (r.schema !== 1) fail('index.schema', 'must be 1'); if (r.schema !== 1) fail('index.schema', 'must be 1');
@ -107,6 +118,7 @@ export function parseManifest(raw: unknown, dir: string): RidgeManifest {
lat: num(p.lat, 'place.lat'), lat: num(p.lat, 'place.lat'),
lon: num(p.lon, 'place.lon'), lon: num(p.lon, 'place.lon'),
altitudeKm: num(p.altitude_km, 'place.altitude_km'), altitudeKm: num(p.altitude_km, 'place.altitude_km'),
tz: zone(p.tz, 'place.tz'),
}, },
lookAzDeg: num(v.look_az_deg, 'view.look_az_deg'), lookAzDeg: num(v.look_az_deg, 'view.look_az_deg'),
windowDeg: num(v.window_deg, 'view.window_deg'), windowDeg: num(v.window_deg, 'view.window_deg'),

View file

@ -13,7 +13,7 @@ const camera: Camera = { azimuthDeg: 180, hfovDeg: 340, vfovDeg: 170, horizonAt:
const sky = (iso: string, state: 'day' | 'dusk' | 'night' = 'night') => { const sky = (iso: string, state: 'day' | 'dusk' | 'night' = 'night') => {
const t = new Date(iso); const t = new Date(iso);
return makePhysicalSky(state, t, 0, FALLBACK_VIEW, sunAt(P, t)); return makePhysicalSky(sunAt(P, t), 0, FALLBACK_VIEW);
}; };
const bodies = (iso: string, state: 'day' | 'dusk' | 'night' = 'night', lines = false) => { const bodies = (iso: string, state: 'day' | 'dusk' | 'night' = 'night', lines = false) => {
const p = sky(iso, state); const p = sky(iso, state);
@ -134,7 +134,7 @@ describe('the stars under the figures', () => {
const { linesAt } = await import('./starCatalogue'); const { linesAt } = await import('./starCatalogue');
const cam = windowFor(FALLBACK_VIEW, 1100, 619).camera; const cam = windowFor(FALLBACK_VIEW, 1100, 619).camera;
const t = new Date('2026-11-25T00:00:00Z'); // full moon, high in the south const t = new Date('2026-11-25T00:00:00Z'); // full moon, high in the south
const p = makePhysicalSky('night', t, 0, FALLBACK_VIEW, sunAt(P, t)); const p = makePhysicalSky(sunAt(P, t), 0, FALLBACK_VIEW);
const nb = nightBodies(p, paintSky(p, 1100, 619, cam), false); const nb = nightBodies(p, paintSky(p, 1100, 619, cam), false);
let vertices = 0; let vertices = 0;
let carried = 0; let carried = 0;

View file

@ -1,10 +1,12 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { FALLBACK_VIEW } from './view'; import { FALLBACK_VIEW } from './view';
import { ELSEWHERE_VIEW } from './manifest.fixture'; import { ELSEWHERE_VIEW } from './manifest.fixture';
import { sunForState } from './sunAt'; import { sunAt } from './sunAt';
import { momentFor } from './skyMoment';
import { makePhysicalSky, paintSky } from './physicalSky'; import { makePhysicalSky, paintSky } from './physicalSky';
import { sunOfBand } from './skyTestkit';
import { ridgeDrawn } from '../skyForState'; import { ridgeDrawn } from '../skyForState';
import type { FixedSkyState } from '../skyState'; import type { FixedSkyState } from './skyMoment';
import { windowFor } from './view'; import { windowFor } from './view';
import type { PhysicalSky } from './physicalSky'; import type { PhysicalSky } from './physicalSky';
@ -43,7 +45,7 @@ describe.each(['day', 'dusk', 'night'] as FixedSkyState[])(
let hi = -1; let hi = -1;
for (const day of DAYS) { for (const day of DAYS) {
for (const w of WEATHER) { for (const w of WEATHER) {
const sky = makePhysicalSky(state, new Date(`${day}T10:40:00Z`), w, FALLBACK_VIEW); const sky = makePhysicalSky(sunOfBand(FALLBACK_VIEW.place, state, new Date(`${day}T10:40:00Z`)), w, FALLBACK_VIEW);
for (const [vw, vh] of VIEWPORTS) { for (const [vw, vh] of VIEWPORTS) {
const px = paintSky(sky, vw, vh, camera(sky, vw, vh)); const px = paintSky(sky, vw, vh, camera(sky, vw, vh));
for (let i = 0; i < px.w * px.h * 4; i += 4) { for (let i = 0; i < px.w * px.h * 4; i += 4) {
@ -64,7 +66,7 @@ describe('weather in the sky', () => {
it('overcast is cloud: less blue and less contrast than clear air at the same sun', () => { it('overcast is cloud: less blue and less contrast than clear air at the same sun', () => {
const at = new Date('2026-06-21T10:40:00Z'); const at = new Date('2026-06-21T10:40:00Z');
const paint = (w: number) => { const paint = (w: number) => {
const sky = makePhysicalSky('day', at, w, FALLBACK_VIEW); const sky = makePhysicalSky(sunOfBand(FALLBACK_VIEW.place, 'day', at), w, FALLBACK_VIEW);
return paintSky(sky, 640, 360, camera(sky, 640, 360)); return paintSky(sky, 640, 360, camera(sky, 640, 360));
}; };
const clear = paint(0); const clear = paint(0);
@ -92,7 +94,7 @@ describe('the sun disc', () => {
const disc = (sky: PhysicalSky) => paintSky(sky, 1280, 720, facingSun(sky, 1280, 720)); const disc = (sky: PhysicalSky) => paintSky(sky, 1280, 720, facingSun(sky, 1280, 720));
const noon = new Date('2026-12-21T11:00:00Z'); // about 18 degrees: higher suns are above the top of the window const noon = new Date('2026-12-21T11:00:00Z'); // about 18 degrees: higher suns are above the top of the window
it('is drawn by the host, in a clear sky by day, white with the sun high', () => { it('is drawn by the host, in a clear sky by day, white with the sun high', () => {
const sky = makePhysicalSky('day', noon, 0, FALLBACK_VIEW); const sky = makePhysicalSky(sunOfBand(FALLBACK_VIEW.place, 'day', noon), 0, FALLBACK_VIEW);
const d = disc(sky).sunDisc; const d = disc(sky).sunDisc;
expect(d).toBeDefined(); expect(d).toBeDefined();
expect(d!.x).toBeGreaterThan(0); expect(d!.x).toBeGreaterThan(0);
@ -103,11 +105,12 @@ describe('the sun disc', () => {
expect(Math.min(...d!.rgb)).toBeGreaterThan(150); // a warm white at 21 degrees expect(Math.min(...d!.rgb)).toBeGreaterThan(150); // a warm white at 21 degrees
}); });
it('is hidden by overcast and absent at night', () => { it('is hidden by overcast and absent at night', () => {
expect(disc(makePhysicalSky('day', noon, 0.7, FALLBACK_VIEW)).sunDisc).toBeUndefined(); expect(disc(makePhysicalSky(sunOfBand(FALLBACK_VIEW.place, 'day', noon), 0.7, FALLBACK_VIEW)).sunDisc).toBeUndefined();
expect(disc(makePhysicalSky('night', noon, 0, FALLBACK_VIEW)).sunDisc).toBeUndefined(); expect(disc(makePhysicalSky(sunOfBand(FALLBACK_VIEW.place, 'night', noon), 0, FALLBACK_VIEW)).sunDisc).toBeUndefined();
}); });
it('is orange-tinted low in the sky', () => { it('is orange-tinted low in the sky (golden hour, 4 degrees up)', () => {
const d = disc(makePhysicalSky('dusk', noon, 0, FALLBACK_VIEW)).sunDisc; const golden = momentFor({ kind: 'named', id: 'golden' }, FALLBACK_VIEW.place, noon);
const d = disc(makePhysicalSky(sunAt(FALLBACK_VIEW.place, golden), 0, FALLBACK_VIEW)).sunDisc;
expect(d).toBeDefined(); expect(d).toBeDefined();
expect(d!.rgb[0]).toBeGreaterThan(d!.rgb[2]); expect(d!.rgb[0]).toBeGreaterThan(d!.rgb[2]);
}); });
@ -118,16 +121,16 @@ describe('the sky is made from the View it is given', () => {
const sameSpotOtherCamera = { ...FALLBACK_VIEW, lookAzDeg: 30, windowDeg: 100, horizonRow: 200 }; const sameSpotOtherCamera = { ...FALLBACK_VIEW, lookAzDeg: 30, windowDeg: 100, horizonRow: 200 };
it("lights the sky from the sun over the View's place, at its altitude", () => { it("lights the sky from the sun over the View's place, at its altitude", () => {
const sky = makePhysicalSky('day', NOW, 0, ELSEWHERE_VIEW); const sky = makePhysicalSky(sunOfBand(ELSEWHERE_VIEW.place, 'day', NOW), 0, ELSEWHERE_VIEW);
expect(sky.view).toBe(ELSEWHERE_VIEW); expect(sky.view).toBe(ELSEWHERE_VIEW);
expect(sky.sun).toEqual(sunForState(ELSEWHERE_VIEW.place, 'day', NOW)); expect(sky.sun).toEqual(sunOfBand(ELSEWHERE_VIEW.place, 'day', NOW));
expect(sky.sun).not.toEqual(sunForState(FALLBACK_VIEW.place, 'day', NOW)); expect(sky.sun).not.toEqual(sunAt(FALLBACK_VIEW.place, sunOfBand(ELSEWHERE_VIEW.place, 'day', NOW).time));
expect(sky.atm.observerKm).toBe(ELSEWHERE_VIEW.place.altitudeKm); expect(sky.atm.observerKm).toBe(ELSEWHERE_VIEW.place.altitudeKm);
}); });
it("fits and samples the stops through the View's camera: the same place and sun with another look is another gradient", () => { it("fits and samples the stops through the View's camera: the same place and sun with another look is another gradient", () => {
const a = makePhysicalSky('day', NOW, 0, FALLBACK_VIEW); const a = makePhysicalSky(sunOfBand(FALLBACK_VIEW.place, 'day', NOW), 0, FALLBACK_VIEW);
const b = makePhysicalSky('day', NOW, 0, sameSpotOtherCamera); const b = makePhysicalSky(sunOfBand(sameSpotOtherCamera.place, 'day', NOW), 0, sameSpotOtherCamera);
expect(b.sun).toEqual(a.sun); expect(b.sun).toEqual(a.sun);
expect(b.stops).not.toEqual(a.stops); expect(b.stops).not.toEqual(a.stops);
}); });

View file

@ -1,7 +1,8 @@
// The ridge scene's sky: the View's place's sun on the real clock, the atmosphere baked from it, a camera, and the display that makes it // The ridge scene's sky: the sun over the View's place at the drawn moment, the atmosphere baked from it, a camera, and the display that makes it
// pixels. `makePhysicalSky` does the one expensive thing (the LUT bake, tens of ms) and fits the display from a fixed 16:9 // pixels. `makePhysicalSky` does the one expensive thing (the LUT bake, tens of ms) and fits the display from a fixed 16:9
// grid, so resizing the window repaints the same sky. `paintSky` is per-texel lookups only. // grid, so resizing the window repaints the same sky. `paintSky` is per-texel lookups only.
import type { FixedSkyState } from '../skyState'; import { skyBand } from './skyMoment';
import type { FixedSkyState } from './skyMoment';
import { bakeAtmosphere } from './earthAtmosphere'; import { bakeAtmosphere } from './earthAtmosphere';
import type { Atmosphere } from './earthAtmosphere'; import type { Atmosphere } from './earthAtmosphere';
import { domeSize, renderDome, SUN_RADIUS, sunOnScreen } from './skyDome'; import { domeSize, renderDome, SUN_RADIUS, sunOnScreen } from './skyDome';
@ -11,7 +12,6 @@ import { display8, fitDisplay } from './toneMap';
import type { Display, Fit } from './toneMap'; import type { Display, Fit } from './toneMap';
import { moonAt } from './nightSky'; import { moonAt } from './nightSky';
import type { MoonSample, NightLight } from './nightSky'; import type { MoonSample, NightLight } from './nightSky';
import { sunForState } from './sunAt';
import type { SunSample } from './sunAt'; import type { SunSample } from './sunAt';
import { windowFor } from './view'; import { windowFor } from './view';
import type { Camera, View } from './view'; import type { Camera, View } from './view';
@ -55,16 +55,10 @@ export function rowMean(dome: Dome, display: Display, row: number): Srgb {
return [Math.round(acc[0] / dome.w), Math.round(acc[1] / dome.w), Math.round(acc[2] / dome.w)]; return [Math.round(acc[0] / dome.w), Math.round(acc[1] / dome.w), Math.round(acc[2] / dome.w)];
} }
export function makePhysicalSky( /** The sky lit by the sun it is given (the moment is skyMoment.ts's choice); the display budget is the band of that sun. */
state: FixedSkyState, export function makePhysicalSky(sun: SunSample, weatherValue: number, view: View): PhysicalSky {
now: Date,
weatherValue: number,
view: View,
/** A sun to draw instead of the state's own (the look sheet's grid of elevations); `state` still picks the display budget. */
sunOverride?: SunSample
): PhysicalSky {
const t0 = clock(); const t0 = clock();
const sun = sunOverride ?? sunForState(view.place, state, now); const state = skyBand(sun.elevation);
const weather = weatherOf(weatherValue); const weather = weatherOf(weatherValue);
const atm = bakeAtmosphere({ const atm = bakeAtmosphere({
sunElevationDeg: sun.elevation, sunElevationDeg: sun.elevation,

View file

@ -120,6 +120,12 @@ describe('the committed ridge assets', () => {
expect(dir.endsWith(`-${raw.bake_id}`)).toBe(true); expect(dir.endsWith(`-${raw.bake_id}`)).toBe(true);
}); });
it('names a time zone Intl knows (the sky draws its named moments in the place local day)', () => {
const tz = (raw as unknown as { place: { tz?: unknown } }).place.tz;
expect(typeof tz).toBe('string');
expect(() => new Intl.DateTimeFormat('en-US', { timeZone: tz as string })).not.toThrow();
});
it('has every card file, at the length the manifest states', () => { it('has every card file, at the length the manifest states', () => {
raw.cards.flatMap(files).forEach((f) => { raw.cards.flatMap(files).forEach((f) => {
expect(statSync(join(ROOT, dir, f.file)).size, f.file).toBe(f.bytes); expect(statSync(join(ROOT, dir, f.file)).size, f.file).toBe(f.bytes);

View file

@ -0,0 +1,271 @@
import { describe, expect, it } from 'vitest';
import {
DAY_FROM,
MOMENT_IDS,
localDate,
localMinutes,
momentFor,
momentKey,
seedFree,
skyBand,
zonedInstant,
} from './skyMoment';
import type { MomentId } from './skyMoment';
import { sunAt } from './sunAt';
import type { Place } from './view';
const PLACES: Record<string, Place> = {
vienna: { id: 'vienna', lat: 48.19, lon: 16.35, altitudeKm: 0.18, tz: 'Europe/Vienna' },
matterhorn: { id: 'matterhorn', lat: 45.98, lon: 7.78, altitudeKm: 3.1, tz: 'Europe/Zurich' },
fuji: { id: 'fuji', lat: 35.31, lon: 138.63, altitudeKm: 0.4, tz: 'Asia/Tokyo' },
amadablam: { id: 'amadablam', lat: 27.9, lon: 86.9, altitudeKm: 4.2, tz: 'Asia/Kathmandu' },
halfdome: {
id: 'halfdome',
lat: 37.73,
lon: -119.55,
altitudeKm: 1.2,
tz: 'America/Los_Angeles',
},
};
const DAYS = ['2026-06-21', '2026-12-21', '2026-03-20'];
const MIN = 60_000;
/** 18:00 place-local on `date`: any instant of that local day names it, and one after the sun's noon, so Night is the coming midnight. */
const during = (date: string, p: Place): Date => zonedInstant(date, 1080, p.tz);
const at = (id: MomentId, p: Place, date: string): Date =>
momentFor({ kind: 'named', id }, p, during(date, p));
const el = (p: Place, t: Date): number => sunAt(p, t).elevation;
describe('the named moments', () => {
describe.each(Object.entries(PLACES))('%s', (_name, p) => {
it.each(DAYS)(
'%s: dawn < morning < noon < golden < dusk inside the local day, night after noon',
(date) => {
const t = Object.fromEntries(MOMENT_IDS.map((id) => [id, at(id, p, date).getTime()]));
expect(t.dawn).toBeLessThan(t.morning);
expect(t.morning).toBeLessThan(t.noon);
expect(t.noon).toBeLessThan(t.golden);
expect(t.golden).toBeLessThan(t.dusk);
expect(t.night).toBeGreaterThan(t.noon);
(['dawn', 'morning', 'noon', 'golden', 'dusk'] as const).forEach((id) =>
expect(localDate(new Date(t[id]), p.tz)).toBe(date)
);
}
);
it.each(DAYS)('%s: each crossing is at its table elevation, within 0.05 degrees', (date) => {
const noonEl = el(p, at('noon', p, date));
expect(el(p, at('dawn', p, date))).toBeCloseTo(-3, 1);
expect(el(p, at('morning', p, date))).toBeCloseTo(Math.min(15, noonEl / 2), 1);
expect(el(p, at('golden', p, date))).toBeCloseTo(4, 1);
expect(el(p, at('dusk', p, date))).toBeCloseTo(-3, 1);
});
it.each(DAYS)(
'%s: noon is the day maximum and night the lowest of the 24 h after it',
(date) => {
const noon = at('noon', p, date);
const night = at('night', p, date);
for (let m = 0; m < 24 * 60; m += 5) {
const t = new Date(noon.getTime() + m * MIN);
expect(el(p, t)).toBeGreaterThanOrEqual(el(p, night) - 1e-3);
}
const dayStart = zonedInstant(date, 0, p.tz).getTime();
for (let m = 0; m < 24 * 60; m += 5) {
expect(el(p, new Date(dayStart + m * MIN))).toBeLessThanOrEqual(el(p, noon) + 1e-3);
}
}
);
});
it('morning is half the noon elevation at Vienna in December (the 15 degree rule would never be met)', () => {
const p = PLACES.vienna;
const noonEl = el(p, at('noon', p, '2026-12-21'));
expect(noonEl).toBeLessThan(30);
expect(el(p, at('morning', p, '2026-12-21'))).toBeCloseTo(noonEl / 2, 1);
expect(el(p, at('morning', p, '2026-06-21'))).toBeCloseTo(15, 1);
});
it('a named moment is today of the place: the same local date gives the same instant, the next day another', () => {
const p = PLACES.fuji;
const a = momentFor({ kind: 'named', id: 'dusk' }, p, zonedInstant('2026-12-21', 30, p.tz));
const b = momentFor({ kind: 'named', id: 'dusk' }, p, zonedInstant('2026-12-21', 1400, p.tz));
const c = momentFor({ kind: 'named', id: 'dusk' }, p, zonedInstant('2026-12-22', 30, p.tz));
expect(a.getTime()).toBe(b.getTime());
expect(c.getTime()).not.toBe(a.getTime());
});
it('is total at a pole, where there is no dawn or no dusk: it falls to noon or midnight', () => {
const pole: Place = { id: 'pole', lat: 80, lon: 0, altitudeKm: 0, tz: 'UTC' };
for (const date of ['2026-06-21', '2026-12-21']) {
const now = zonedInstant(date, 720, 'UTC');
for (const id of MOMENT_IDS) {
const t = momentFor({ kind: 'named', id }, pole, now);
expect(Number.isFinite(t.getTime())).toBe(true);
}
}
const june = zonedInstant('2026-06-21', 720, 'UTC');
expect(momentFor({ kind: 'named', id: 'dawn' }, pole, june).getTime()).toBe(
momentFor({ kind: 'named', id: 'noon' }, pole, june).getTime()
);
});
});
describe('zones', () => {
it.each(['Europe/Vienna', 'Asia/Tokyo', 'Asia/Kathmandu', 'America/Phoenix'])(
'%s: zonedInstant round-trips every minute of a day',
(tz) => {
for (let m = 0; m < 1440; m += 1) {
const t = zonedInstant('2026-06-21', m, tz);
expect(localDate(t, tz)).toBe('2026-06-21');
expect(localMinutes(t, tz)).toBe(m);
}
}
);
it('Kathmandu is UTC+5:45 and Phoenix has no daylight saving', () => {
expect(zonedInstant('2026-12-21', 720, 'Asia/Kathmandu').toISOString()).toBe(
'2026-12-21T06:15:00.000Z'
);
expect(zonedInstant('2026-07-01', 720, 'America/Phoenix').toISOString()).toBe(
'2026-07-01T19:00:00.000Z'
);
});
it('a wall time in the spring-forward gap lands after it; one that happens twice is the first', () => {
// Vienna, 2026-03-29: 02:00 became 03:00 (01:00Z). 2026-10-25: 03:00 became 02:00 (01:00Z).
expect(zonedInstant('2026-03-29', 150, 'Europe/Vienna').toISOString()).toBe(
'2026-03-29T01:30:00.000Z'
);
expect(zonedInstant('2026-10-25', 150, 'Europe/Vienna').toISOString()).toBe(
'2026-10-25T00:30:00.000Z'
);
});
it('the place decides, not the zone of the client', () => {
const p = PLACES.fuji;
const probe = () => ({
noon: momentFor({ kind: 'named', id: 'noon' }, p, new Date('2026-12-21T05:00:00Z')).getTime(),
free: momentFor({ kind: 'free', date: '2026-07-15', minutes: 330 }, p, new Date()).getTime(),
date: localDate(new Date('2026-12-21T16:00:00Z'), p.tz),
zi: zonedInstant('2026-03-29', 150, 'Europe/Vienna').getTime(),
});
const was = process.env.TZ;
try {
const seen = ['Pacific/Kiritimati', 'America/Anchorage', 'UTC'].map((tz) => {
process.env.TZ = tz;
return probe();
});
expect(seen[1]).toEqual(seen[0]);
expect(seen[2]).toEqual(seen[0]);
} finally {
if (was === undefined) delete process.env.TZ;
else process.env.TZ = was;
}
});
});
describe('Fuji dawn is Japanese dawn', () => {
it('lands in the Japanese morning, east of south-east, and a world away from the Vienna one', () => {
const fuji = PLACES.fuji;
const now = new Date('2026-12-21T04:00:00Z'); // local noon at Fuji
const t = momentFor({ kind: 'named', id: 'dawn' }, fuji, now);
const hourUtc = t.getUTCHours() + t.getUTCMinutes() / 60;
expect(t.getUTCDate()).toBe(20); // the previous UTC day
expect(hourUtc).toBeGreaterThan(20.5);
expect(hourUtc).toBeLessThan(22);
const s = sunAt(fuji, t);
expect(s.elevation).toBeCloseTo(-3, 1);
expect(s.azimuth).toBeGreaterThan(110);
expect(s.azimuth).toBeLessThan(125);
const vienna = momentFor({ kind: 'named', id: 'dawn' }, PLACES.vienna, now);
expect(Math.abs(vienna.getTime() - t.getTime()) / 3_600_000).toBeGreaterThan(7);
expect(Math.abs(vienna.getTime() - t.getTime()) / 3_600_000).toBeLessThan(9.5);
});
});
describe("Night is tonight's, the nearest one", () => {
const night = { kind: 'named', id: 'night' } as const;
const p = PLACES.vienna;
it('at 00:30 it is the midnight coming within the hour, not the one a day ahead; after noon the one coming', () => {
const at = Date.parse('2026-06-21T22:30:00Z'); // 00:30 on June 22, Vienna
const early = momentFor(night, p, new Date(at));
expect(localDate(early, p.tz)).toBe('2026-06-22');
expect(early.getTime() - at).toBeGreaterThan(0);
expect(early.getTime() - at).toBeLessThan(2 * 3_600_000);
const evening = momentFor(night, p, new Date('2026-06-22T12:00:00Z')); // 14:00 June 22
expect(localDate(evening, p.tz)).toBe('2026-06-23');
expect(evening.getTime() - early.getTime()).toBeGreaterThan(23.9 * 3_600_000);
expect(evening.getTime() - early.getTime()).toBeLessThan(24.1 * 3_600_000);
expect(momentFor(night, p, new Date('2026-06-22T18:00:00Z')).getTime()).toBe(evening.getTime());
});
it('the key follows the instant drawn: it is the same across the midnight roll and changes at the noon side', () => {
const k = (iso: string) => momentKey(night, p, new Date(iso));
expect(k('2026-06-21T22:30:00Z')).toBe(k('2026-06-21T21:30:00Z')); // 00:30 and 23:30
expect(k('2026-06-21T22:30:00Z')).not.toBe(k('2026-06-22T12:00:00Z'));
expect(k('2026-06-22T12:00:00Z')).toBe(k('2026-06-22T20:00:00Z'));
});
});
describe('purity and bands', () => {
it('auto is the time it is given', () => {
const now = new Date('2026-05-05T05:05:05Z');
expect(momentFor({ kind: 'auto' }, PLACES.vienna, now)).toBe(now);
expect(momentKey({ kind: 'auto' }, PLACES.vienna, now)).toBe('live');
});
it('a free moment is the place-local wall time, held inside 1900..2100', () => {
const p = PLACES.vienna;
const t = momentFor({ kind: 'free', date: '2026-12-21', minutes: 400 }, p, new Date());
expect(localDate(t, p.tz)).toBe('2026-12-21');
expect(localMinutes(t, p.tz)).toBe(400);
expect(
localDate(momentFor({ kind: 'free', date: '1800-01-01', minutes: 0 }, p, new Date()), p.tz)
).toBe('1900-01-01');
expect(
localDate(momentFor({ kind: 'free', date: '2999-05-05', minutes: 0 }, p, new Date()), p.tz)
).toBe('2100-12-31');
});
it('skyBand: day at 6.0, night at -6.0, dusk between', () => {
expect(skyBand(DAY_FROM)).toBe('day');
expect(skyBand(-DAY_FROM)).toBe('night');
expect(skyBand(DAY_FROM - 0.001)).toBe('dusk');
expect(skyBand(-DAY_FROM + 0.001)).toBe('dusk');
expect(skyBand(0)).toBe('dusk');
expect(skyBand(80)).toBe('day');
expect(skyBand(-80)).toBe('night');
});
it('the key of a moment follows its local date and id, or its date and minutes', () => {
const p = PLACES.vienna;
const n = { kind: 'named', id: 'noon' } as const;
expect(momentKey(n, p, new Date('2026-06-21T10:00:00Z'))).toBe(
momentKey(n, p, new Date('2026-06-21T20:00:00Z'))
);
expect(momentKey(n, p, new Date('2026-06-21T10:00:00Z'))).not.toBe(
momentKey(n, p, new Date('2026-06-22T10:00:00Z'))
);
expect(momentKey({ kind: 'free', date: '2026-06-21', minutes: 5 }, p, new Date())).not.toBe(
momentKey({ kind: 'free', date: '2026-06-21', minutes: 10 }, p, new Date())
);
});
});
describe('the picker seed', () => {
it('opens from the moment Auto or a named choice is drawing, in the place zone, to the 5 minutes the slider steps', () => {
const p = PLACES.fuji;
const now = new Date('2026-12-21T04:03:00Z'); // 13:03 at Fuji
expect(seedFree({ kind: 'auto' }, p, now)).toEqual({
kind: 'free',
date: '2026-12-21',
minutes: 13 * 60,
});
const noon = seedFree({ kind: 'named', id: 'noon' }, p, now);
expect(noon.date).toBe('2026-12-21');
expect(Math.abs(noon.minutes - 11 * 60 - 45)).toBeLessThanOrEqual(15); // solar noon at 138.6 E is about 11:45 JST
expect(noon.minutes % 5).toBe(0);
const free = { kind: 'free', date: '2026-07-15', minutes: 330 } as const;
expect(seedFree(free, p, now)).toBe(free);
});
});

View file

@ -0,0 +1,286 @@
// Which instant the sky is drawn at, and which band it is. One owner, pure (no store, no React, no clock):
// `momentFor(choice, place, now)` turns the viewer's choice, the place and the time into the instant, and `skyBand` turns the sun
// at that instant into the sky the ink and the tone map are fitted to. Place-local time exists only here, through Intl with `place.tz`;
// the viewer's own zone decides nothing. The named moments are one table (`SKY_MOMENTS`), a row each, tuned by eye.
import type { Place } from './view';
import { sunAt } from './sunAt';
/**
* The three skies ever drawn. Each has the luminance band its theme ink needs against bare sky (WCAG relative luminance,
* the `luminance` of src/sky/skyTokens.js): day, at least 0.2983 (the dark text ink #342d25); dusk, at least 0.4554 (the link
* #2a4f27); night, at most 0.0931 (the light text ink #aeccff). The ridge scene's display budgets (ridge/toneMap.ts `BUDGET`)
* sit inside them.
*/
export type FixedSkyState = 'day' | 'dusk' | 'night';
/** Sun elevation (degrees) from which it is day, and below the negative of which it is night; between, dusk (dawn included). */
export const DAY_FROM = 6;
/** The one function that turns a sun into day, dusk or night. */
export const skyBand = (elevationDeg: number): FixedSkyState =>
elevationDeg >= DAY_FROM ? 'day' : elevationDeg <= -DAY_FROM ? 'night' : 'dusk';
export const MOMENT_IDS = ['dawn', 'morning', 'noon', 'golden', 'dusk', 'night'] as const;
export type MomentId = typeof MOMENT_IDS[number];
/** What the viewer picked: the live sky, a named moment of today at the place, or a place-local date and minute of the day. */
export type SkyChoice =
| { kind: 'auto' }
| { kind: 'named'; id: MomentId }
| { kind: 'free'; date: string; minutes: number };
/** The ephemeris range (sunAt.ts header): free dates are held inside it. */
export const FREE_DATE_MIN = '1900-01-01';
export const FREE_DATE_MAX = '2100-12-31';
const MIN = 60_000;
const DAY = 24 * 60 * MIN;
// ---------------------------------------------------------------------------------------------------------------- place-local time
const formats = new Map<string, Intl.DateTimeFormat>();
const formatFor = (tz: string): Intl.DateTimeFormat => {
let f = formats.get(tz);
if (!f) {
f = new Intl.DateTimeFormat('en-US', {
timeZone: tz,
hourCycle: 'h23',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
});
formats.set(tz, f);
}
return f;
};
/** The wall clock of `t` in `tz`, read as if it were UTC (ms): its difference from `t` is the zone's offset. */
const wallAsUtc = (t: number, tz: string): number => {
const v: Record<string, number> = {};
formatFor(tz)
.formatToParts(new Date(t))
.forEach((p) => {
if (p.type !== 'literal') v[p.type] = Number(p.value);
});
return Date.UTC(v.year, v.month - 1, v.day, v.hour, v.minute, v.second);
};
const offsetAt = (t: number, tz: string): number => wallAsUtc(t, tz) - Math.floor(t / 1000) * 1000;
const pad = (n: number, w = 2): string => String(n).padStart(w, '0');
const dateOf = (utcMs: number): string => {
const d = new Date(utcMs);
return `${pad(d.getUTCFullYear(), 4)}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())}`;
};
const DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
const utcOfDate = (date: string): number => {
const m = DATE.exec(date);
if (!m) return NaN;
return Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
};
/** True for a real calendar date 'YYYY-MM-DD'. */
export const isDate = (date: unknown): date is string =>
typeof date === 'string' && DATE.test(date) && dateOf(utcOfDate(date)) === date;
/** The place-local calendar date of `now`, 'YYYY-MM-DD'. */
export const localDate = (now: Date, tz: string): string => dateOf(wallAsUtc(now.getTime(), tz));
/** The place-local minute of the day (0..1439) of `now`. */
export const localMinutes = (now: Date, tz: string): number => {
const wall = new Date(wallAsUtc(now.getTime(), tz));
return wall.getUTCHours() * 60 + wall.getUTCMinutes();
};
/**
* The instant at which the wall clock of `tz` reads `date` and `minutes`. A wall time that does not exist (the spring-forward gap) is
* shifted forward by the gap, so it lands after it; one that happens twice (fall-back) resolves to the first.
*/
export function zonedInstant(date: string, minutes: number, tz: string): Date {
const guess = utcOfDate(date) + minutes * MIN;
const before = offsetAt(guess - DAY, tz);
const after = offsetAt(guess + DAY, tz);
const valid = [...new Set([before, after])]
.map((o) => guess - o)
.filter((t) => offsetAt(t, tz) === guess - t)
.sort((a, b) => a - b);
return new Date(valid.length ? valid[0] : guess - before);
}
/** The short name of the zone at that instant ('CET', 'GMT+5:45'): what the picker shows beside a place-local time. */
export const zoneName = (at: Date, tz: string): string =>
new Intl.DateTimeFormat('en-US', { timeZone: tz, timeZoneName: 'short' })
.formatToParts(at)
.find((p) => p.type === 'timeZoneName')?.value ?? tz;
// ---------------------------------------------------------------------------------------------------------------- the named moments
const elevationAt = (place: Place, t: number): number => sunAt(place, new Date(t)).elevation;
const STEP = 5 * MIN;
/** The time in [a, b] (ms) where `f` is largest (sign 1) or smallest (sign -1), to under a minute: the function is unimodal there. */
function extremum(f: (t: number) => number, a: number, b: number, sign: 1 | -1): number {
let lo = a;
let hi = b;
while (hi - lo > MIN / 2) {
const m1 = lo + (hi - lo) / 3;
const m2 = hi - (hi - lo) / 3;
if (sign * f(m1) < sign * f(m2)) lo = m1;
else hi = m2;
}
return (lo + hi) / 2;
}
/** The time in [from, to] where `f` is largest (sign 1) or smallest (sign -1): a scan in 5-minute steps, refined to under a minute. */
function peak(f: (t: number) => number, from: number, to: number, sign: 1 | -1): number {
let best = from;
let bestV = -Infinity;
for (let t = from; t <= to; t += STEP) {
const v = sign * f(t);
if (v > bestV) {
bestV = v;
best = t;
}
}
return extremum(f, Math.max(from, best - STEP), Math.min(to, best + STEP), sign);
}
/** The first rising (or last setting) crossing of `deg` in [from, to]: a 5-minute scan, bisected under a second; undefined when there is none. */
function crossing(
f: (t: number) => number,
deg: number,
from: number,
to: number,
rising: boolean
): number | undefined {
const above = (t: number) => f(t) >= deg;
let found: [number, number] | undefined;
for (let a = from; a < to; a += STEP) {
const b = Math.min(a + STEP, to);
if (above(a) !== above(b) && above(b) === rising) {
found = [a, b];
if (rising) break;
}
}
if (!found) return undefined;
let [lo, hi] = found;
while (hi - lo > 500) {
const m = (lo + hi) / 2;
if (above(m) === rising) hi = m;
else lo = m;
}
return (lo + hi) / 2;
}
/** The place-local day a named moment is a moment of: its start and end, and the sun's noon in between. */
interface Day {
place: Place;
from: number;
to: number;
noon: number;
noonElevation: number;
}
interface Rule {
/** 'noon' and 'midnight' are the extremes; 'rising' and 'setting' are the crossing of `deg` (a function of the day's noon elevation) before and after noon. */
at: 'noon' | 'midnight' | 'rising' | 'setting';
deg?: (noonElevation: number) => number;
}
/**
* The named moments, one row each (tuned by eye, ruling ridge-look-tuned-by-eye-no-contrast-gates). A crossing the day does not have
* (polar) falls to the day's noon (rising) or midnight (setting). Night is solar midnight, tonight's: before the day's noon the one that
* just passed or is coming this morning, after it the one that is coming (`momentOf`'s `before`), never one a whole day away.
*/
export const SKY_MOMENTS: Record<MomentId, Rule> = {
dawn: { at: 'rising', deg: () => -3 },
morning: { at: 'rising', deg: (noon) => Math.min(15, noon / 2) },
noon: { at: 'noon' },
golden: { at: 'setting', deg: () => 4 },
dusk: { at: 'setting', deg: () => -3 },
night: { at: 'midnight' },
};
function momentOf(id: MomentId, d: Day, before: boolean): number {
const rule = SKY_MOMENTS[id];
const f = (t: number) => elevationAt(d.place, t);
const midnight = () => peak(f, d.noon, d.noon + DAY, -1);
if (rule.at === 'noon') return d.noon;
if (rule.at === 'midnight') return before ? peak(f, d.noon - DAY, d.noon, -1) : midnight();
const deg = rule.deg ? rule.deg(d.noonElevation) : 0;
if (rule.at === 'rising') return crossing(f, deg, d.from, d.noon, true) ?? d.noon;
return crossing(f, deg, d.noon, d.to, false) ?? midnight();
}
const days = new Map<string, Day>();
const named = new Map<string, number>();
/** The place-local day `date` at the place (memoised: a pure function of these). */
function dayOf(place: Place, date: string): Day {
const key = `${date}|${place.tz}|${place.lat}|${place.lon}`;
let d = days.get(key);
if (!d) {
const from = zonedInstant(date, 0, place.tz).getTime();
const to = zonedInstant(dateOf(utcOfDate(date) + DAY), 0, place.tz).getTime();
const noon = peak((x) => elevationAt(place, x), from, to, 1);
d = { place, from, to, noon, noonElevation: elevationAt(place, noon) };
if (days.size > 256) days.clear();
days.set(key, d);
}
return d;
}
/** The instant of a named moment on a place-local date at the place (memoised). Only Night looks at `now`: which side of the day's noon it is. */
function namedInstant(id: MomentId, place: Place, date: string, now: Date): Date {
const d = dayOf(place, date);
const before = now.getTime() < d.noon;
const key = `${id}|${date}|${before}|${place.tz}|${place.lat}|${place.lon}`;
let t = named.get(key);
if (t === undefined) {
t = momentOf(id, d, before);
if (named.size > 256) named.clear();
named.set(key, t);
}
return new Date(t);
}
// ---------------------------------------------------------------------------------------------------------------- the one decision
/** A free date held inside the ephemeris range; anything that is not a date reads as the range's start. */
const clampDate = (date: string): string =>
!isDate(date) || date < FREE_DATE_MIN
? FREE_DATE_MIN
: date > FREE_DATE_MAX
? FREE_DATE_MAX
: date;
const clampMinutes = (m: number): number => Math.min(1439, Math.max(0, Math.floor(m) || 0));
/** The instant the sky is drawn at for a choice at a place: auto is `now`; a named moment is today's at the place (Night: tonight's, the nearest one); a free moment is its own. */
export function momentFor(choice: SkyChoice, place: Place, now: Date): Date {
if (choice.kind === 'auto') return now;
if (choice.kind === 'named') return namedInstant(choice.id, place, localDate(now, place.tz), now);
return zonedInstant(clampDate(choice.date), clampMinutes(choice.minutes), place.tz);
}
/** The free moment (place-local date, minute to the 5 the slider steps) a choice is drawing now: where the picker opens from. */
export function seedFree(
choice: SkyChoice,
place: Place,
now: Date
): Extract<SkyChoice, { kind: 'free' }> {
if (choice.kind === 'free') return choice;
const at = momentFor(choice, place, now);
return {
kind: 'free',
date: localDate(at, place.tz),
minutes: Math.floor(localMinutes(at, place.tz) / 5) * 5,
};
}
/** What a rebuild is for, of the moment: live for auto, the id and place-local date of the instant for a named one, the date and minutes for a free one. */
export function momentKey(choice: SkyChoice, place: Place, now: Date): string {
if (choice.kind === 'auto') return 'live';
if (choice.kind === 'named') return `${choice.id}@${localDate(momentFor(choice, place, now), place.tz)}`;
return `${clampDate(choice.date)}@${clampMinutes(choice.minutes)}`;
}

View file

@ -0,0 +1,28 @@
// Test helpers for the sky: a moment named by the clock of the place, and the sun of a band. Tests only.
import { momentFor } from './skyMoment';
import type { FixedSkyState } from './skyMoment';
import { sunAt } from './sunAt';
import type { SunSample } from './sunAt';
import { FALLBACK_VIEW } from './view';
import type { Place } from './view';
const VIENNA = FALLBACK_VIEW.place;
/** 22 September 2026 at h:m of local solar time at Vienna (the equinox: the sun is up from about 06:00 to 18:00 and the equation of time is a few minutes). */
export const atSolarTime = (h: number, m = 0): Date =>
new Date(Date.UTC(2026, 8, 22, h, m) - VIENNA.lon * 4 * 60_000);
/** The sun of a band on the local day of `date` at `place`: Day is noon, Dusk the evening's -3 degrees, Night solar midnight. */
export const sunOfBand = (
place: Place,
band: FixedSkyState,
date: Date,
): SunSample =>
sunAt(
place,
momentFor(
{ kind: 'named', id: band === 'day' ? 'noon' : band },
place,
date
)
);

View file

@ -1,10 +1,13 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { solarNoon, STATE_ELEVATION, sunAt, sunForState } from './sunAt'; import { sunAt } from './sunAt';
import { momentFor } from './skyMoment';
import { FALLBACK_VIEW } from './view'; import { FALLBACK_VIEW } from './view';
const P = FALLBACK_VIEW.place; const P = FALLBACK_VIEW.place;
const at = (iso: string) => new Date(iso); const at = (iso: string) => new Date(iso);
/** The sun's noon of the local day of `t` (the named moment of the sky menu). */
const noonOf = (p: typeof P, t: Date) => momentFor({ kind: 'named', id: 'noon' }, p, t);
describe('the sun over Vienna', () => { describe('the sun over Vienna', () => {
it('the Vienna place reproduces the sun the old Vienna constant gave, exactly, at three dates', () => { it('the Vienna place reproduces the sun the old Vienna constant gave, exactly, at three dates', () => {
@ -22,24 +25,24 @@ describe('the sun over Vienna', () => {
}); });
it('stands at 90 - lat + declination at solar noon: the solstices and equinox', () => { it('stands at 90 - lat + declination at solar noon: the solstices and equinox', () => {
const june = sunAt(P, solarNoon(P, at('2026-06-21T12:00:00Z'))); const june = sunAt(P, noonOf(P, at('2026-06-21T12:00:00Z')));
expect(june.elevation).toBeCloseTo(90 - P.lat + 23.44, 0); expect(june.elevation).toBeCloseTo(90 - P.lat + 23.44, 0);
const december = sunAt(P, solarNoon(P, at('2026-12-21T12:00:00Z'))); const december = sunAt(P, noonOf(P, at('2026-12-21T12:00:00Z')));
expect(december.elevation).toBeCloseTo(90 - P.lat - 23.44, 0); expect(december.elevation).toBeCloseTo(90 - P.lat - 23.44, 0);
const march = sunAt(P, solarNoon(P, at('2026-03-20T12:00:00Z'))); const march = sunAt(P, noonOf(P, at('2026-03-20T12:00:00Z')));
expect(march.elevation).toBeCloseTo(90 - P.lat, 0); expect(march.elevation).toBeCloseTo(90 - P.lat, 0);
}); });
it('is due south at solar noon, east in the morning and west in the afternoon', () => { it('is due south at solar noon, east in the morning and west in the afternoon', () => {
const noon = solarNoon(P, at('2026-09-23T12:00:00Z')); const noon = noonOf(P, at('2026-09-23T12:00:00Z'));
expect(Math.abs(sunAt(P, noon).azimuth - 180)).toBeLessThan(2); // solarNoon is found to 5 minutes, which is 1.25 degrees of azimuth expect(Math.abs(sunAt(P, noon).azimuth - 180)).toBeLessThan(2); // noonOf is found to under a minute
expect(sunAt(P, new Date(noon.getTime() - 3 * 3600_000)).azimuth).toBeLessThan(150); expect(sunAt(P, new Date(noon.getTime() - 3 * 3600_000)).azimuth).toBeLessThan(150);
expect(sunAt(P, new Date(noon.getTime() + 3 * 3600_000)).azimuth).toBeGreaterThan(210); expect(sunAt(P, new Date(noon.getTime() + 3 * 3600_000)).azimuth).toBeGreaterThan(210);
}); });
it('solar noon at 16.35 E falls near 10:40 UTC in mid November', () => { it('solar noon at 16.35 E falls near 10:40 UTC in mid November', () => {
// 16.3534 E is 65.4 minutes ahead of Greenwich; the equation of time in mid November is +15 minutes (sun early): 12:00 - 65.5 - 15 = 10:40 UTC. // 16.3534 E is 65.4 minutes ahead of Greenwich; the equation of time in mid November is +15 minutes (sun early): 12:00 - 65.5 - 15 = 10:40 UTC.
const n = solarNoon(P, at('2026-11-11T12:00:00Z')); const n = noonOf(P, at('2026-11-11T12:00:00Z'));
const minutes = n.getUTCHours() * 60 + n.getUTCMinutes(); const minutes = n.getUTCHours() * 60 + n.getUTCMinutes();
expect(minutes).toBeGreaterThan(10 * 60 + 30); expect(minutes).toBeGreaterThan(10 * 60 + 30);
expect(minutes).toBeLessThan(10 * 60 + 50); expect(minutes).toBeLessThan(10 * 60 + 50);
@ -55,20 +58,4 @@ describe('the sun over Vienna', () => {
expect(Math.abs(daylight('2026-12-21T00:00:00Z') - (8 * 60 + 4))).toBeLessThan(15); expect(Math.abs(daylight('2026-12-21T00:00:00Z') - (8 * 60 + 4))).toBeLessThan(15);
expect(Math.abs(daylight('2026-06-21T00:00:00Z') - (16 * 60 + 0))).toBeLessThan(15); expect(Math.abs(daylight('2026-06-21T00:00:00Z') - (16 * 60 + 0))).toBeLessThan(15);
}); });
it('sunForState: the real sun when it is in the state, else a moment of today that is', () => {
const noon = solarNoon(P, at('2026-11-11T12:00:00Z'));
expect(sunForState(P, 'day', noon).time).toEqual(noon);
const midnight = new Date(noon.getTime() + 12 * 3600_000);
for (const state of ['day', 'dusk', 'night'] as const) {
for (const now of [noon, midnight, at('2026-11-11T15:30:00Z')]) {
const s = sunForState(P, state, now);
const [lo, hi] = STATE_ELEVATION[state];
expect(s.elevation).toBeGreaterThanOrEqual(lo - 0.01);
expect(s.elevation).toBeLessThanOrEqual(hi + 0.01);
}
}
expect(sunForState(P, 'dusk', noon).elevation).toBeCloseTo(0, 1);
expect(sunForState(P, 'dusk', noon).azimuth).toBeGreaterThan(180); // sets in the west half
});
}); });

View file

@ -1,9 +1,6 @@
// The sun over a Place (`view.ts`) at a real moment: one ephemeris, `sunPosition` of src/sky/sun.js (the // The sun over a Place (`view.ts`) at a real moment: one ephemeris, `sunPosition` of src/sky/sun.js (the
// low-precision NOAA/Meeus series, a hundredth of a degree for 1900..2100; no refraction), and the choice of a moment for each // low-precision NOAA/Meeus series, a hundredth of a degree for 1900..2100; no refraction). The moment a sky is drawn at is skyMoment.ts's. The ridge sky is the physical atmosphere (`earthAtmosphere.ts`) lit from this sun.
// fixed sky state. The ridge sky is the physical atmosphere (`earthAtmosphere.ts`) lit from this sun.
import { sunPosition } from '../../../../sky/sun.js'; import { sunPosition } from '../../../../sky/sun.js';
import { DAY_FROM } from '../skyState';
import type { FixedSkyState } from '../skyState';
import type { Place } from './view'; import type { Place } from './view';
export interface SunSample { export interface SunSample {
@ -22,53 +19,3 @@ export function sunAt(place: Place, time: Date): SunSample {
}; };
return { elevation, azimuth, time }; return { elevation, azimuth, time };
} }
const MIN = 60_000;
/** Sun elevation range of each fixed state: the thresholds `resolveSkyState` uses (day from DAY_FROM, night below -DAY_FROM). */
export const STATE_ELEVATION: Record<FixedSkyState, readonly [number, number]> = {
day: [DAY_FROM, 90],
dusk: [-DAY_FROM, DAY_FROM],
night: [-90, -DAY_FROM],
};
const startOfUtcDay = (t: Date): number =>
Math.floor(t.getTime() / (24 * 60 * MIN)) * 24 * 60 * MIN;
/** The moment of the day (UTC day of `t`, every 5 minutes) the sun is highest over the place: solar noon to the step. */
export function solarNoon(place: Place, t: Date): Date {
const d0 = startOfUtcDay(t);
let best = d0;
let bestEl = -90;
for (let m = 0; m < 24 * 60; m += 5) {
const el = sunAt(place, new Date(d0 + m * MIN)).elevation;
if (el > bestEl) {
bestEl = el;
best = d0 + m * MIN;
}
}
return new Date(best);
}
/**
* The sun a state draws. The real sun over the place now when it is in the state's range (so 'auto' is the real sky); otherwise the
* sun of today at a moment that is: noon for Day, the evening sunset for Dusk, the opposite of noon for Night. A picker that
* forces Day at night shows a noon sky, as a person looking at a noon photograph would.
*/
export function sunForState(place: Place, state: FixedSkyState, now: Date): SunSample {
const real = sunAt(place, now);
const [lo, hi] = STATE_ELEVATION[state];
if (real.elevation >= lo && real.elevation <= hi) return real;
const noon = solarNoon(place, now);
if (state === 'day') return sunAt(place, noon);
if (state === 'night') return sunAt(place, new Date(noon.getTime() + 12 * 60 * MIN));
// Dusk: bisect the evening crossing of the horizon between noon and the opposite moment.
let a = noon.getTime();
let b = noon.getTime() + 12 * 60 * MIN;
for (let i = 0; i < 30; i += 1) {
const m = (a + b) / 2;
if (sunAt(place, new Date(m)).elevation > 0) a = m;
else b = m;
}
return sunAt(place, new Date((a + b) / 2));
}

View file

@ -1,11 +1,12 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { FALLBACK_VIEW } from './view'; import { FALLBACK_VIEW } from './view';
import { makePhysicalSky } from './physicalSky'; import { makePhysicalSky } from './physicalSky';
import { sunOfBand } from './skyTestkit';
import { renderDome } from './skyDome'; import { renderDome } from './skyDome';
import { windowFor } from './view'; import { windowFor } from './view';
import { applyCurve, BLACK_LIFT, BUDGET, NIGHT_CEILING, NIGHT_LIFT, SCOTOPIC, displayLumaOf, fitDisplay, makeCurve, scotopic, scotopicWeight } from './toneMap'; import { applyCurve, BLACK_LIFT, BUDGET, NIGHT_CEILING, NIGHT_LIFT, SCOTOPIC, displayLumaOf, fitDisplay, makeCurve, scotopic, scotopicWeight } from './toneMap';
import { sunAt } from './sunAt'; import { sunAt } from './sunAt';
import type { FixedSkyState } from '../skyState'; import type { FixedSkyState } from './skyMoment';
const sweep = (c: ReturnType<typeof makeCurve>) => const sweep = (c: ReturnType<typeof makeCurve>) =>
Array.from({ length: 401 }, (_, i) => applyCurve(c, i / 400)); Array.from({ length: 401 }, (_, i) => applyCurve(c, i / 400));
@ -28,7 +29,7 @@ describe('the tone curve', () => {
}); });
describe.each(['day', 'dusk', 'night'] as FixedSkyState[])('the %s curve fitted to a sky', (state) => { describe.each(['day', 'dusk', 'night'] as FixedSkyState[])('the %s curve fitted to a sky', (state) => {
const sky = makePhysicalSky(state, new Date('2026-06-21T10:40:00Z'), 0, FALLBACK_VIEW); const sky = makePhysicalSky(sunOfBand(FALLBACK_VIEW.place, state, new Date('2026-06-21T10:40:00Z')), 0, FALLBACK_VIEW);
const { camera } = windowFor(sky.view, 64, 36); const { camera } = windowFor(sky.view, 64, 36);
const dome = renderDome(sky.atm, sky.sun, camera, 64, 36, sky.weather.cover, sky.night); const dome = renderDome(sky.atm, sky.sun, camera, 64, 36, sky.weather.cover, sky.night);
const b = BUDGET[state]; const b = BUDGET[state];
@ -67,7 +68,7 @@ describe.each(['day', 'dusk', 'night'] as FixedSkyState[])('the %s curve fitted
describe('the night display', () => { describe('the night display', () => {
const night = (iso: string) => { const night = (iso: string) => {
const t = new Date(iso); const t = new Date(iso);
return makePhysicalSky('night', t, 0, FALLBACK_VIEW, sunAt(FALLBACK_VIEW.place, t)); return makePhysicalSky(sunAt(FALLBACK_VIEW.place, t), 0, FALLBACK_VIEW);
}; };
const fullMoon = night('2026-11-24T22:00:00Z'); const fullMoon = night('2026-11-24T22:00:00Z');
const newMoon = night('2026-12-09T20:00:00Z'); const newMoon = night('2026-12-09T20:00:00Z');
@ -86,7 +87,7 @@ describe('the night display', () => {
it('grades toward the rods at night and not by day', () => { it('grades toward the rods at night and not by day', () => {
expect(fullMoon.fit.display.grade).toBeGreaterThan(0.8); expect(fullMoon.fit.display.grade).toBeGreaterThan(0.8);
expect(newMoon.fit.display.grade).toBeGreaterThan(0.99); expect(newMoon.fit.display.grade).toBeGreaterThan(0.99);
expect(makePhysicalSky('day', new Date('2026-06-21T10:40:00Z'), 0, FALLBACK_VIEW).fit.display.grade ?? 0).toBe(0); expect(makePhysicalSky(sunOfBand(FALLBACK_VIEW.place, 'day', new Date('2026-06-21T10:40:00Z')), 0, FALLBACK_VIEW).fit.display.grade ?? 0).toBe(0);
}); });
it('has no fixed night ceiling: the curve tops out at NIGHT_CEILING', () => { it('has no fixed night ceiling: the curve tops out at NIGHT_CEILING', () => {

View file

@ -10,7 +10,7 @@
// distribution of the sky grid so that its 5th, 50th and 95th percentiles land on the state's target display luminances. The curve // distribution of the sky grid so that its 5th, 50th and 95th percentiles land on the state's target display luminances. The curve
// starts at a small black lift and ends at white, or at the state's ceiling when it has one. It is fitted on the sky grid alone: the // starts at a small black lift and ends at white, or at the state's ceiling when it has one. It is fitted on the sky grid alone: the
// cards are not sampled, they ride the same curve. // cards are not sampled, they ride the same curve.
import type { FixedSkyState } from '../skyState'; import type { FixedSkyState } from './skyMoment';
import { SUN_LUX } from './nightSky'; import { SUN_LUX } from './nightSky';
type Rgb = readonly [number, number, number]; type Rgb = readonly [number, number, number];

View file

@ -9,6 +9,8 @@ export interface Place {
lat: number; lat: number;
lon: number; lon: number;
altitudeKm: number; altitudeKm: number;
/** The place's IANA time zone (the baker writes it): the one owner of place-local time is skyMoment.ts. */
tz: string;
} }
/** The manifest's `view`: the baked window of the sky the planes cover. Angles are degrees, planes are in plane pixels. */ /** The manifest's `view`: the baked window of the sky the planes cover. Angles are degrees, planes are in plane pixels. */
@ -45,7 +47,7 @@ export interface Camera {
/** The sky of a scene with no planes (a failed load): Vienna facing south-west, with the numbers of the Vienna bake. */ /** The sky of a scene with no planes (a failed load): Vienna facing south-west, with the numbers of the Vienna bake. */
export const FALLBACK_VIEW: View = { export const FALLBACK_VIEW: View = {
place: { id: 'vienna', lat: 48.1929826, lon: 16.3534237, altitudeKm: 0.183 }, place: { id: 'vienna', lat: 48.1929826, lon: 16.3534237, altitudeKm: 0.183, tz: 'Europe/Vienna' },
lookAzDeg: 214, lookAzDeg: 214,
windowDeg: 72, windowDeg: 72,
planeW: 1280, planeW: 1280,

View file

@ -1,81 +1,132 @@
import { afterEach, describe, expect, it, vi } from 'vitest'; import { afterEach, describe, expect, it, vi } from 'vitest';
import { FALLBACK_VIEW } from './ridge/view'; import { FALLBACK_VIEW } from './ridge/view';
import { ELSEWHERE_VIEW } from './ridge/manifest.fixture'; import { ELSEWHERE_VIEW } from './ridge/manifest.fixture';
import { atStandardTime } from './standardTime.testkit'; import { atSolarTime } from './ridge/skyTestkit';
import { ridgeDrawn, ridgeSkyFor, ridgeSkyKey, loadWeather } from './skyForState'; import { CLEAR_SKY, ridgeDrawn, ridgeSkyFor, ridgeSkyKey, loadWeather } from './skyForState';
import { DAY_FROM, setSkyClock } from './skyState'; import { setSkyClock } from './skyState';
import { DAY_FROM } from './ridge/skyMoment';
import type { SkyChoice } from './ridge/skyMoment';
import { BUDGET } from './ridge/toneMap'; import { BUDGET } from './ridge/toneMap';
import { ridgeWeather, setFedWeather } from './ridge/weather';
const STATES = ['day', 'dusk', 'night'] as const; const auto: SkyChoice = { kind: 'auto' };
const named = (id: 'dawn' | 'morning' | 'noon' | 'golden' | 'dusk' | 'night'): SkyChoice => ({
kind: 'named',
id,
});
const BANDS = [
['day', named('noon')],
['dusk', named('dusk')],
['night', named('night')],
] as const;
afterEach(() => { afterEach(() => {
setSkyClock(); setSkyClock();
setFedWeather(undefined);
vi.unstubAllGlobals(); vi.unstubAllGlobals();
}); });
describe('ridgeSkyFor', () => { describe('ridgeSkyFor', () => {
it('carries the physical sky of the state', () => { it.each(BANDS)('carries the physical sky of the %s moment', (band, choice) => {
for (const state of STATES) { const sky = ridgeSkyFor(choice, FALLBACK_VIEW, 0.3);
const sky = ridgeSkyFor(state, FALLBACK_VIEW, 0.3); expect(sky.physical?.state).toBe(band);
expect(sky.physical?.state).toBe(state);
expect(sky.physical?.stops).toEqual({ top: sky.top, mid: sky.mid, horizon: sky.horizon }); expect(sky.physical?.stops).toEqual({ top: sky.top, mid: sky.mid, horizon: sky.horizon });
}
}); });
it('draws the sky auto resolves to, never nothing', () => { it('Auto draws the real sun now, never nothing', () => {
const key = (s: ReturnType<typeof ridgeSkyFor>) => [ const key = (s: ReturnType<typeof ridgeSkyFor>) => [s.top, s.mid, s.horizon, s.physical?.sun.time];
s.top, const noon = atSolarTime(12, 0);
s.mid, expect(key(ridgeSkyFor(auto, FALLBACK_VIEW, 0.3, noon))[3]).toEqual(noon);
s.horizon, expect(ridgeSkyFor(auto, FALLBACK_VIEW, 0.3, noon).physical?.state).toBe('day');
s.physical?.sun, expect(ridgeSkyFor(auto, FALLBACK_VIEW, 0.3, atSolarTime(0, 0)).physical?.state).toBe('night');
]; expect(ridgeSkyFor(auto, FALLBACK_VIEW, 0.3, atSolarTime(18, 10)).physical?.state).toBe('dusk');
setSkyClock(() => atStandardTime(12, 0));
expect(key(ridgeSkyFor('auto', FALLBACK_VIEW, 0.3))).toEqual(key(ridgeSkyFor('day', FALLBACK_VIEW, 0.3)));
setSkyClock(() => atStandardTime(0, 0));
expect(key(ridgeSkyFor('auto', FALLBACK_VIEW, 0.3))).toEqual(key(ridgeSkyFor('night', FALLBACK_VIEW, 0.3)));
setSkyClock(() => atStandardTime(18, 10));
expect(key(ridgeSkyFor('auto', FALLBACK_VIEW, 0.3))).toEqual(key(ridgeSkyFor('dusk', FALLBACK_VIEW, 0.3)));
}); });
it("is lit from the real sun over Vienna: a forced state's sun is inside the state, the clear noon sky is blue", () => { it("is lit from the real sun over Vienna: a moment's sun is inside its band, the clear noon sky is blue", () => {
const day = ridgeSkyFor('day', FALLBACK_VIEW, 0); const day = ridgeSkyFor(named('noon'), FALLBACK_VIEW, 0);
expect(day.physical?.sun.elevation).toBeGreaterThanOrEqual(DAY_FROM); expect(day.physical?.sun.elevation).toBeGreaterThanOrEqual(DAY_FROM);
expect(day.top[2]).toBeGreaterThan(day.top[0]); expect(day.top[2]).toBeGreaterThan(day.top[0]);
const dusk = ridgeSkyFor('dusk', FALLBACK_VIEW, 0); expect(Math.abs(ridgeSkyFor(named('dusk'), FALLBACK_VIEW, 0).physical?.sun.elevation ?? 99)).toBeLessThanOrEqual(DAY_FROM);
expect(Math.abs(dusk.physical?.sun.elevation ?? 99)).toBeLessThanOrEqual(DAY_FROM); expect(ridgeSkyFor(named('night'), FALLBACK_VIEW, 0).physical?.sun.elevation).toBeLessThanOrEqual(-DAY_FROM);
expect(ridgeSkyFor('night', FALLBACK_VIEW, 0).physical?.sun.elevation).toBeLessThanOrEqual(-DAY_FROM); });
it('a free moment is lit from the sun of its own date', () => {
const sky = ridgeSkyFor({ kind: 'free', date: '2026-07-15', minutes: 13 * 60 }, FALLBACK_VIEW);
expect(sky.physical?.sun.time.toISOString()).toBe('2026-07-15T11:00:00.000Z');
expect(sky.physical?.state).toBe('day');
}); });
it("is made over the View's place: the sun and the observer are the View's", () => { it("is made over the View's place: the sun and the observer are the View's", () => {
const sky = ridgeSkyFor('day', ELSEWHERE_VIEW, 0); const sky = ridgeSkyFor(named('noon'), ELSEWHERE_VIEW, 0);
expect(sky.physical?.view).toBe(ELSEWHERE_VIEW); expect(sky.physical?.view).toBe(ELSEWHERE_VIEW);
expect(sky.physical?.atm.observerKm).toBe(ELSEWHERE_VIEW.place.altitudeKm); expect(sky.physical?.atm.observerKm).toBe(ELSEWHERE_VIEW.place.altitudeKm);
}); });
it("keys a rebuild by the View's place as well: another place is another key", () => { // Each band's ceiling is its budget's (night's is a tunable, NIGHT_CEILING: the operator tunes it by eye).
const other = { ...FALLBACK_VIEW, place: { ...FALLBACK_VIEW.place, id: 'graz' } }; it.each(BANDS)('%s: the display is the curve of its budget: black lift at the floor, and its ceiling', (band, choice) => {
expect(ridgeSkyKey('day', FALLBACK_VIEW, 0.3)).not.toBe(ridgeSkyKey('day', other, 0.3)); const r = ridgeDrawn(band);
expect(ridgeSkyKey('day', other, 0.3)).toContain('graz'); expect(r.darkest).toBe(BUDGET[band].floor);
}); expect(r.lightest).toBeLessThanOrEqual(BUDGET[band].ceiling);
const fit = ridgeSkyFor(choice, FALLBACK_VIEW, 0.3).physical?.fit;
it('keys a rebuild by state and weather, not by the moving sun', () => {
setSkyClock(() => atStandardTime(12, 0));
expect(ridgeSkyKey('auto', FALLBACK_VIEW, 0.3)).toBe(ridgeSkyKey('day', FALLBACK_VIEW, 0.3));
expect(ridgeSkyKey('day', FALLBACK_VIEW, 0.3)).not.toBe(ridgeSkyKey('day', FALLBACK_VIEW, 0.8));
expect(ridgeSkyKey('day', FALLBACK_VIEW, 0.3)).not.toBe(ridgeSkyKey('night', FALLBACK_VIEW, 0.3));
});
// Each state's ceiling is its budget's (night's is a tunable, NIGHT_CEILING: the operator tunes it by eye).
it.each(STATES)('%s: the display is the curve of its budget: black lift at the floor, and its ceiling', (state) => {
const r = ridgeDrawn(state);
expect(r.darkest).toBe(BUDGET[state].floor);
expect(r.lightest).toBeLessThanOrEqual(BUDGET[state].ceiling);
const fit = ridgeSkyFor(state, FALLBACK_VIEW, 0.3).physical?.fit;
expect(fit?.lo).toBeGreaterThanOrEqual(r.darkest - 1e-9); expect(fit?.lo).toBeGreaterThanOrEqual(r.darkest - 1e-9);
expect(fit?.hi).toBeLessThanOrEqual(r.lightest + 1e-9); expect(fit?.hi).toBeLessThanOrEqual(r.lightest + 1e-9);
}); });
}); });
describe('ridgeSkyKey', () => {
const noonNow = atSolarTime(12, 0);
it("keys a rebuild by the View's place as well: another place is another key", () => {
const other = { ...FALLBACK_VIEW, place: { ...FALLBACK_VIEW.place, id: 'graz' } };
expect(ridgeSkyKey(named('noon'), FALLBACK_VIEW, 0.3, noonNow)).not.toBe(ridgeSkyKey(named('noon'), other, 0.3, noonNow));
expect(ridgeSkyKey(named('noon'), other, 0.3, noonNow)).toContain('graz');
});
it('differs between Auto-at-day and Noon: live against frozen', () => {
expect(ridgeSkyKey(auto, FALLBACK_VIEW, 0.3, noonNow)).not.toBe(ridgeSkyKey(named('noon'), FALLBACK_VIEW, 0.3, noonNow));
});
it('is equal for one named moment across two calls on one local date, and changes with the weather and the moment', () => {
const a = ridgeSkyKey(named('noon'), FALLBACK_VIEW, 0.3, atSolarTime(9, 0));
expect(ridgeSkyKey(named('noon'), FALLBACK_VIEW, 0.3, atSolarTime(21, 0))).toBe(a);
expect(ridgeSkyKey(named('noon'), FALLBACK_VIEW, 0.8, noonNow)).not.toBe(a);
expect(ridgeSkyKey(named('night'), FALLBACK_VIEW, 0.3, noonNow)).not.toBe(a);
expect(ridgeSkyKey(named('noon'), FALLBACK_VIEW, 0.3, new Date(noonNow.getTime() + 24 * 3_600_000))).not.toBe(a);
});
it('changes with the free date or minutes', () => {
const k = (date: string, minutes: number) => ridgeSkyKey({ kind: 'free', date, minutes }, FALLBACK_VIEW, 0, noonNow);
expect(k('2026-07-15', 300)).not.toBe(k('2026-07-16', 300));
expect(k('2026-07-15', 300)).not.toBe(k('2026-07-15', 305));
expect(k('2026-07-15', 300)).toBe(k('2026-07-15', 300));
});
it('is stable under the minute tick inside a band (Auto)', () => {
const at = (m: number) => ridgeSkyKey(auto, FALLBACK_VIEW, 0.3, new Date(atSolarTime(11, 0).getTime() + m * 60_000));
expect(at(0)).toBe(at(1));
expect(at(0)).toBe(at(90));
});
});
describe('the weather of a moment', () => {
it('a free moment draws a clear sky whatever the feed holds; Auto and the named moments draw the feed', () => {
setFedWeather(0.9);
expect(ridgeWeather()).toBe(0.9);
const noonNow = atSolarTime(12, 0);
const free: SkyChoice = { kind: 'free', date: '2026-07-15', minutes: 13 * 60 };
expect(ridgeSkyFor(free, FALLBACK_VIEW, undefined, noonNow).physical?.weather).toEqual(
ridgeSkyFor(free, FALLBACK_VIEW, CLEAR_SKY, noonNow).physical?.weather
);
expect(ridgeSkyKey(free, FALLBACK_VIEW, undefined, noonNow)).toContain(`:${CLEAR_SKY}:`);
for (const choice of [auto, named('noon')]) {
expect(ridgeSkyKey(choice, FALLBACK_VIEW, undefined, noonNow)).toContain(':0.9:');
expect(ridgeSkyFor(choice, FALLBACK_VIEW, undefined, noonNow).physical?.weather).toEqual(
ridgeSkyFor(choice, FALLBACK_VIEW, 0.9, noonNow).physical?.weather
);
}
});
});
describe('loadWeather', () => { describe('loadWeather', () => {
it('reads the file again for another place inside the refresh window: the weather it set belongs to the sun of the place it was read for', async () => { it('reads the file again for another place inside the refresh window: the weather it set belongs to the sun of the place it was read for', async () => {
const fetched = vi.fn(async () => ({ ok: false, status: 404, json: async () => ({}) })); const fetched = vi.fn(async () => ({ ok: false, status: 404, json: async () => ({}) }));
@ -92,15 +143,16 @@ describe('loadWeather', () => {
describe('the rebuild key and the constellation lines', () => { describe('the rebuild key and the constellation lines', () => {
it('carries the lines at night only: toggling them is a different sky, a day sky is the same', async () => { it('carries the lines at night only: toggling them is a different sky, a day sky is the same', async () => {
vi.stubGlobal('localStorage', { getItem: () => null, setItem: () => undefined }); vi.stubGlobal('localStorage', { getItem: () => null, setItem: () => undefined, removeItem: () => undefined });
vi.resetModules(); vi.resetModules();
const st = await import('./skyState'); const st = await import('./skyState');
const f = await import('./skyForState'); const f = await import('./skyForState');
const off = f.ridgeSkyKey('night', FALLBACK_VIEW, 0); const now = atSolarTime(12, 0);
const dayOff = f.ridgeSkyKey('day', FALLBACK_VIEW, 0); const off = f.ridgeSkyKey(named('night'), FALLBACK_VIEW, 0, now);
st.pickSkyState('night'); const dayOff = f.ridgeSkyKey(named('noon'), FALLBACK_VIEW, 0, now);
st.pickSkyState('night'); st.pickSkyChoice(named('night'));
expect(f.ridgeSkyKey('night', FALLBACK_VIEW, 0)).toBe(`${off}:lines`); st.pickSkyChoice(named('night'));
expect(f.ridgeSkyKey('day', FALLBACK_VIEW, 0)).toBe(dayOff); expect(f.ridgeSkyKey(named('night'), FALLBACK_VIEW, 0, now)).toBe(`${off}:lines`);
expect(f.ridgeSkyKey(named('noon'), FALLBACK_VIEW, 0, now)).toBe(dayOff);
}); });
}); });

View file

@ -1,27 +1,36 @@
// What the ridge scene is told for a sky state. 'auto' is a choice, not a sky: it draws the sky it // What the ridge scene is told for a sky choice. The choice is not a sky: `momentFor` (ridge/skyMoment.ts) decides the instant it draws,
// resolves to (`resolveSkyState`, the clock), so the scene paints one of day, dusk or night, fitted to that // the sun at that instant is what the physical sky is lit from, and its band (`skyBand`) picks the display's luminance budget (ridge/toneMap.ts).
// state's luminance budget (ridge/toneMap.ts).
import type { SkyColours } from './ridge/skyColour'; import type { SkyColours } from './ridge/skyColour';
import { makePhysicalSky } from './ridge/physicalSky'; import { makePhysicalSky } from './ridge/physicalSky';
import { momentFor, momentKey, skyBand } from './ridge/skyMoment';
import type { FixedSkyState, SkyChoice } from './ridge/skyMoment';
import { sunAt } from './ridge/sunAt';
import type { Place, View } from './ridge/view'; import type { Place, View } from './ridge/view';
import { BUDGET } from './ridge/toneMap'; import { BUDGET } from './ridge/toneMap';
import { ridgeWeather, setFedWeather } from './ridge/weather'; import { ridgeWeather, setFedWeather } from './ridge/weather';
import { currentWeather, fetchWeatherFile } from './ridge/weatherFeed'; import { currentWeather, fetchWeatherFile } from './ridge/weatherFeed';
import { getConstellationLines, resolveSkyState, skyNow } from './skyState'; import { getConstellationLines, skyNow } from './skyState';
import type { SkyState } from './skyState';
/** A clear sky: what a free moment is drawn with (ruling ridge-weather-on-frozen-moments: today's weather says nothing of another date). */
export const CLEAR_SKY = 0;
/** The weather a choice is drawn with: a free moment is clear; Auto and the named moments of today draw today's weather. */
const weatherFor = (choice: SkyChoice): number =>
choice.kind === 'free' ? CLEAR_SKY : ridgeWeather();
/** /**
* What a rebuild of the ridge scene is for: the fixed state it draws, the weather and, at night, the constellation lines. The sun moves with the clock inside a state and * What a rebuild of the ridge scene is for: the band and moment it draws, the weather, the place and, at night, the constellation lines.
* is not part of the key (the scene is baked at its start), as the sky was one gradient per state before. * The sun moves with the clock inside an Auto band and is not part of the key (the scene is baked at its start); a named moment is its id
* and local date, a free one its date and minutes.
*/ */
export const ridgeSkyKey = ( export const ridgeSkyKey = (
state: SkyState, choice: SkyChoice,
view: View, view: View,
weather: number = ridgeWeather(), weather: number = weatherFor(choice),
now: Date = skyNow() now: Date = skyNow()
): string => { ): string => {
const fixed = resolveSkyState(state, now); const band = skyBand(sunAt(view.place, momentFor(choice, view.place, now)).elevation);
return `ridge:${fixed}:${weather}:${view.place.id}${fixed === 'night' && getConstellationLines() ? ':lines' : ''}`; return `ridge:${band}:${weather}:${view.place.id}:${momentKey(choice, view.place, now)}${band === 'night' && getConstellationLines() ? ':lines' : ''}`;
}; };
const WEATHER_REFRESH_MS = 10 * 60_000; const WEATHER_REFRESH_MS = 10 * 60_000;
@ -39,18 +48,17 @@ export async function loadWeather(url: string, place: Place, now: Date = skyNow(
} }
/** /**
* The ridge scene's `sky` option: the physical sky over the View's place for the state ('auto': the real sun now; a forced state: the * The ridge scene's `sky` option: the physical sky over the View's place at the instant the choice draws (`momentFor`: Auto the real sun now,
* sun of today at a moment inside it, `sunForState`), as a palette for the layers and stars plus the `physical` sky the host canvas * a named or free moment its own), as a palette for the layers and stars plus the `physical` sky the host canvas
* is painted from. The atmosphere LUTs are baked here, once per scene start (tens of ms). * is painted from. The atmosphere LUTs are baked here, once per scene start (tens of ms).
*/ */
export function ridgeSkyFor( export function ridgeSkyFor(
state: SkyState, choice: SkyChoice,
view: View, view: View,
weather: number = ridgeWeather(), weather: number = weatherFor(choice),
now: Date = skyNow() now: Date = skyNow()
): SkyColours { ): SkyColours {
const fixed = resolveSkyState(state, now); const physical = makePhysicalSky(sunAt(view.place, momentFor(choice, view.place, now)), weather, view);
const physical = makePhysicalSky(fixed, now, weather, view);
return { return {
...physical.stops, ...physical.stops,
physical, physical,
@ -67,8 +75,7 @@ export interface Range {
* The ridge sky's range: what its display is fitted to hold (`BUDGET`, toneMap.ts), which `physicalSky.test.ts` proves over the * The ridge sky's range: what its display is fitted to hold (`BUDGET`, toneMap.ts), which `physicalSky.test.ts` proves over the
* sun's whole year over Vienna. Dark ink needs the floor; light ink the ceiling. * sun's whole year over Vienna. Dark ink needs the floor; light ink the ceiling.
*/ */
export function ridgeDrawn(state: SkyState): Range { export function ridgeDrawn(band: FixedSkyState): Range {
const b = BUDGET[resolveSkyState(state)]; const b = BUDGET[band];
return { darkest: b.floor, lightest: b.ceiling }; return { darkest: b.floor, lightest: b.ceiling };
} }

View file

@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest';
import { baked } from '../../../sky/baked'; import { baked } from '../../../sky/baked';
import { AA, luminance } from '../../../sky/skyTokens.js'; import { AA, luminance } from '../../../sky/skyTokens.js';
import { indexColorMXID } from '../../../util/colorMXID'; import { indexColorMXID } from '../../../util/colorMXID';
import type { FixedSkyState } from './skyState'; import type { FixedSkyState } from './ridge/skyMoment';
import { import {
LIGHTEST_PATCH, LIGHTEST_PATCH,
NIGHT_INK_MAX_L, NIGHT_INK_MAX_L,

View file

@ -15,7 +15,7 @@ import chroma from 'chroma-js';
import { AA, luminance } from '../../../sky/skyTokens.js'; import { AA, luminance } from '../../../sky/skyTokens.js';
import { baked } from '../../../sky/baked'; import { baked } from '../../../sky/baked';
import { indexColorMXID } from '../../../util/colorMXID'; import { indexColorMXID } from '../../../util/colorMXID';
import type { FixedSkyState } from './skyState'; import type { FixedSkyState } from './ridge/skyMoment';
import type { SkyThemeId } from './skyTheme'; import type { SkyThemeId } from './skyTheme';
export interface SkyInk { export interface SkyInk {
@ -31,9 +31,9 @@ export interface SkyInk {
export const sceneInk = ( export const sceneInk = (
themeId: SkyThemeId | undefined, themeId: SkyThemeId | undefined,
sceneOn: boolean, sceneOn: boolean,
state: FixedSkyState, state: FixedSkyState | undefined,
phone: boolean phone: boolean
): SkyInk | undefined => (themeId && sceneOn ? { state, phone } : undefined); ): SkyInk | undefined => (themeId && sceneOn && state ? { state, phone } : undefined);
/** WCAG relative luminance of the lightest 24x12 patch of terrain behind the timeline. */ /** WCAG relative luminance of the lightest 24x12 patch of terrain behind the timeline. */
export const LIGHTEST_PATCH: Record<FixedSkyState, { desktop: number; phone: number }> = { export const LIGHTEST_PATCH: Record<FixedSkyState, { desktop: number; phone: number }> = {

View file

@ -0,0 +1,47 @@
// The place the sky is over, and the one decision of which place is drawn. The store (skyState.ts) holds the place; this file is the only writer
// of it: the baked place's manifest, loaded once and shared, when the ridge planes are drawn, and the fallback view (view.ts FALLBACK_VIEW) when
// they are not (the manifest or its cards did not load), because the scene is then the sky alone over that view. So the sky, the weather, the
// rebuild key, the ink and the Auto timer all read the place the scene draws. Main-chunk safe: no sky, no ridge code, only the manifest parser,
// the fallback view and the store.
import type { BackgroundSceneConfig } from './tier';
import { loadManifest } from './ridge/manifest';
import type { RidgeManifest } from './ridge/manifest';
import { FALLBACK_VIEW } from './ridge/view';
import type { View } from './ridge/view';
import { setSkyPlace } from './skyState';
// Set when a build drew the sky alone, so a rebuild key made before the next build is for the view that is drawn.
let skyOnly = false;
/** A scene start is a fresh attempt at the planes. */
export function resetSkyPlanes(): void {
skyOnly = false;
}
/**
* Load the manifest of the place `config` names (unknown or absent: the index's default, as `loadManifest` decides) and make the view being
* drawn the sky's place. Safe to call whenever a reader wants the view: the load is memoised and setting the same place is not a change. A
* failed load is the fallback view, returned with its error so the scene can be the sky alone.
*/
export async function ensureSkyPlace(
config: Pick<BackgroundSceneConfig, 'place'> | undefined
): Promise<{ manifest: RidgeManifest | null; view: View; fail: Error | null }> {
let manifest: RidgeManifest | null = null;
let fail: Error | null = null;
try {
manifest = await loadManifest(import.meta.env.BASE_URL, config?.place);
} catch (e) {
fail = e instanceof Error ? e : new Error(String(e));
}
const view = manifest && !skyOnly ? manifest.view : FALLBACK_VIEW;
setSkyPlace(view.place);
return { manifest, view, fail };
}
/** A build has settled what it draws: the manifest's planes (the manifest), or the sky alone (null). Makes that view's place the sky's and returns the view. */
export function drawnView(manifest: RidgeManifest | null): View {
skyOnly = manifest === null;
const view = manifest?.view ?? FALLBACK_VIEW;
setSkyPlace(view.place);
return view;
}

View file

@ -1,12 +1,17 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { atStandardTime } from './standardTime.testkit'; import { atSolarTime } from './ridge/skyTestkit';
import { import { FALLBACK_VIEW } from './ridge/view';
SKY_STATE_KEY, import { sceneThemeId } from './skyTheme';
resolveSkyState, import { SKY_CHOICE_KEY } from './skyState';
type SkyState, import type { SkyChoice } from './ridge/skyMoment';
} from './skyState';
type Mod = typeof import('./skyState'); type Mod = typeof import('./skyState');
const VIENNA = FALLBACK_VIEW.place;
const OLD_KEY = 'ratatoskr.skyState';
const noon: SkyChoice = { kind: 'named', id: 'noon' };
const dusk: SkyChoice = { kind: 'named', id: 'dusk' };
const night: SkyChoice = { kind: 'named', id: 'night' };
const auto: SkyChoice = { kind: 'auto' };
function fakeStorage(initial: Record<string, string> = {}) { function fakeStorage(initial: Record<string, string> = {}) {
const data = new Map(Object.entries(initial)); const data = new Map(Object.entries(initial));
@ -16,6 +21,9 @@ function fakeStorage(initial: Record<string, string> = {}) {
setItem: (k: string, v: string) => { setItem: (k: string, v: string) => {
data.set(k, v); data.set(k, v);
}, },
removeItem: (k: string) => {
data.delete(k);
},
}; };
} }
const fresh = (): Promise<Mod> => { const fresh = (): Promise<Mod> => {
@ -27,31 +35,74 @@ afterEach(() => {
vi.unstubAllGlobals(); vi.unstubAllGlobals();
}); });
describe('sky state', () => { describe('persistence', () => {
let storage: ReturnType<typeof fakeStorage>; let storage: ReturnType<typeof fakeStorage>;
beforeEach(() => { beforeEach(() => {
storage = fakeStorage(); storage = fakeStorage();
vi.stubGlobal('localStorage', storage); vi.stubGlobal('localStorage', storage);
}); });
it('defaults to auto when nothing is stored', async () => { it('defaults to Auto when nothing is stored', async () => {
expect((await fresh()).getSkyState()).toBe('auto'); expect((await fresh()).getSkyChoice()).toEqual(auto);
}); });
it.each(['night', 'day', 'dusk', 'auto'] as const)('restores a stored %s', async (s) => { it.each([auto, noon, night, { kind: 'free', date: '2026-12-21', minutes: 400 }] as SkyChoice[])(
storage.data.set(SKY_STATE_KEY, s); 'restores a stored %j',
expect((await fresh()).getSkyState()).toBe(s); async (c) => {
}); storage.data.set(SKY_CHOICE_KEY, JSON.stringify(c));
expect((await fresh()).getSkyChoice()).toEqual(c);
it.each(['', 'noon', 'NIGHT', '"night"', 'null'])(
'falls back to auto on stored %j',
async (v) => {
storage.data.set(SKY_STATE_KEY, v);
expect((await fresh()).getSkyState()).toBe('auto');
} }
); );
it('falls back to auto when storage throws', async () => { it.each([
'',
'night',
'null',
'{',
JSON.stringify({ kind: 'named', id: 'midday' }),
JSON.stringify({ kind: 'named' }),
JSON.stringify({ kind: 'free', date: '1899-12-31', minutes: 0 }),
JSON.stringify({ kind: 'free', date: '2101-01-01', minutes: 0 }),
JSON.stringify({ kind: 'free', date: '2026-02-30', minutes: 0 }),
JSON.stringify({ kind: 'free', date: '2026-06-21', minutes: 1440 }),
JSON.stringify({ kind: 'free', date: '2026-06-21', minutes: -1 }),
JSON.stringify({ kind: 'free', date: '2026-06-21', minutes: 1.5 }),
JSON.stringify({ kind: 'free', date: 20260621, minutes: 5 }),
])('reads %j as Auto', async (v) => {
storage.data.set(SKY_CHOICE_KEY, v);
expect((await fresh()).getSkyChoice()).toEqual(auto);
});
it.each([
['auto', auto],
['day', noon],
['dusk', dusk],
['night', night],
] as const)('migrates the old key %s to %j once, and removes it', async (old, want) => {
storage.data.set(OLD_KEY, old);
const m = await fresh();
expect(m.getSkyChoice()).toEqual(want);
expect(storage.data.has(OLD_KEY)).toBe(false);
expect(JSON.parse(storage.data.get(SKY_CHOICE_KEY) as string)).toEqual(want);
m.setSkyChoice(dusk);
expect(storage.data.has(OLD_KEY)).toBe(false);
expect((await fresh()).getSkyChoice()).toEqual(dusk);
});
it.each(['noon', 'NIGHT', '', '"night"', 'null'])('ignores the old key holding %j, and removes it', async (old) => {
storage.data.set(OLD_KEY, old);
expect((await fresh()).getSkyChoice()).toEqual(auto);
expect(storage.data.has(OLD_KEY)).toBe(false);
});
it('the new key wins over a stale old one', async () => {
storage.data.set(OLD_KEY, 'night');
storage.data.set(SKY_CHOICE_KEY, JSON.stringify(dusk));
expect((await fresh()).getSkyChoice()).toEqual(dusk);
expect(storage.data.has(OLD_KEY)).toBe(false);
});
it('keeps the pick for the page load when storage is refused', async () => {
vi.stubGlobal('localStorage', { vi.stubGlobal('localStorage', {
getItem: () => { getItem: () => {
throw new Error('denied'); throw new Error('denied');
@ -59,70 +110,154 @@ describe('sky state', () => {
setItem: () => { setItem: () => {
throw new Error('denied'); throw new Error('denied');
}, },
removeItem: () => {
throw new Error('denied');
},
}); });
const m = await fresh(); const m = await fresh();
expect(m.getSkyState()).toBe('auto'); expect(m.getSkyChoice()).toEqual(auto);
m.setSkyState('night'); m.setSkyChoice(night);
expect(m.getSkyState()).toBe('night'); expect(m.getSkyChoice()).toEqual(night);
}); });
it('persists a set state under one key and reads it back after a reload', async () => { it('migrates an old pick even when the new key cannot be written: the pick holds for the page load, the old key stays', async () => {
(await fresh()).setSkyState('dusk'); storage.data.set(OLD_KEY, 'day');
expect([...storage.data.entries()]).toEqual([[SKY_STATE_KEY, 'dusk']]); vi.stubGlobal('localStorage', {
expect((await fresh()).getSkyState()).toBe('dusk'); ...storage,
setItem: () => {
throw new Error('denied');
},
});
expect((await fresh()).getSkyChoice()).toEqual(noon);
expect(storage.data.has(OLD_KEY)).toBe(true);
}); });
it('ignores an invalid state', async () => { it('writes the new key before it removes the old one', async () => {
storage.data.set(OLD_KEY, 'dusk');
const order: string[] = [];
vi.stubGlobal('localStorage', {
...storage,
setItem: (k: string, v: string) => {
order.push(`set ${k}`);
storage.data.set(k, v);
},
removeItem: (k: string) => {
order.push(`remove ${k}`);
storage.data.delete(k);
},
});
expect((await fresh()).getSkyChoice()).toEqual(dusk);
expect(order).toEqual([`set ${SKY_CHOICE_KEY}`, `remove ${OLD_KEY}`]);
});
it('persists a set choice under one key and reads it back after a reload', async () => {
(await fresh()).setSkyChoice(dusk);
expect([...storage.data.entries()]).toEqual([[SKY_CHOICE_KEY, JSON.stringify(dusk)]]);
expect((await fresh()).getSkyChoice()).toEqual(dusk);
});
it('ignores an invalid choice', async () => {
const m = await fresh(); const m = await fresh();
m.setSkyState('night'); m.setSkyChoice(night);
m.setSkyState('noon' as SkyState); m.setSkyChoice({ kind: 'named', id: 'midday' } as unknown as SkyChoice);
expect(m.getSkyState()).toBe('night'); expect(m.getSkyChoice()).toEqual(night);
expect(storage.data.get(SKY_STATE_KEY)).toBe('night');
}); });
it('notifies subscribers on change only, and stops after unsubscribe', async () => { it('notifies subscribers on change only, and stops after unsubscribe', async () => {
const m = await fresh(); const m = await fresh();
m.setSkyPlace(VIENNA);
const cb = vi.fn(); const cb = vi.fn();
const off = m.subscribe(cb); const off = m.subscribe(cb);
m.setSkyState('day'); m.setSkyChoice(noon);
m.setSkyState('day'); m.setSkyChoice(noon);
expect(cb.mock.calls).toEqual([['day']]); expect(cb).toHaveBeenCalledTimes(1);
off(); off();
m.setSkyState('night'); m.setSkyChoice(night);
expect(cb).toHaveBeenCalledTimes(1); expect(cb).toHaveBeenCalledTimes(1);
}); });
it('tells a late subscriber nothing until the next change', async () => { it('tells a late subscriber nothing until the next change', async () => {
const m = await fresh(); const m = await fresh();
m.setSkyState('day'); m.setSkyChoice(noon);
const cb = vi.fn(); const cb = vi.fn();
m.subscribe(cb); m.subscribe(cb);
expect(cb).not.toHaveBeenCalled(); expect(cb).not.toHaveBeenCalled();
}); });
}); });
describe('auto follows the clock', () => { describe('one authority: the choice at the place decides the sky and the ink', () => {
const local = (h: number, m = 0) => atStandardTime(h, m); // local solar time ~ local clock let m: Mod;
let storage: ReturnType<typeof fakeStorage>; beforeEach(async () => {
vi.stubGlobal('localStorage', fakeStorage());
m = await fresh();
m.setSkyClock(() => atSolarTime(0, 0));
});
it('Noon picked at local midnight is day, and the ink theme is Noonday Sky', () => {
m.setSkyPlace(VIENNA);
m.setSkyChoice(noon);
expect(m.getResolvedSkyState()).toBe('day');
expect(sceneThemeId(m.getResolvedSkyState(), true)).toBe('noonday-sky');
});
it('Night picked at noon is night, and the ink theme is Midnight Sky', () => {
m.setSkyPlace(VIENNA);
m.setSkyClock(() => atSolarTime(12, 0));
m.setSkyChoice(night);
expect(m.getResolvedSkyState()).toBe('night');
expect(sceneThemeId(m.getResolvedSkyState(), true)).toBe('midnight-sky');
});
it('a free moment is its own sky: December at 06:40 Vienna is dusk or night, July at 13:00 day', () => {
m.setSkyPlace(VIENNA);
m.setSkyChoice({ kind: 'free', date: '2026-12-21', minutes: 6 * 60 + 40 });
expect(m.getResolvedSkyState()).toBe('night');
m.setSkyChoice({ kind: 'free', date: '2026-07-15', minutes: 13 * 60 });
expect(m.getResolvedSkyState()).toBe('day');
});
it('with no place the resolved sky is undefined and the theme is not decided', () => {
m.setSkyChoice(noon);
expect(m.getResolvedSkyState()).toBeUndefined();
expect(sceneThemeId(m.getResolvedSkyState(), true)).toBeUndefined();
});
it('setting the place tells the listeners, once', () => {
const cb = vi.fn();
m.subscribe(cb);
m.setSkyPlace(VIENNA);
m.setSkyPlace({ ...VIENNA });
expect(cb.mock.calls).toEqual([['night']]);
expect(m.getSkyPlace()).toEqual(VIENNA);
});
});
describe('Auto follows the clock', () => {
const local = (h: number, m = 0) => atSolarTime(h, m);
beforeEach(() => { beforeEach(() => {
vi.useFakeTimers(); vi.useFakeTimers();
storage = fakeStorage(); vi.stubGlobal('localStorage', fakeStorage());
vi.stubGlobal('localStorage', storage);
}); });
afterEach(() => { afterEach(() => {
vi.useRealTimers(); vi.useRealTimers();
}); });
it('resolves noon to day, midnight to night and the twilight after sunset to dusk', () => { it('is the real sun over the place: noon is day, midnight night and the twilight after sunset dusk', async () => {
expect(resolveSkyState('auto', local(12))).toBe('day'); const m = await fresh();
expect(resolveSkyState('auto', local(0))).toBe('night'); m.setSkyPlace(VIENNA);
expect(resolveSkyState('auto', local(18, 10))).toBe('dusk'); const at = (t: Date) => {
expect(resolveSkyState('auto', local(5, 50))).toBe('dusk'); m.setSkyClock(() => t);
expect(resolveSkyState('day', local(0))).toBe('day'); return m.getResolvedSkyState();
};
expect(at(local(12))).toBe('day');
expect(at(local(0))).toBe('night');
expect(at(local(18, 10))).toBe('dusk');
expect(at(local(5, 50))).toBe('dusk');
}); });
it('tells listeners the resolved sky when the clock crosses a boundary, and only then', async () => { it('tells listeners the resolved sky when the clock crosses a boundary, and only then', async () => {
const m = await fresh(); const m = await fresh();
m.setSkyPlace(VIENNA);
let now = local(17, 0); let now = local(17, 0);
m.setSkyClock(() => now); m.setSkyClock(() => now);
const cb = vi.fn(); const cb = vi.fn();
@ -139,6 +274,7 @@ describe('auto follows the clock', () => {
it('still tells everyone when a listener comes or goes inside the window before the clock crosses', async () => { it('still tells everyone when a listener comes or goes inside the window before the clock crosses', async () => {
const m = await fresh(); const m = await fresh();
m.setSkyPlace(VIENNA);
let now = local(17, 0); let now = local(17, 0);
m.setSkyClock(() => now); m.setSkyClock(() => now);
const [a, b, late] = [vi.fn(), vi.fn(), vi.fn()]; const [a, b, late] = [vi.fn(), vi.fn(), vi.fn()];
@ -155,25 +291,46 @@ describe('auto follows the clock', () => {
offLate(); offLate();
}); });
it('keeps no timer without listeners or when a fixed state is chosen', async () => { it('keeps no timer without listeners or when a free moment is chosen; one timer serves Auto and a named moment', async () => {
const m = await fresh(); const m = await fresh();
const off = m.subscribe(() => undefined); const off = m.subscribe(() => undefined);
expect(vi.getTimerCount()).toBe(1); expect(vi.getTimerCount()).toBe(1);
m.setSkyState('night'); m.setSkyChoice({ kind: 'free', date: '2026-07-01', minutes: 600 });
expect(vi.getTimerCount()).toBe(0); expect(vi.getTimerCount()).toBe(0);
m.setSkyState('auto'); m.setSkyChoice(night);
expect(vi.getTimerCount()).toBe(1);
m.setSkyChoice(auto);
expect(vi.getTimerCount()).toBe(1); expect(vi.getTimerCount()).toBe(1);
off(); off();
expect(vi.getTimerCount()).toBe(0); expect(vi.getTimerCount()).toBe(0);
}); });
it('a named moment is told again when the place-local day rolls over, once, and not before', async () => {
const m = await fresh();
m.setSkyPlace(VIENNA);
m.setSkyChoice(noon);
let now = new Date('2026-06-21T21:30:00Z'); // 23:30 in Vienna
m.setSkyClock(() => now);
const cb = vi.fn();
const off = m.subscribe(cb);
vi.advanceTimersByTime(10 * 60_000);
expect(cb).not.toHaveBeenCalled();
now = new Date('2026-06-21T22:05:00Z'); // 00:05 on the 22nd
vi.advanceTimersByTime(60_000);
expect(cb).toHaveBeenCalledTimes(1);
vi.advanceTimersByTime(60 * 60_000);
expect(cb).toHaveBeenCalledTimes(1);
off();
});
it('notifies a change of choice with the resolved sky', async () => { it('notifies a change of choice with the resolved sky', async () => {
const m = await fresh(); const m = await fresh();
m.setSkyPlace(VIENNA);
m.setSkyClock(() => local(12)); m.setSkyClock(() => local(12));
const cb = vi.fn(); const cb = vi.fn();
m.subscribe(cb); m.subscribe(cb);
m.setSkyState('night'); m.setSkyChoice(night);
m.setSkyState('auto'); m.setSkyChoice(auto);
expect(cb.mock.calls).toEqual([['night'], ['day']]); expect(cb.mock.calls).toEqual([['night'], ['day']]);
}); });
}); });
@ -188,40 +345,41 @@ describe('the constellation lines toggle', () => {
it('are off by default, and a first pick of Night is a plain choice that leaves them off', async () => { it('are off by default, and a first pick of Night is a plain choice that leaves them off', async () => {
const m = await fresh(); const m = await fresh();
expect(m.getConstellationLines()).toBe(false); expect(m.getConstellationLines()).toBe(false);
m.pickSkyState('night'); m.pickSkyChoice(night);
expect(m.getSkyState()).toBe('night'); expect(m.getSkyChoice()).toEqual(night);
expect(m.getConstellationLines()).toBe(false); expect(m.getConstellationLines()).toBe(false);
}); });
it('re-picking Night while the choice is Night toggles them, tells the listeners, and keeps the choice', async () => { it('re-picking Night while the choice is Night toggles them, tells the listeners, and keeps the choice', async () => {
const m = await fresh(); const m = await fresh();
m.pickSkyState('night'); m.setSkyPlace(VIENNA);
m.pickSkyChoice(night);
const cb = vi.fn(); const cb = vi.fn();
m.subscribe(cb); m.subscribe(cb);
m.pickSkyState('night'); m.pickSkyChoice(night);
expect(m.getConstellationLines()).toBe(true); expect(m.getConstellationLines()).toBe(true);
expect(cb.mock.calls).toEqual([['night']]); expect(cb.mock.calls).toEqual([['night']]);
expect(m.getSkyState()).toBe('night'); expect(m.getSkyChoice()).toEqual(night);
m.pickSkyState('night'); m.pickSkyChoice(night);
expect(m.getConstellationLines()).toBe(false); expect(m.getConstellationLines()).toBe(false);
expect(cb).toHaveBeenCalledTimes(2); expect(cb).toHaveBeenCalledTimes(2);
}); });
it('are not toggled by re-picking any other state, nor by picking Night from Auto that resolves to night', async () => { it('are not toggled by re-picking any other choice, nor by picking Night from Auto that is drawing night', async () => {
const m = await fresh(); const m = await fresh();
m.pickSkyState('day'); m.pickSkyChoice(noon);
m.pickSkyState('day'); m.pickSkyChoice(noon);
expect(m.getConstellationLines()).toBe(false); expect(m.getConstellationLines()).toBe(false);
m.setSkyClock(() => new Date('2026-12-04T00:00:00Z')); m.setSkyClock(() => new Date('2026-12-04T00:00:00Z'));
m.pickSkyState('auto'); m.pickSkyChoice(auto);
m.pickSkyState('night'); m.pickSkyChoice(night);
expect(m.getConstellationLines()).toBe(false); expect(m.getConstellationLines()).toBe(false);
}); });
it('persist per viewer, and come back from storage', async () => { it('persist per viewer, and come back from storage', async () => {
const m = await fresh(); const m = await fresh();
m.pickSkyState('night'); m.pickSkyChoice(night);
m.pickSkyState('night'); m.pickSkyChoice(night);
expect(storage.data.get(m.SKY_LINES_KEY)).toBe('on'); expect(storage.data.get(m.SKY_LINES_KEY)).toBe('on');
const again = await fresh(); const again = await fresh();
expect(again.getConstellationLines()).toBe(true); expect(again.getConstellationLines()).toBe(true);
@ -235,11 +393,14 @@ describe('the constellation lines toggle', () => {
setItem: () => { setItem: () => {
throw new Error('denied'); throw new Error('denied');
}, },
removeItem: () => {
throw new Error('denied');
},
}); });
const m = await fresh(); const m = await fresh();
expect(m.getConstellationLines()).toBe(false); expect(m.getConstellationLines()).toBe(false);
m.pickSkyState('night'); m.pickSkyChoice(night);
m.pickSkyState('night'); m.pickSkyChoice(night);
expect(m.getConstellationLines()).toBe(true); expect(m.getConstellationLines()).toBe(true);
}); });
}); });

View file

@ -1,54 +1,73 @@
// Which sky the signed-out page is drawn against. The choice is one value, kept in one // Which sky the signed-out page is drawn against: three small stores and the notice that one of them moved. The viewer's choice (Auto, a
// localStorage key; whoever draws the sky (the scene, the title bar's control) reads it here. // named moment, a free moment), the place the sky is over, and the constellation lines. They decide nothing: which instant is drawn is
// 'auto' is a choice, not a sky: it resolves from the clock to day, dusk or night // `momentFor` and which band it is, `skyBand` (ridge/skyMoment.ts); the resolved sky here is those two applied to the stores.
// (`resolveSkyState`), and every sky drawn is one of those three. import { MOMENT_IDS, FREE_DATE_MAX, FREE_DATE_MIN, isDate, momentFor, momentKey, skyBand } from './ridge/skyMoment';
import { sunElevation } from '../../../sky/sun.js'; import type { FixedSkyState, MomentId, SkyChoice } from './ridge/skyMoment';
import { sunAt } from './ridge/sunAt';
import type { Place } from './ridge/view';
export type SkyState = 'auto' | 'day' | 'dusk' | 'night'; export const SKY_CHOICE_KEY = 'ratatoskr.skyChoice';
export const SKY_STATES: readonly SkyState[] = ['auto', 'day', 'dusk', 'night']; const AUTO: SkyChoice = { kind: 'auto' };
export const SKY_STATE_KEY = 'ratatoskr.skyState';
const isSkyState = (v: unknown): v is SkyState => SKY_STATES.includes(v as SkyState); /** A stored value as a choice, or undefined when it is not one (wrong shape, unknown moment, a date outside 1900..2100, minutes outside 0..1439). */
export function parseSkyChoice(raw: unknown): SkyChoice | undefined {
if (typeof raw !== 'object' || raw === null) return undefined;
const c = raw as Record<string, unknown>;
if (c.kind === 'auto') return AUTO;
if (c.kind === 'named' && MOMENT_IDS.includes(c.id as MomentId)) {
return { kind: 'named', id: c.id as MomentId };
}
if (
c.kind === 'free' &&
isDate(c.date) &&
c.date >= FREE_DATE_MIN &&
c.date <= FREE_DATE_MAX &&
Number.isInteger(c.minutes) &&
(c.minutes as number) >= 0 &&
(c.minutes as number) <= 1439
) {
return { kind: 'free', date: c.date, minutes: c.minutes as number };
}
return undefined;
}
function load(): SkyState { const same = (a: SkyChoice, b: SkyChoice): boolean => JSON.stringify(a) === JSON.stringify(b);
// The sky menu once held Auto, Day, Dusk and Night under another key. It is read once, here, and removed: Day became Noon.
const OLD_KEY = 'ratatoskr.skyState';
const FROM_OLD = new Map<string, SkyChoice>([
['auto', AUTO],
['day', { kind: 'named', id: 'noon' }],
['dusk', { kind: 'named', id: 'dusk' }],
['night', { kind: 'named', id: 'night' }],
]);
function load(): SkyChoice {
try { try {
const stored = localStorage.getItem(SKY_STATE_KEY); const old = localStorage.getItem(OLD_KEY);
return isSkyState(stored) ? stored : 'auto'; if (old !== null) {
const migrated = FROM_OLD.get(old);
if (migrated && localStorage.getItem(SKY_CHOICE_KEY) === null) {
try {
// The new key first: a refusal leaves the old one in place, and the pick holds for this page load.
localStorage.setItem(SKY_CHOICE_KEY, JSON.stringify(migrated));
} catch { } catch {
return 'auto'; return migrated;
}
localStorage.removeItem(OLD_KEY);
return migrated;
}
localStorage.removeItem(OLD_KEY);
}
const stored = localStorage.getItem(SKY_CHOICE_KEY);
return (stored !== null && parseSkyChoice(JSON.parse(stored))) || AUTO;
} catch {
return AUTO;
} }
} }
/**
* The three skies ever drawn. Each has the luminance band its theme ink needs against bare sky (WCAG relative luminance,
* the `luminance` of src/sky/skyTokens.js): day, at least 0.2983 (the dark text ink #342d25); dusk, at least 0.4554 (the link
* #2a4f27); night, at most 0.0931 (the light text ink #aeccff). The ridge scene's display budgets (ridge/toneMap.ts `BUDGET`)
* sit inside them.
*/
export type FixedSkyState = 'day' | 'dusk' | 'night';
/** Where the clock puts the sun: the latitude the skies are baked for (src/sky/skyTokens.js MOMENTS), the longitude of this timezone. */
const LAT = 45;
/** Sun elevation (degrees) from which it is day, and below the negative of which it is night; between, dusk (dawn included). */
export const DAY_FROM = 6;
let clock: () => Date = () => new Date(); let clock: () => Date = () => new Date();
/** Minutes west of UTC of this timezone's standard time (the larger of its January and July offsets), so daylight saving does not move the sun. */
export const standardOffsetMinutes = (now: Date): number =>
Math.max(
new Date(now.getFullYear(), 0, 1).getTimezoneOffset(),
new Date(now.getFullYear(), 6, 1).getTimezoneOffset()
);
/** The fixed sky a choice draws now: itself, or for 'auto' the sky the sun's elevation here calls for. */
export function resolveSkyState(s: SkyState, now: Date = clock()): FixedSkyState {
if (s !== 'auto') return s;
const lon = -standardOffsetMinutes(now) / 4;
const el = sunElevation(now, LAT, lon) as number;
if (el >= DAY_FROM) return 'day';
return el <= -DAY_FROM ? 'night' : 'dusk';
}
/** The constellation lines (a hidden extra, ruling ridge-constellation-lines-hidden-extra): on or off, per viewer, off by default. */ /** The constellation lines (a hidden extra, ruling ridge-constellation-lines-hidden-extra): on or off, per viewer, off by default. */
export const SKY_LINES_KEY = 'ratatoskr.skyLines'; export const SKY_LINES_KEY = 'ratatoskr.skyLines';
@ -66,55 +85,67 @@ export const getConstellationLines = (): boolean => {
return lines; return lines;
}; };
let current: SkyState | undefined; let current: SkyChoice | undefined;
const listeners = new Set<(s: FixedSkyState) => void>(); let place: Place | undefined;
const listeners = new Set<(s: FixedSkyState | undefined) => void>();
let timer: ReturnType<typeof setTimeout> | undefined; let timer: ReturnType<typeof setTimeout> | undefined;
let shown: FixedSkyState | undefined; let shown: FixedSkyState | undefined;
let shownKey: string | undefined;
const TICK_MS = 60_000; const TICK_MS = 60_000;
/** The choice (what the control shows). */ /** The choice (what the control shows). */
export const getSkyState = (): SkyState => { export const getSkyChoice = (): SkyChoice => {
current ??= load(); current ??= load();
return current; return current;
}; };
/** The sky being drawn: the choice, resolved. */ /** The place the sky is over: the loaded manifest's, set by skyPlace.ts; undefined until one is known. */
export const getResolvedSkyState = (): FixedSkyState => resolveSkyState(getSkyState()); export const getSkyPlace = (): Place | undefined => place;
/** The moment the sky is drawn for: the real time, or the test clock. */
export const skyNow = (): Date => clock();
/** The band being drawn: the choice at the place, through `momentFor` and `skyBand`; undefined until a place is known (no sky is drawn for ink). */
export const getResolvedSkyState = (): FixedSkyState | undefined =>
place && skyBand(sunAt(place, momentFor(getSkyChoice(), place, skyNow())).elevation);
/** What a rebuild would be for, of the moment now drawn (`momentKey`): a named moment's changes when the place-local day rolls over. */
const drawnKey = (): string | undefined => place && momentKey(getSkyChoice(), place, skyNow());
const emit = () => { const emit = () => {
shown = getResolvedSkyState(); shown = getResolvedSkyState();
[...listeners].forEach((cb) => cb(shown as FixedSkyState)); shownKey = drawnKey();
[...listeners].forEach((cb) => cb(shown));
}; };
// While anyone listens and the choice is 'auto', one timer checks the clock each minute and tells // While anyone listens and the choice is Auto or a named moment, one timer checks the clock each minute and tells
// listeners when the resolved sky changes from the one last told (`shown`, set when telling and when the // listeners when the resolved band, or the moment drawn (an Auto band, a named moment's place-local day), changes from the one
// first listener arrives, never by a later arrival or departure). Otherwise there is no timer. // last told (`shown` and `shownKey`, set when telling and when the first listener arrives, never by a later arrival or departure).
// A free moment does not move with the clock, so it has no timer.
function sync(): void { function sync(): void {
clearTimeout(timer); clearTimeout(timer);
timer = undefined; timer = undefined;
if (listeners.size === 0 || getSkyState() !== 'auto') return; if (listeners.size === 0 || getSkyChoice().kind === 'free') return;
const tick = () => { const tick = () => {
if (getResolvedSkyState() !== shown) emit(); if (getResolvedSkyState() !== shown || drawnKey() !== shownKey) emit();
timer = setTimeout(tick, TICK_MS); timer = setTimeout(tick, TICK_MS);
}; };
timer = setTimeout(tick, TICK_MS); timer = setTimeout(tick, TICK_MS);
} }
/** The moment the sky is drawn for: the real time, or the test clock. */
export const skyNow = (): Date => clock();
/** Replace the clock (tests); no argument restores the real one. */ /** Replace the clock (tests); no argument restores the real one. */
export function setSkyClock(now?: () => Date): void { export function setSkyClock(now?: () => Date): void {
clock = now ?? (() => new Date()); clock = now ?? (() => new Date());
sync(); sync();
} }
export function setSkyState(s: SkyState): void { export function setSkyChoice(c: SkyChoice): void {
if (!isSkyState(s)) return; const next = parseSkyChoice(c);
const changed = s !== getSkyState(); if (!next) return;
current = s; const changed = !same(next, getSkyChoice());
current = next;
try { try {
localStorage.setItem(SKY_STATE_KEY, s); localStorage.setItem(SKY_CHOICE_KEY, JSON.stringify(next));
} catch { } catch {
// Storage is refused (private mode, quota): the choice holds for this page load only. // Storage is refused (private mode, quota): the choice holds for this page load only.
} }
@ -124,12 +155,22 @@ export function setSkyState(s: SkyState): void {
} }
} }
/** The place the sky is over (skyPlace.ts, once the manifest is loaded). Listeners hear it, since the band depends on it. */
export function setSkyPlace(p: Place | undefined): void {
if (p?.id === place?.id && p?.tz === place?.tz && p?.lat === place?.lat && p?.lon === place?.lon) {
return;
}
place = p;
emit();
}
/** /**
* A pick in the sky menu. Picking a state sets it; picking Night while the choice already is Night toggles the constellation lines, which * A pick in the sky menu. Picking a choice sets it; picking Night while the choice already is Night toggles the constellation lines, which
* listeners hear as a sky change (the scene is rebuilt for it: `ridgeSkyKey` carries the flag). * listeners hear as a sky change (the scene is rebuilt for it: `ridgeSkyKey` carries the flag).
*/ */
export function pickSkyState(s: SkyState): void { export function pickSkyChoice(c: SkyChoice): void {
if (s === 'night' && getSkyState() === 'night') { const now = getSkyChoice();
if (c.kind === 'named' && c.id === 'night' && now.kind === 'named' && now.id === 'night') {
lines = !getConstellationLines(); lines = !getConstellationLines();
try { try {
localStorage.setItem(SKY_LINES_KEY, lines ? 'on' : 'off'); localStorage.setItem(SKY_LINES_KEY, lines ? 'on' : 'off');
@ -139,12 +180,15 @@ export function pickSkyState(s: SkyState): void {
emit(); emit();
return; return;
} }
setSkyState(s); setSkyChoice(c);
} }
/** Listeners hear the resolved sky: on a change of choice, and while 'auto', when the clock crosses a boundary. */ /** Listeners hear the resolved band: on a change of choice or place, while Auto, when the clock crosses a band, and while a named moment, when the place-local day rolls over. */
export function subscribe(cb: (s: FixedSkyState) => void): () => void { export function subscribe(cb: (s: FixedSkyState | undefined) => void): () => void {
if (listeners.size === 0) shown = getResolvedSkyState(); if (listeners.size === 0) {
shown = getResolvedSkyState();
shownKey = drawnKey();
}
listeners.add(cb); listeners.add(cb);
sync(); sync();
return () => { return () => {

View file

@ -1,5 +1,5 @@
import { describe, expect, it, vi } from 'vitest'; import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import { atStandardTime } from './standardTime.testkit'; import { atSolarTime } from './ridge/skyTestkit';
import { baked } from '../../../sky/baked'; import { baked } from '../../../sky/baked';
import { AA, contrast } from '../../../sky/skyTokens.js'; import { AA, contrast } from '../../../sky/skyTokens.js';
import { Editor } from '../../components/editor/Editor.css'; import { Editor } from '../../components/editor/Editor.css';
@ -12,9 +12,14 @@ import { SkyPlate, plateRegions } from './skyPlate.css';
import { import {
getResolvedSkyState, getResolvedSkyState,
setSkyClock, setSkyClock,
setSkyPlace,
subscribe as subscribeSky, subscribe as subscribeSky,
} from './skyState'; } from './skyState';
import { sceneThemeId } from './skyTheme'; import { sceneThemeId } from './skyTheme';
import { FALLBACK_VIEW } from './ridge/view';
beforeAll(() => setSkyPlace(FALLBACK_VIEW.place));
afterAll(() => setSkyPlace(undefined));
const SKY = { 'midnight-sky': baked.midnight, 'noonday-sky': baked.noonday } as const; const SKY = { 'midnight-sky': baked.midnight, 'noonday-sky': baked.noonday } as const;
const r2 = (n: number) => n.toFixed(2); const r2 = (n: number) => n.toFixed(2);
@ -32,7 +37,7 @@ describe('sceneThemeId, the theme the page wears', () => {
it('auto draws the clock sky and that sky decides', () => { it('auto draws the clock sky and that sky decides', () => {
[0, 12, 23].forEach((h) => { [0, 12, 23].forEach((h) => {
setSkyClock(() => atStandardTime(h, 10)); setSkyClock(() => atSolarTime(h, 10));
expect(sceneThemeId(getResolvedSkyState(), true)).toBe( expect(sceneThemeId(getResolvedSkyState(), true)).toBe(
h === 12 ? 'noonday-sky' : 'midnight-sky' h === 12 ? 'noonday-sky' : 'midnight-sky'
); );
@ -40,6 +45,13 @@ describe('sceneThemeId, the theme the page wears', () => {
setSkyClock(); setSkyClock();
}); });
it('with no place known there is no drawn sky to follow: the theme is not decided', () => {
setSkyPlace(undefined);
expect(getResolvedSkyState()).toBeUndefined();
expect(sceneThemeId(getResolvedSkyState(), true)).toBeUndefined();
setSkyPlace(FALLBACK_VIEW.place);
});
it('with the scene off no sky is drawn, so the person theme stands', () => { it('with the scene off no sky is drawn, so the person theme stands', () => {
(['day', 'dusk', 'night'] as const).forEach((st) => (['day', 'dusk', 'night'] as const).forEach((st) =>
expect(sceneThemeId(st, false)).toBeUndefined() expect(sceneThemeId(st, false)).toBeUndefined()
@ -49,12 +61,12 @@ describe('sceneThemeId, the theme the page wears', () => {
it('the resolved sky a hook subscribes to changes as the clock crosses, so theme classes follow', () => { it('the resolved sky a hook subscribes to changes as the clock crosses, so theme classes follow', () => {
vi.useFakeTimers(); vi.useFakeTimers();
let hour = 12; let hour = 12;
setSkyClock(() => atStandardTime(hour, 10)); setSkyClock(() => atSolarTime(hour, 10));
const seen: string[] = []; const seen: Array<string | undefined> = [];
const off = subscribeSky((s) => seen.push(s)); const off = subscribeSky((s) => seen.push(s));
expect(getResolvedSkyState()).toBe('day'); expect(getResolvedSkyState()).toBe('day');
hour = 0; hour = 0;
setSkyClock(() => atStandardTime(hour, 10)); setSkyClock(() => atSolarTime(hour, 10));
vi.advanceTimersByTime(61_000); vi.advanceTimersByTime(61_000);
expect(seen).toEqual(['night']); expect(seen).toEqual(['night']);
expect(getResolvedSkyState()).toBe('night'); expect(getResolvedSkyState()).toBe('night');

View file

@ -1,8 +1,8 @@
// Which theme the drawn sky lights the page with. While a scene is on, the sky being drawn (the fixed pick, or the // Which theme the drawn sky lights the page with. While a scene is on, the sky being drawn (the
// clock's state under 'auto'; `useResolvedSkyState`) alone decides the theme and, with it, the ink: Day and Dusk // choice at the place; `useResolvedSkyState`) alone decides the theme and, with it, the ink: Day and Dusk
// wear Noonday Sky, Night wears Midnight Sky. A person's own theme (the theme menu) stands only where no sky is // wear Noonday Sky, Night wears Midnight Sky. A person's own theme (the theme menu) stands only where no sky is
// drawn, that is with the scene off. // drawn, that is with the scene off.
import type { FixedSkyState } from './skyState'; import type { FixedSkyState } from './ridge/skyMoment';
export type SkyThemeId = 'midnight-sky' | 'noonday-sky'; export type SkyThemeId = 'midnight-sky' | 'noonday-sky';
@ -13,5 +13,7 @@ const BY_STATE: Record<FixedSkyState, SkyThemeId> = {
}; };
/** The theme the page wears: the drawn sky's while a scene is on, otherwise none (the person's theme stands). */ /** The theme the page wears: the drawn sky's while a scene is on, otherwise none (the person's theme stands). */
export const sceneThemeId = (resolved: FixedSkyState, sceneOn: boolean): SkyThemeId | undefined => export const sceneThemeId = (
sceneOn ? BY_STATE[resolved] : undefined; resolved: FixedSkyState | undefined,
sceneOn: boolean
): SkyThemeId | undefined => (sceneOn && resolved ? BY_STATE[resolved] : undefined);

View file

@ -1,7 +0,0 @@
import { standardOffsetMinutes } from './skyState';
/** 22 September 2026 at h:m of local solar time as the sky clock reads it (standard time, whatever daylight saving says). */
export const atStandardTime = (h: number, m = 0): Date => {
const probe = new Date(2026, 8, 22);
return new Date(Date.UTC(2026, 8, 22, h, m) + standardOffsetMinutes(probe) * 60000);
};

View file

@ -1,19 +1,23 @@
import { useSyncExternalStore } from 'react'; import { useSyncExternalStore } from 'react';
import { import {
getResolvedSkyState, getResolvedSkyState,
getSkyState, getSkyChoice,
getSkyPlace,
subscribe, subscribe,
type FixedSkyState,
type SkyState,
} from '../features/scene/skyState'; } from '../features/scene/skyState';
import type { Place } from '../features/scene/ridge/view';
import type { FixedSkyState, SkyChoice } from '../features/scene/ridge/skyMoment';
import { getSceneDrawn, subscribeSceneDrawn } from '../features/scene/sceneDrawn'; import { getSceneDrawn, subscribeSceneDrawn } from '../features/scene/sceneDrawn';
/** The choice, as the control shows it ('auto' stays 'auto'). The sky being drawn is `useResolvedSkyState`. */ /** The choice, as the control shows it (Auto stays Auto). The sky being drawn is `useResolvedSkyState`. */
export const useSkyState = (): SkyState => useSyncExternalStore(subscribe, getSkyState); export const useSkyChoice = (): SkyChoice => useSyncExternalStore(subscribe, getSkyChoice);
/** The sky being drawn: day, dusk or night. Unlike the choice it changes as the clock crosses, so it re-renders. */ /** The sky being drawn: day, dusk or night, or undefined until the place is known. Unlike the choice it changes as the clock crosses under Auto, so it re-renders. */
export const useResolvedSkyState = (): FixedSkyState => export const useResolvedSkyState = (): FixedSkyState | undefined =>
useSyncExternalStore(subscribe, getResolvedSkyState); useSyncExternalStore(subscribe, getResolvedSkyState);
/** The place the sky is over, or undefined until a scene has settled what it draws (skyPlace.ts). */
export const useDrawnPlace = (): Place | undefined => useSyncExternalStore(subscribe, getSkyPlace);
/** Whether a background scene is drawing a sky right now (not merely configured): false on a failed or lost context. */ /** Whether a background scene is drawing a sky right now (not merely configured): false on a failed or lost context. */
export const useSceneOn = (): boolean => useSyncExternalStore(subscribeSceneDrawn, getSceneDrawn); export const useSceneOn = (): boolean => useSyncExternalStore(subscribeSceneDrawn, getSceneDrawn);

View file

@ -25,7 +25,7 @@ vi.mock('./useSkyState', async () => {
const drawn = await import('../features/scene/sceneDrawn'); const drawn = await import('../features/scene/sceneDrawn');
return { return {
useResolvedSkyState: () => 'night', useResolvedSkyState: () => 'night',
useSkyState: () => 'night', useSkyChoice: () => ({ kind: 'named', id: 'night' }),
useSceneOn: () => drawn.getSceneDrawn(), useSceneOn: () => drawn.getSceneDrawn(),
}; };
}); });