174 lines
7.9 KiB
TypeScript
174 lines
7.9 KiB
TypeScript
/**
|
|
* The ONLY place in the repository where the sun is computed (CLAUDE.md §7).
|
|
*
|
|
* NOAA's solar calculator, after Meeus, Astronomical Algorithms: the sun's
|
|
* declination and the equation of time at an instant, then the hour angle at
|
|
* which the sun's centre is 0.833° below the horizon (refraction plus its
|
|
* radius). Good to about a minute below 72° latitude.
|
|
*
|
|
* Every time returned is an instant (epoch milliseconds). Reading it on a clock
|
|
* is the app's job, with the city's zone, so a DST change moves only the clock
|
|
* (.agents/features/sun.md D3). The place is a city the player chose, or a guess
|
|
* from the device's zone: never GPS (CLAUDE.md §5.6 rule 6).
|
|
*/
|
|
import { addDays, isLocalDay, localDay, type LocalDay } from '../time/localDay.js';
|
|
|
|
export interface Place {
|
|
/** Degrees, north positive. */
|
|
readonly lat: number;
|
|
/** Degrees, east positive. */
|
|
readonly lon: number;
|
|
/** IANA zone whose local day is asked about. */
|
|
readonly timeZone: string;
|
|
}
|
|
|
|
/** A place with the name the player knows it by: a town they chose, or the guess. */
|
|
export interface NamedPlace extends Place {
|
|
readonly name: string;
|
|
/** Province, state or region, or ''. */
|
|
readonly region: string;
|
|
readonly country: string;
|
|
}
|
|
|
|
/**
|
|
* One local day of sun. Sunrise and sunset are the ones around this day's solar
|
|
* noon, so tonight's sunset may fall after midnight, on the next local day (D2).
|
|
*/
|
|
export type SunDay =
|
|
| { readonly kind: 'sun-sets'; readonly day: LocalDay; readonly sunrise: number; readonly solarNoon: number; readonly sunset: number }
|
|
/** The sun never sets. `lowestLight` is solar midnight, after this day's noon. */
|
|
| { readonly kind: 'polar-day'; readonly day: LocalDay; readonly solarNoon: number; readonly lowestLight: number }
|
|
/** The sun never rises. Solar noon is when the twilight is brightest. */
|
|
| { readonly kind: 'polar-night'; readonly day: LocalDay; readonly solarNoon: number };
|
|
|
|
const MINUTE = 60_000;
|
|
const DAY = 24 * 60 * MINUTE;
|
|
const RAD = Math.PI / 180;
|
|
/** The sun's centre at sunrise and sunset: 0.833° below the horizon. */
|
|
const ZENITH = 90.833 * RAD;
|
|
|
|
interface Sun {
|
|
/** Radians. */
|
|
readonly declination: number;
|
|
/** Minutes the true sun is ahead of the mean sun. */
|
|
readonly equationOfTime: number;
|
|
}
|
|
|
|
/** The sun's declination and the equation of time at an instant (NOAA). */
|
|
function sunAt(epochMs: number): Sun {
|
|
const T = (epochMs / DAY + 2440587.5 - 2451545) / 36525; // Julian centuries since J2000.0
|
|
const L0 = (((280.46646 + T * (36000.76983 + T * 0.0003032)) % 360) + 360) % 360;
|
|
const M = 357.52911 + T * (35999.05029 - 0.0001537 * T);
|
|
const e = 0.016708634 - T * (0.000042037 + 0.0000001267 * T);
|
|
const C = Math.sin(M * RAD) * (1.914602 - T * (0.004817 + 0.000014 * T))
|
|
+ Math.sin(2 * M * RAD) * (0.019993 - 0.000101 * T)
|
|
+ Math.sin(3 * M * RAD) * 0.000289;
|
|
const omega = 125.04 - 1934.136 * T;
|
|
const lambda = L0 + C - 0.00569 - 0.00478 * Math.sin(omega * RAD);
|
|
const eps0 = 23 + (26 + (21.448 - T * (46.815 + T * (0.00059 - T * 0.001813))) / 60) / 60;
|
|
const eps = (eps0 + 0.00256 * Math.cos(omega * RAD)) * RAD;
|
|
const y = Math.tan(eps / 2) ** 2;
|
|
const eq = y * Math.sin(2 * L0 * RAD) - 2 * e * Math.sin(M * RAD)
|
|
+ 4 * e * y * Math.sin(M * RAD) * Math.cos(2 * L0 * RAD)
|
|
- 0.5 * y * y * Math.sin(4 * L0 * RAD) - 1.25 * e * e * Math.sin(2 * M * RAD);
|
|
return { declination: Math.asin(Math.sin(eps) * Math.sin(lambda * RAD)), equationOfTime: (4 * eq) / RAD };
|
|
}
|
|
|
|
/** cos of the hour angle at sunrise and sunset. Above 1: never rises. Below -1: never sets. */
|
|
function cosHourAngle(lat: number, declination: number): number {
|
|
return Math.cos(ZENITH) / (Math.cos(lat * RAD) * Math.cos(declination)) - Math.tan(lat * RAD) * Math.tan(declination);
|
|
}
|
|
|
|
/** Solar noon nearest 12:00 mean solar time on the UTC date starting at `utcMidnight`. */
|
|
function solarNoonOn(utcMidnight: number, lon: number): number {
|
|
let noon = utcMidnight + (720 - 4 * lon) * MINUTE;
|
|
for (let i = 0; i < 2; i++) noon = utcMidnight + (720 - 4 * lon - sunAt(noon).equationOfTime) * MINUTE;
|
|
return noon;
|
|
}
|
|
|
|
/**
|
|
* Sunrise (`side` -1) or sunset (`side` +1) around the solar noon of the UTC date
|
|
* starting at `utcMidnight`, refined at its own instant. The date is passed in,
|
|
* never derived from noon: near 180° the noon itself can fall on the next UTC date.
|
|
* An hour angle out of range, only near the edge of polar day or night, is clamped (D5).
|
|
*/
|
|
function horizonCrossing(utcMidnight: number, noon: number, lat: number, lon: number, side: -1 | 1): number {
|
|
let at = noon;
|
|
for (let i = 0; i < 4; i++) {
|
|
const sun = sunAt(at);
|
|
const H = Math.acos(Math.min(1, Math.max(-1, cosHourAngle(lat, sun.declination)))) / RAD; // degrees
|
|
// Minutes from this UTC midnight; below 0 or above 1440 is the day before or after.
|
|
const fromMidnight = 720 - 4 * lon - sun.equationOfTime + side * 4 * H;
|
|
at = utcMidnight + fromMidnight * MINUTE;
|
|
}
|
|
return at;
|
|
}
|
|
|
|
function check(day: LocalDay, place: Place): number {
|
|
if (!isLocalDay(day)) throw new RangeError(`sunDay: '${day}' is not a LocalDay (YYYY-MM-DD)`);
|
|
const [y, m, d] = day.split('-').map(Number) as [number, number, number];
|
|
const utcMidnight = Date.UTC(y, m - 1, d);
|
|
if (new Date(utcMidnight).getUTCDate() !== d) throw new RangeError(`sunDay: ${day} does not exist`);
|
|
if (!(Math.abs(place.lat) <= 90)) throw new RangeError(`sunDay: latitude ${place.lat} is outside -90..90`);
|
|
if (!(Math.abs(place.lon) <= 180)) throw new RangeError(`sunDay: longitude ${place.lon} is outside -180..180`);
|
|
return utcMidnight;
|
|
}
|
|
|
|
/** The sun on one local day at one place. */
|
|
export function sunDay(day: LocalDay, place: Place): SunDay {
|
|
const { lat, lon, timeZone } = place;
|
|
let utcMidnight = check(day, place);
|
|
|
|
// The solar noon that falls on this local day. Zones far from their longitude
|
|
// (UTC+14 at 157° W) put it on the UTC date before or after. A clock twelve
|
|
// hours off the sun can leave a day with no noon at all; then the nearest is
|
|
// used (D8). No real zone is that far off.
|
|
let solarNoon = solarNoonOn(utcMidnight, lon);
|
|
for (let i = 0; i < 2; i++) {
|
|
const on = localDay(solarNoon, timeZone);
|
|
if (on === day) break;
|
|
utcMidnight += on < day ? DAY : -DAY;
|
|
solarNoon = solarNoonOn(utcMidnight, lon);
|
|
}
|
|
|
|
const c = cosHourAngle(lat, sunAt(solarNoon).declination);
|
|
if (c > 1) return { kind: 'polar-night', day, solarNoon };
|
|
// Solar midnight: halfway to the next solar noon.
|
|
if (c < -1) return { kind: 'polar-day', day, solarNoon, lowestLight: (solarNoon + solarNoonOn(utcMidnight + DAY, lon)) / 2 };
|
|
return {
|
|
kind: 'sun-sets', day, solarNoon,
|
|
sunrise: horizonCrossing(utcMidnight, solarNoon, lat, lon, -1),
|
|
sunset: horizonCrossing(utcMidnight, solarNoon, lat, lon, 1)
|
|
};
|
|
}
|
|
|
|
/**
|
|
* The next invitation at or after `now`, and the sun's day it belongs to. Yesterday
|
|
* is checked first: just after midnight in Reykjavík in June, last evening's sunset
|
|
* is still a few minutes away (D2).
|
|
*/
|
|
export function nextInvitation(now: number, place: Place): { readonly sun: SunDay; readonly at: number } {
|
|
if (!Number.isFinite(now)) throw new RangeError(`nextInvitation: now must be a finite instant, got ${String(now)}`);
|
|
const today = localDay(now, place.timeZone);
|
|
for (const offset of [-1, 0, 1, 2]) {
|
|
const sun = sunDay(addDays(today, offset), place);
|
|
const at = invitation(sun);
|
|
if (at >= now) return { sun, at };
|
|
}
|
|
// Unreachable: tomorrow's invitation is always after now. Kept so a broken sun fails loudly.
|
|
throw new Error(`nextInvitation: no invitation within two days of ${today}`);
|
|
}
|
|
|
|
/**
|
|
* When the game invites the player outside: the sunset; in polar day the lowest
|
|
* light; in polar night noon, when the twilight is brightest (D4; decided by the
|
|
* author, Q10).
|
|
*/
|
|
export function invitation(sun: SunDay): number {
|
|
switch (sun.kind) {
|
|
case 'sun-sets': return sun.sunset;
|
|
case 'polar-day': return sun.lowestLight;
|
|
case 'polar-night': return sun.solarNoon;
|
|
}
|
|
}
|