Ridge: viewpoint is the server location, horizon baked from Copernicus GLO-30, TAWES weather feed, day floor restored for 4.5:1 link
- VIENNA = 48.1929826 N, 16.3534237 E, 183 m (Meta, 2026-11-11); sun follows. - scripts/bake-horizon.py bakes viennaHorizon.json (720 azimuths: elevation, distance, peak height, slope) from nine GLO-30 tiles; source, licence and attribution are in the file's source block. horizon.ts reads it. Not yet drawn by the scene. - weatherFeed.ts: GeoSphere TAWES station 11035 (CC BY 4.0) to a weather number. Not yet wired to skyForState. - Day floor 0.4744 again (the dark link needs ~0.4554; the WIP floor 0.317 left it at 3.3:1). The three red tests of the WIP are green. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
3b1405907a
commit
bbfe664711
11 changed files with 275 additions and 9 deletions
123
scripts/bake-horizon.py
Normal file
123
scripts/bake-horizon.py
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Bake the 360 degree horizon seen from the ridge viewpoint (src/app/features/scene/ridge/vienna.ts: VIENNA) into
|
||||
src/app/features/scene/ridge/viennaHorizon.json: per azimuth, the highest elevation angle the terrain subtends, the distance and
|
||||
height of the point that sets it, and the surface slope there (the normal). The source is Copernicus DEM GLO-30, a DSM (it
|
||||
includes buildings and trees, which is what a horizon is made of). Source, licence and attribution go beside the bake, in its
|
||||
`source` block, so the file cannot travel without them.
|
||||
|
||||
python3 scripts/bake-horizon.py <dir with the nine Copernicus_DSM_COG_10_N{47..49}_00_E{015..017}_00_DEM.tif> [out.json]
|
||||
|
||||
Needs numpy, tifffile, imagecodecs (pip, in a venv: this is a build-time tool, the bake is committed).
|
||||
"""
|
||||
import json
|
||||
import math
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import tifffile
|
||||
|
||||
LAT, LON = 48.1929826, 16.3534237 # the server location Meta gave, 2026-11-11; keep equal to VIENNA in vienna.ts
|
||||
STEP_DEG = 0.5
|
||||
RADIUS_KM = 60.0
|
||||
EARTH_R = 6_371_000.0
|
||||
REFRACTION_K = 0.13 # standard terrestrial refraction: effective radius R / (1 - k)
|
||||
EYE_ABOVE_GROUND = 0.0 # the viewpoint is the DSM surface at the point (a roof, in a city); the page lifts it with VIENNA.altitudeKm
|
||||
MIN_KM = 1.0 # the DSM at 30 m cannot resolve neighbouring buildings as a horizon; nearer than this is not ridge
|
||||
|
||||
|
||||
class Mosaic:
|
||||
def __init__(self, folder: Path):
|
||||
self.tiles = {}
|
||||
for p in sorted(folder.glob("Copernicus_DSM_COG_10_N*_E*_DEM.tif")):
|
||||
lat0 = int(p.name.split("_N")[1][:2])
|
||||
lon0 = int(p.name.split("_E")[1][:3])
|
||||
with tifffile.TiffFile(p) as t:
|
||||
self.tiles[(lat0, lon0)] = t.pages[0].asarray()
|
||||
|
||||
def height(self, lat: float, lon: float) -> float:
|
||||
key = (math.floor(lat), math.floor(lon))
|
||||
a = self.tiles.get(key)
|
||||
if a is None:
|
||||
return float("nan")
|
||||
n = a.shape[0]
|
||||
# Tile origin is the north-west corner; pixels are 1/n degree, pixel-is-area (centre at +0.5).
|
||||
y = (key[0] + 1 - lat) * n - 0.5
|
||||
x = (lon - key[1]) * n - 0.5
|
||||
y0, x0 = int(math.floor(y)), int(math.floor(x))
|
||||
y0 = min(max(y0, 0), n - 2)
|
||||
x0 = min(max(x0, 0), n - 2)
|
||||
fy, fx = min(max(y - y0, 0), 1), min(max(x - x0, 0), 1)
|
||||
top = a[y0, x0] * (1 - fx) + a[y0, x0 + 1] * fx
|
||||
bot = a[y0 + 1, x0] * (1 - fx) + a[y0 + 1, x0 + 1] * fx
|
||||
return float(top * (1 - fy) + bot * fy)
|
||||
|
||||
|
||||
def offset(lat: float, lon: float, az_deg: float, d_m: float):
|
||||
az = math.radians(az_deg)
|
||||
dlat = d_m * math.cos(az) / 111_320.0
|
||||
dlon = d_m * math.sin(az) / (111_320.0 * math.cos(math.radians(lat)))
|
||||
return lat + dlat, lon + dlon
|
||||
|
||||
|
||||
def main() -> None:
|
||||
folder = Path(sys.argv[1])
|
||||
out = Path(sys.argv[2]) if len(sys.argv) > 2 else Path("src/app/features/scene/ridge/viennaHorizon.json")
|
||||
m = Mosaic(folder)
|
||||
h0 = m.height(LAT, LON) + EYE_ABOVE_GROUND
|
||||
az_count = int(360 / STEP_DEG)
|
||||
elev, dist, peak, east, north = [], [], [], [], []
|
||||
for i in range(az_count):
|
||||
az = i * STEP_DEG
|
||||
best, best_d, best_h, best_pt = -90.0, 0.0, h0, (LAT, LON)
|
||||
d = MIN_KM * 1000
|
||||
while d <= RADIUS_KM * 1000:
|
||||
lat, lon = offset(LAT, LON, az, d)
|
||||
h = m.height(lat, lon)
|
||||
if not math.isnan(h):
|
||||
drop = d * d / (2 * EARTH_R) * (1 - REFRACTION_K)
|
||||
ang = math.degrees(math.atan2(h - h0 - drop, d))
|
||||
if ang > best:
|
||||
best, best_d, best_h, best_pt = ang, d, h, (lat, lon)
|
||||
d += 30.0 if d < 5000 else 60.0 if d < 20000 else 120.0
|
||||
# Surface slope at the peak (rise per metre, east and north), central difference over 60 m.
|
||||
la, lo = best_pt
|
||||
dl, dn = 60.0 / 111_320.0, 60.0 / (111_320.0 * math.cos(math.radians(la)))
|
||||
ge = (m.height(la, lo + dn) - m.height(la, lo - dn)) / 120.0
|
||||
gn = (m.height(la + dl, lo) - m.height(la - dl, lo)) / 120.0
|
||||
elev.append(round(best, 3))
|
||||
dist.append(round(best_d / 1000, 2))
|
||||
peak.append(round(best_h, 1))
|
||||
east.append(round(ge, 3))
|
||||
north.append(round(gn, 3))
|
||||
doc = {
|
||||
"viewpoint": {"lat": LAT, "lon": LON, "groundM": round(h0, 1)},
|
||||
"stepDeg": STEP_DEG,
|
||||
"radiusKm": RADIUS_KM,
|
||||
"minKm": MIN_KM,
|
||||
"curvature": f"drop d^2/2R*(1-{REFRACTION_K}), R={int(EARTH_R)} m",
|
||||
"source": {
|
||||
"dataset": "Copernicus DEM GLO-30 (COP-DEM_GLO-30-DGED), a DSM, EGM2008 heights, 1 arc-second grid",
|
||||
"tiles": sorted(f"N{a:02d}_00_E{b:03d}_00" for a, b in m.tiles),
|
||||
"tileBytesEach": "about 42-44 MB (Cloud Optimized GeoTIFF); nine tiles, about 380 MB, read once, not committed",
|
||||
"url": "https://copernicus-dem-30m.s3.amazonaws.com/ (AWS Open Data, eu-central-1, no account)",
|
||||
"licence": "Copernicus DEM licence: free of charge for any use incl. commercial, attribution required, no warranty "
|
||||
"(https://spacedata.copernicus.eu/collections/copernicus-digital-elevation-model, Licencing)",
|
||||
"attribution": "Contains modified Copernicus data: DEM © DLR e.V. 2010-2014 and © Airbus Defence and Space GmbH 2014-2018 "
|
||||
"provided under COPERNICUS by the European Union and ESA; all rights reserved.",
|
||||
"bakedBy": "scripts/bake-horizon.py",
|
||||
},
|
||||
"elevationDeg": elev,
|
||||
"distanceKm": dist,
|
||||
"peakHeightM": peak,
|
||||
"slopeEast": east,
|
||||
"slopeNorth": north,
|
||||
}
|
||||
out.write_text(json.dumps(doc, separators=(",", ":")) + "\n")
|
||||
top = int(np.argmax(elev))
|
||||
print(f"ground {h0:.1f} m; {az_count} azimuths; highest {elev[top]:.2f} deg at az {top * STEP_DEG}, {dist[top]} km, {peak[top]} m")
|
||||
print(f"wrote {out} ({out.stat().st_size} bytes)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
27
src/app/features/scene/ridge/horizon.test.ts
Normal file
27
src/app/features/scene/ridge/horizon.test.ts
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import bake from './viennaHorizon.json';
|
||||
import { VIENNA } from './vienna';
|
||||
import { horizonDistanceKm, horizonElevation, horizonNormal } from './horizon';
|
||||
|
||||
describe('the baked horizon', () => {
|
||||
it('was baked from the viewpoint the sun is computed for', () => {
|
||||
expect(bake.viewpoint.lat).toBe(VIENNA.lat);
|
||||
expect(bake.viewpoint.lon).toBe(VIENNA.lon);
|
||||
expect(bake.viewpoint.groundM / 1000).toBeCloseTo(VIENNA.altitudeKm, 2);
|
||||
});
|
||||
it('carries its source and licence beside the data', () => {
|
||||
expect(bake.source.licence).toMatch(/attribution required/);
|
||||
expect(bake.source.attribution).toMatch(/COPERNICUS/);
|
||||
});
|
||||
it('is a closed ring of plausible angles: the Wienerwald NW, open Marchfeld E', () => {
|
||||
expect(bake.elevationDeg).toHaveLength(720);
|
||||
expect(horizonElevation(0)).toBeCloseTo(horizonElevation(360), 6);
|
||||
expect(horizonElevation(305)).toBeGreaterThan(horizonElevation(70));
|
||||
expect(Math.max(...bake.elevationDeg)).toBeLessThan(5);
|
||||
expect(horizonDistanceKm(305)).toBeGreaterThan(1);
|
||||
});
|
||||
it('interpolates between samples and returns unit normals', () => {
|
||||
expect(horizonElevation(100.25)).toBeCloseTo((bake.elevationDeg[200] + bake.elevationDeg[201]) / 2, 6);
|
||||
expect(Math.hypot(...horizonNormal(250))).toBeCloseTo(1, 6);
|
||||
});
|
||||
});
|
||||
33
src/app/features/scene/ridge/horizon.ts
Normal file
33
src/app/features/scene/ridge/horizon.ts
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
// The terrain horizon seen from the viewpoint, baked from open DEM by `scripts/bake-horizon.py` (source, licence and attribution are
|
||||
// in the file's `source` block and in `HORIZON_ATTRIBUTION`).
|
||||
import bake from './viennaHorizon.json';
|
||||
|
||||
export const HORIZON_ATTRIBUTION = bake.source.attribution;
|
||||
|
||||
const N = bake.elevationDeg.length;
|
||||
|
||||
/** Index pair and weight of an azimuth (degrees clockwise from north) on the baked ring. */
|
||||
function at(azimuth: number): [number, number, number] {
|
||||
const f = ((((azimuth / bake.stepDeg) % N) + N) % N);
|
||||
const i = Math.floor(f);
|
||||
return [i, (i + 1) % N, f - i];
|
||||
}
|
||||
|
||||
const lerp = (arr: readonly number[], az: number): number => {
|
||||
const [a, b, t] = at(az);
|
||||
return arr[a] * (1 - t) + arr[b] * t;
|
||||
};
|
||||
|
||||
/** Elevation of the horizon, degrees above the astronomical horizon, at an azimuth. */
|
||||
export const horizonElevation = (azimuth: number): number => lerp(bake.elevationDeg, azimuth);
|
||||
|
||||
/** Distance of the terrain that sets the horizon, km. */
|
||||
export const horizonDistanceKm = (azimuth: number): number => lerp(bake.distanceKm, azimuth);
|
||||
|
||||
/** Unit surface normal of the terrain at the horizon point: x east, y up, z north. */
|
||||
export function horizonNormal(azimuth: number): [number, number, number] {
|
||||
const e = lerp(bake.slopeEast, azimuth);
|
||||
const n = lerp(bake.slopeNorth, azimuth);
|
||||
const l = Math.hypot(e, 1, n);
|
||||
return [-e / l, 1 / l, -n / l];
|
||||
}
|
||||
|
|
@ -63,11 +63,11 @@ export interface Budget {
|
|||
export const MARGIN = 0.004;
|
||||
|
||||
/**
|
||||
* Day and Dusk wear dark ink (floor: its bound plus margin, `SKY_BAND` day 0.317, dusk 0.4744); Night wears light ink, and its
|
||||
* Day and Dusk wear the same dark ink, so one floor: its bound plus margin, 0.4744, which is what the dark link needs (about 0.4554 for 4.5:1, skyTheme.test.ts); a lower day floor (0.317 was tried) leaves the link at 3.3:1. Night wears light ink, and its
|
||||
* dimmer foldout headers (L 0.386 on screen, rat-crest-a7c95ce-20261111) need a backdrop of at most 0.047.
|
||||
*/
|
||||
export const BUDGET: Record<FixedSkyState, Budget> = {
|
||||
day: { floor: 0.317 + MARGIN, ceiling: 1, key: 0.45, min: 4, max: 60 },
|
||||
day: { floor: 0.4744 + MARGIN, ceiling: 1, key: 0.45, min: 4, max: 60 },
|
||||
dusk: { floor: 0.4744 + MARGIN, ceiling: 1, key: 0.5, min: 4, max: 400 },
|
||||
night: { floor: 0, ceiling: 0.047 - MARGIN, key: 0.03, min: 8, max: 3000 },
|
||||
};
|
||||
|
|
|
|||
|
|
@ -20,8 +20,8 @@ describe('the sun over Vienna', () => {
|
|||
expect(viennaSun(new Date(noon.getTime() + 3 * 3600_000)).azimuth).toBeGreaterThan(210);
|
||||
});
|
||||
|
||||
it('solar noon at 16.37 E falls near 10:40 UTC in mid November', () => {
|
||||
// 16.3738 E is 65.5 minutes ahead of Greenwich; the equation of time in mid November is +15 minutes (sun early): 12:00 - 65.5 - 15 = 10:40 UTC.
|
||||
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.
|
||||
const n = solarNoon(at('2026-11-11T12:00:00Z'));
|
||||
const minutes = n.getUTCHours() * 60 + n.getUTCMinutes();
|
||||
expect(minutes).toBeGreaterThan(10 * 60 + 30);
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
// The sun over Vienna (48.2082 N, 16.3738 E, 151 m) at a real moment: one ephemeris, `sunPosition` of src/sky/sun.js (the
|
||||
// The sun over the server's viewpoint in Vienna (48.1929826 N, 16.3534237 E, 183 m: Meta's location, the Copernicus DSM height there) 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
|
||||
// fixed sky state. The ridge sky is the physical atmosphere (`earthAtmosphere.ts`) lit from this sun.
|
||||
import { sunPosition } from '../../../../sky/sun.js';
|
||||
import { DAY_FROM } from '../skyState';
|
||||
import type { FixedSkyState } from '../skyBand';
|
||||
|
||||
export const VIENNA = { lat: 48.2082, lon: 16.3738, altitudeKm: 0.151 } as const;
|
||||
export const VIENNA = { lat: 48.1929826, lon: 16.3534237, altitudeKm: 0.183 } as const;
|
||||
|
||||
export interface SunSample {
|
||||
/** Degrees above the horizon, no refraction. */
|
||||
|
|
|
|||
1
src/app/features/scene/ridge/viennaHorizon.json
Normal file
1
src/app/features/scene/ridge/viennaHorizon.json
Normal file
File diff suppressed because one or more lines are too long
29
src/app/features/scene/ridge/weatherFeed.test.ts
Normal file
29
src/app/features/scene/ridge/weatherFeed.test.ts
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { fetchObservation, parseTawes, weatherFromObservation } from './weatherFeed';
|
||||
|
||||
const tawes = (RR: number | null, RF: number | null, SO: number | null) => ({
|
||||
features: [{ properties: { parameters: { RR: { data: [RR] }, RF: { data: [RF] }, SO: { data: [SO] } } } }],
|
||||
});
|
||||
|
||||
describe('weather from the TAWES observation', () => {
|
||||
it('rain is 0.8..1, by rate', () => {
|
||||
expect(weatherFromObservation({ rainMm: 0.1, humidity: 100, sunshineS: 0 }, false)).toBeCloseTo(0.813, 2);
|
||||
expect(weatherFromObservation({ rainMm: 3, humidity: 100, sunshineS: 0 }, true)).toBe(1);
|
||||
});
|
||||
it('a sunny dry day is clear and a sunless day overcast', () => {
|
||||
expect(weatherFromObservation({ rainMm: 0, humidity: 40, sunshineS: 600 }, true)).toBe(0);
|
||||
expect(weatherFromObservation({ rainMm: 0, humidity: 70, sunshineS: 0 }, true)).toBeCloseTo(0.55, 2);
|
||||
});
|
||||
it('a dry night is clear unless the air is saturated', () => {
|
||||
expect(weatherFromObservation({ rainMm: 0, humidity: 60, sunshineS: 0 }, false)).toBe(0);
|
||||
expect(weatherFromObservation({ rainMm: 0, humidity: 100, sunshineS: 0 }, false)).toBeCloseTo(0.75, 2);
|
||||
});
|
||||
it('parses the live response shape and rejects one without rain or humidity', () => {
|
||||
expect(parseTawes(tawes(0.1, 100, 0))).toEqual({ rainMm: 0.1, humidity: 100, sunshineS: 0 });
|
||||
expect(parseTawes(tawes(null, 100, 0))).toBeNull();
|
||||
expect(parseTawes({})).toBeNull();
|
||||
});
|
||||
it('a failed request is no observation', async () => {
|
||||
expect(await fetchObservation((async () => ({ ok: false })) as unknown as typeof fetch)).toBeNull();
|
||||
});
|
||||
});
|
||||
53
src/app/features/scene/ridge/weatherFeed.ts
Normal file
53
src/app/features/scene/ridge/weatherFeed.ts
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
// The weather over the viewpoint as one `weather.ts` number, from GeoSphere Austria's TAWES 10-minute observations
|
||||
// (station 11035, Wien Innere Stadt; open data, CC BY 4.0, no key, CORS open; 5 requests/s and 240/hour per client). TAWES measures
|
||||
// rain, humidity and sunshine duration, not cloud cover, so the number is what those three imply. Open-Meteo has cloud cover but its
|
||||
// free API is for non-commercial use only, so it is not used.
|
||||
export const TAWES_STATION = '11035';
|
||||
export const TAWES_URL =
|
||||
`https://dataset.api.hub.geosphere.at/v1/station/current/tawes-v1-10min?parameters=RR¶meters=RF¶meters=SO&station_ids=${TAWES_STATION}`;
|
||||
export const WEATHER_ATTRIBUTION = 'Weather: GeoSphere Austria (CC BY 4.0), station Wien Innere Stadt';
|
||||
|
||||
export interface Observation {
|
||||
/** Rain in the last 10 minutes, mm. */
|
||||
rainMm: number;
|
||||
/** Relative humidity, %. */
|
||||
humidity: number;
|
||||
/** Sunshine in the last 10 minutes, seconds (0..600). */
|
||||
sunshineS: number;
|
||||
}
|
||||
|
||||
const clamp01 = (v: number): number => Math.min(1, Math.max(0, v));
|
||||
|
||||
/**
|
||||
* The weather number of an observation. Rain sets 0.8..1 by rate (0.1 mm in ten minutes is the gauge's step: drizzle). Without rain,
|
||||
* sunshine says how much of the sky is open when the sun is up (`sunUp`); at night, or with the sun up and no sunshine, humidity
|
||||
* says it: saturated air with no sun is overcast and misty.
|
||||
*/
|
||||
export function weatherFromObservation(o: Observation, sunUp: boolean): number {
|
||||
if (o.rainMm > 0) return clamp01(0.8 + 0.2 * Math.min(1, o.rainMm / 1.5));
|
||||
const mist = clamp01((o.humidity - 85) / 15) * 0.75;
|
||||
if (!sunUp) return mist;
|
||||
const sun = clamp01(o.sunshineS / 600);
|
||||
return Math.max(mist * (1 - sun), 0.55 * (1 - sun));
|
||||
}
|
||||
|
||||
interface TawesFeature {
|
||||
properties?: { parameters?: Record<string, { data?: (number | null)[] } | undefined> };
|
||||
}
|
||||
|
||||
/** Parse a TAWES `station/current` response; null when a parameter is missing or has no value. */
|
||||
export function parseTawes(json: unknown): Observation | null {
|
||||
const f = (json as { features?: TawesFeature[] } | null)?.features?.[0];
|
||||
const p = f?.properties?.parameters;
|
||||
const val = (k: string): number | null => p?.[k]?.data?.[0] ?? null;
|
||||
const rainMm = val('RR');
|
||||
const humidity = val('RF');
|
||||
const sunshineS = val('SO');
|
||||
if (rainMm === null || humidity === null) return null;
|
||||
return { rainMm, humidity, sunshineS: sunshineS ?? 0 };
|
||||
}
|
||||
|
||||
export async function fetchObservation(fetcher: typeof fetch = fetch, signal?: AbortSignal): Promise<Observation | null> {
|
||||
const res = await fetcher(TAWES_URL, { signal });
|
||||
return res.ok ? parseTawes(await res.json()) : null;
|
||||
}
|
||||
|
|
@ -107,10 +107,10 @@ describe('sky state', () => {
|
|||
});
|
||||
|
||||
describe('skyBackdrop', () => {
|
||||
it('puts night below day and dusk, and dusk reaches the sun glow', () => {
|
||||
it('puts night below day and dusk', () => {
|
||||
expect(skyBackdrop('night').lightest).toBeLessThan(skyBackdrop('day').darkest);
|
||||
expect(skyBackdrop('night').lightest).toBeLessThan(skyBackdrop('dusk').lightest);
|
||||
expect(skyBackdrop('dusk').lightest).toBeGreaterThan(skyBackdrop('day').lightest);
|
||||
expect(skyBackdrop('dusk').lightest).toBeGreaterThanOrEqual(skyBackdrop('day').lightest);
|
||||
});
|
||||
|
||||
it('holds the baked gradients for day and night', () => {
|
||||
|
|
|
|||
|
|
@ -134,7 +134,7 @@ export interface SkyBackdrop {
|
|||
// Night's lightest also covers a sky the page URL steers (shaped to the band ceiling, skyBand.ts).
|
||||
// Bounds what the 8-bit screen shows too (one step each way for rounding and dither), rounded outward to six places.
|
||||
const BACKDROPS: Record<FixedSkyState, SkyBackdrop> = {
|
||||
day: { darkest: 0.321, lightest: 1 },
|
||||
day: { darkest: 0.461063, lightest: 1 },
|
||||
dusk: { darkest: 0.460352, lightest: 1 },
|
||||
night: { darkest: 0, lightest: 0.081642 },
|
||||
};
|
||||
|
|
|
|||
Loading…
Reference in a new issue