diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..77100e3b --- /dev/null +++ b/.gitattributes @@ -0,0 +1,5 @@ +# The ridge bake is addressed by its bytes (bake_id covers the manifest text and the tile files): public/ridge is checked out exactly as committed, whatever +# core.autocrlf says, so a Windows working tree serves the bytes its directory name was hashed from. +public/ridge/** -text +# The baker's inputs and schema are text, read the same everywhere. +scripts/ridge-bake/**/*.json text eol=lf diff --git a/.github/workflows/build-pull-request.yml b/.github/workflows/build-pull-request.yml index 964add54..e74946bc 100644 --- a/.github/workflows/build-pull-request.yml +++ b/.github/workflows/build-pull-request.yml @@ -18,10 +18,14 @@ jobs: - name: Setup node uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: - node-version-file: ".node-version" + node-version-file: '.node-version' package-manager-cache: false - name: Install dependencies run: npm ci + - name: Ridge asset gate + run: | + npx vitest run src/app/features/scene/ridge/ridgeAssets.test.ts + echo "ridge assets: $(find public/ridge -type f | wc -l) files, $(du -sb public/ridge | cut -f1) bytes" - name: Build app env: NODE_OPTIONS: '--max_old_space_size=4096' diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md new file mode 100644 index 00000000..1d22b489 --- /dev/null +++ b/THIRD_PARTY_NOTICES.md @@ -0,0 +1,21 @@ +# Third-party notices + +## d3-celestial (constellation lines) + +The constellation line chains in `src/app/features/scene/ridge/nightSkyData.ts` are derived from +`data/constellations.lines.json` of d3-celestial, https://github.com/ofrohn/d3-celestial, +under the licence below. + +``` +Copyright (c) 2015, Olaf Frohn +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.``` diff --git a/config.json b/config.json index fea9a59e..3e349d86 100644 --- a/config.json +++ b/config.json @@ -26,7 +26,7 @@ "enabled": false }, "fileZoneShare": { - "enabled": false + "enabled": true }, "push": { "vapidPublicKey": "", diff --git a/deployment/idunn/recipe.toml b/deployment/idunn/recipe.toml new file mode 100644 index 00000000..c4c1049d --- /dev/null +++ b/deployment/idunn/recipe.toml @@ -0,0 +1,34 @@ +schema = "gamecult.idunn.target_declaration.v1" +target = "ratatoskr" +# Idunn stamps the source commit into the build environment under this name. The release is not built from source: the +# dist tarball below is built by scripts the release owner runs (build-prod-dist.sh) and enters pinned by sha256, so +# each release is a recipe commit whose pin is its provenance. The stamp the served index carries is the commit the +# tarball was built from, which is not this commit. +source_stamp_environment = "RATATOSKR_BUILD_COMMIT" + +# Release dist f1172b5becb392cc690ddf671d70367e391fd392: the output of build-prod-dist.sh (live config check passed), packed +# as dist/ at the top of one gzip tar. The tree carries the repo's own config.json; what is served is the operator's +# carried file, which Idunn copies beside dist/ and the vhost aliases over the tree's (a vhost without that alias would +# serve the repo config). +[[external_inputs]] +id = "dist-tarball" +url = "https://eureka.gamecult.org/forge/GameCult/Ratatoskr/releases/download/dist-f1172b5b/ratatoskr-f1172b5b-dist.tar.gz" +sha256 = "014a6ff68686b5af0b323b115c2f33dc655749f59495b6f62671a0e4c881141b" +runner = "unpack" +destination = "release/dist.tar.gz" + +[[steps]] +id = "unpack-dist" +phase = "prepare" +runner = "unpack" +argv = ["tar", "-xzf", "release/dist.tar.gz", "-C", "release"] + +[[artifacts]] +id = "dist" +source_kind = "runner-output" +runner = "unpack" +source = "release/dist" +destination = "dist" + +[static_release] +artifact = "dist" diff --git a/docs/commons-files-desk.md b/docs/commons-files-desk.md index fa7242d2..d9152065 100644 --- a/docs/commons-files-desk.md +++ b/docs/commons-files-desk.md @@ -118,9 +118,9 @@ Under A the paused service is not built, and most of its list disappears: ## Cuts under A -Status 2026-11-14 (dev da822e9e plus the size-refusal cut): built: folders by album title path with navigation and breadcrumb (#147), pagination (#148), version folding (#149), add-to-album with named refusals (#150), Stop for a send in flight, replaces loops shown, freshest last event on add (#151), and the pre-send size refusal: a file larger than the server's `m.upload.size` is named and left unsent before any upload or album root, and a server stating no cap refuses nothing. **Not built: the Commons entry row** (item 1 below, found by `#commons:gamecult.org` or the carried `media.commons` id through `lookupMediaRoom`, behind a dark `filesDesk.enabled` flag; neither the row nor the flag exists in the code). It waits on Eureka's Commons room. +Status 2026-11-14 (dev da822e9e plus the size-refusal cut): built: folders by album title path with navigation and breadcrumb (#147), pagination (#148), version folding (#149), add-to-album with named refusals (#150), Stop for a send in flight, replaces loops shown, freshest last event on add (#151), and the pre-send size refusal: a file larger than the server's `m.upload.size` is named and left unsent before any upload or album root, and a server stating no cap refuses nothing. The Commons entry row is built (item 1): `useCommons` in `MediaRow.tsx` finds the room by the alias `#commons:` (provisioning records no id for it), through `lookupZoneRoom` (the one lookup `lookupMediaRoom` also uses); `EstateNavigator` shows it above the tiers as a Commons link when joined, a join row when invited or not joined, and nothing when the room is absent, the lookup failed or is out. It is gated on the existing `fileZoneShare.enabled`, not a new `filesDesk.enabled` flag. The album view and ShareSet work there because provisioning creates the Commons with the `org.gamecult.file_zone` create type. Members can share only once the room's power levels let them post: provisioning gives the poster level to the Minds alone. -1. **Commons entry**: a Commons row in the navigator (like `MediaRow`, found by alias or carried id), opening the room's album view. Flagged, no new data layer. +1. **Commons entry**: a Commons row in the navigator (like `MediaRow`, found by alias), opening the room's album view. Flagged, no new data layer. 2. **Pagination** of albums and files in `useAlbums` (done, PR #148). 3. **Folders by title path** and the album list grouped by it. 4. **Versions**: read `org.gamecult.publish.replaces`, show the latest of a chain with the earlier versions folded under it (done, PR #149). diff --git a/docs/gamecult/client-build-install.md b/docs/gamecult/client-build-install.md index b2505fe1..95c54f0f 100644 --- a/docs/gamecult/client-build-install.md +++ b/docs/gamecult/client-build-install.md @@ -113,9 +113,8 @@ Hard-refresh to clear `sw.js`. Do not delete the failed release; leave it for di ## Open -- The served config (checked 2026-11-12) is not the repo's: it says `backgroundScene.style` - `terrain` where the repo says `ridge` (#106, Meta 2026-11-11), lacks the repo's `dings`, - `fileZoneShare` and `registration` blocks (all off in the repo), and has no trailing newline. - The new keys default off or inert when absent, so only the style is a decision. Meta says which - style ships. Until the served file is replaced, every handoff build stops at the live check - unless `ALLOW_CONFIG_DRIFT=1` is set (section 1). +- Release a5 (2026-11-20, dist `a1fdfee3`, receipt `/opt/commons/handoff/rat146-a5-receipt-20261120.md`) + replaced the carried config with the repo's `config.json` (ridge, `fileZoneShare` on; ruling + `ratatoskr:ruling:ridge-only-scene-terrain-cut`). The carried file and the build pin are equal, so a + handoff build passes its live check without `ALLOW_CONFIG_DRIFT=1`. A release that changes + `config.json` changes the carried file deliberately, as a5's `carry.sh` did. diff --git a/docs/gamecult/ridge-backdrop-target.md b/docs/gamecult/ridge-backdrop-target.md new file mode 100644 index 00000000..238dd71c --- /dev/null +++ b/docs/gamecult/ridge-backdrop-target.md @@ -0,0 +1,19 @@ +# Ridge backdrop target + +The scene's bottom silhouette is replaced by baked A+D ridge planes. The baker is Python and offline; the browser composes pre-lit planes over the live physical sky. Typed state for this campaign (ideas, questions, rulings, cuts) lives in the instance mind `nibu`, campaign `ratatoskr-backdrop`; this file keeps only the ends. + +## Why +The live noise ridge is nearly invisible on a phone (about 1.35:1 against the darkest sky) because every ridge pixel is lifted to the text-contrast floor, and the star dots show between nav and header glyphs because the shell is transparent. Meta, 2026-11-13: do not polish the old backdrop; ship the A+D ridge pipeline (round 2 mockup: https://minds.gamecult.org/nibu/ridge-mockups-ad/). + +## Ends +- One owner per decision: the baker owns ridge geometry and shading; the runtime owns only the ring's residency, the camera's pose against its heading, blending and compositing. No ridge geometry is computed in the browser. +- The ground under the authored 500 m near clip is the place's own DEM from 1 m, drawn by card 0 inside the silhouette of the terrain at the clip and riding card 0's slide; everything that bounds the view reads terrain at or beyond the clip: `r_max` is where the linear slide holds for the nearest solid terrain each card draws in each tile (a tile of near ground only binds at the clip, 500 m, where it is slid), and every bake keeps 150 rows under the horizon so the plane reaches the bottom of every viewport. +- Nothing from the scene paints above app content: the scene is one stacking context at the back of the app, and nothing it creates has its own z-index or lives outside it. +- Phone cost is bounded: no per-frame script for the ridge (one exception: while a finger or the mouse is down in the scene view, pointer events turn the heading and the heading owner re-issues the rig; the twinkle is the other), decoded size and fetched size gated in CI. +- The ring is the bake and the heading is unbounded: the whole 360 degrees ships as azimuth tiles, the client holds only the arc it is about to need and fetches more as the view turns, and nothing caps the heading: it is unwrapped within a stretch of motion and `ridge/heading.ts` `normalize` brings it into [0, 360) before each one, so no angle or pixel position grows with uptime, while `ridge/ring.ts` is the one place that reasons about the wrap at 0 / 360. +- Motion is derived, not authored: a card's scale and shift come each second from the heading, the camera's angle on its circle and the viewer's offset (one pose, one owner: `ridge/heading.ts`, whose every change starts a segment from the pose the view has, and whose eases keep each pose inside the baked bound) and the card's distance (`ridge/view.ts` `cardPose`), and ride the compositor as one animation per card. +- The baker has fixtures with known right answers (the far-plateau spike, chain-end taper, slot union, seam) and a mutation runner that must kill each re-introduced cause. +- A baked asset names its baker version, DEM source and licence in a validated manifest; the terrain credit shown in the scene view's Place submenu comes from the manifest. + +## Not in scope +Button size (Void's). Patching the old noise-ridge path. Cone sampling. Live DEM access from the browser. diff --git a/harness/scene/README.md b/harness/scene/README.md index 624d4b0b..217e2241 100644 --- a/harness/scene/README.md +++ b/harness/scene/README.md @@ -20,3 +20,44 @@ directory whose ancestors hold no empty `package.json` (esbuild reads them). Timings from SwiftShader are CPU time: use them for the split between passes and for before and after of one change, never as a phone frame time. + +## Ridge live scene + +`ridgeLive.html` is one live scene (tier 'full', the sky plate and the cards on the compositor) filling the window, for a driver to turn and screenshot: `?h=214&sun=232:22&speed=6` (start heading, the sun's azimuth and elevation, degrees a second of rotation), +`?sky=night&lines=1`. `window.live` offers `hold(h)`, `pose()`, `plate()`, `left()` (the plate's left edge on the page) and `plateCost()` (ms of main thread to paint one plate here); `window.longTasks` lists the tasks over 50 ms. +A held heading's sun lands within a tenth of a pixel of the column the heading owner says, across re-centres of the plate. + +## Ridge look sheet + +Renders a baked place (`?place=`, the index default otherwise) lit for six sky states (dawn 2, morning 15, noon 55, golden 6, dusk -3, night -30 degrees of sun) +by a set of looks (`RidgeLook`, `src/app/features/scene/ridge/lightCards.ts`, the one owner of look values), one 480x270 canvas per cell, drawn by the app's own still +path (`createRidgeScene` at tier 'still' over a `createBackdrop` of the tiles round the heading), at the rest azimuth unless `?views=` says otherwise. The sky +behind a cell is the app's own, without clouds. Not shipped. + + ...ridgeSheet.html?views=214:0:200,0:0:200,214:90:98.2&sky=2 # one column per view heading:phi:offset (degrees, degrees, metres) at one sky (an index of SKIES) + +`&sun=100:6` puts the sun of that sky at compass azimuth 100, 6 degrees up (the stars are those of the moment the sheet is opened): a sun at the heading's side shows where the turned sky puts it, `&sky=5&lines=1` is the night. + +A heading of 0 or 360 is across north; a phi other than 0 is the offset-only rotation mode (the camera circling the centre, the view direction staying); the offset is +clamped to the place's range as the app does (phi 0: `camera.r_max_forward_m`, another phi: `camera.r_max_m`). + + npx vite --port 5199 # from the repo root; the app's vite config serves the page and public/ + http://localhost:5199/harness/scene/ridgeSheet.html # four presets x six skies + ...ridgeSheet.html?preset=swiss # one preset (physical|swiss|poster|painterly) + ...ridgeSheet.html?looks=%5B%7B%22label%22%3A%22no-ink%22%2C%22inkScale%22%3A0%7D%2C%7B%22label%22%3A%22hazy%22%2C%22hazeScale%22%3A8%7D%5D + ...?w=640 # cell width + +`looks=` is a url-encoded or base64 JSON array of `{label, ...partial RidgeLook}` and replaces the preset rows (`inkKeep` and `reliefLight` merge by key). +A cell costs one WebGL2 context and a card decode, so the full sheet takes tens of seconds (much longer in a background tab). + +Presets (`PRESETS` in `ridgeSheet.ts`; swiss and poster take every key not named from `PHYSICAL_LOOK`, the rest from `DEFAULT_LOOK`, the painterly cel look), chosen by reasoning, not by eye, for Self to tune: + +| preset | values | +| --- | --- | +| physical | PHYSICAL_LOOK (Lambert, no noise, sky haze, full ink) | +| swiss | reliefLight {mix 0.7, azimuthDeg -45, elevationDeg 40}, contrastByDistance 0.9, hazeScale 6, hazeTint [0, 0.05, 0.25], nearWarm 0.5, inkScale 0.6 | +| poster | reliefWeight 0.15, cardToneStep 0.25, cardGradient 0.5, inkKeep {edge 0.25, occlude 0.9, crease 1}, hazeScale 4 | +| 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 | + +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). diff --git a/harness/scene/ridgeDemo.ts b/harness/scene/ridgeDemo.ts index 3606d14f..17e67774 100644 --- a/harness/scene/ridgeDemo.ts +++ b/harness/scene/ridgeDemo.ts @@ -1,6 +1,5 @@ // Standalone page for the ridge scene: full window, no host app. `?tier=still|low|full` picks the -// tier, `?probe=1` shows the rAF median/p95 readout. The bake record (each chunk's cost, from -// the scene's `onBake`) and the long tasks the page saw are on `window.bakes` and `window.longTasks` +// tier, `?probe=1` shows the rAF median/p95 readout. The long tasks the page saw are on `window.longTasks` // for a driver to read. Not shipped. import { startBackgroundScene } from '../../src/app/features/scene'; import type { SceneTier } from '../../src/app/features/scene'; @@ -8,8 +7,7 @@ import type { SceneTier } from '../../src/app/features/scene'; const q = new URLSearchParams(location.search); const tier = (q.get('tier') ?? 'full') as SceneTier; const canvas = document.getElementById('c') as HTMLCanvasElement; -const w = window as unknown as { scene: unknown; bakes: unknown[]; longTasks: number[]; firstViewMs: number }; -w.bakes = []; +const w = window as unknown as { scene: unknown; longTasks: number[]; firstViewMs: number }; w.longTasks = []; try { new PerformanceObserver((l) => l.getEntries().forEach((e) => w.longTasks.push(e.duration))).observe({ @@ -21,7 +19,6 @@ try { const t0 = performance.now(); startBackgroundScene({ tier }, {}, { canvas, - onBake: (b: unknown) => w.bakes.push(b), } as never).then((scene) => { w.firstViewMs = performance.now() - t0; w.scene = scene; diff --git a/harness/scene/ridgeLive.html b/harness/scene/ridgeLive.html new file mode 100644 index 00000000..fba96a06 --- /dev/null +++ b/harness/scene/ridgeLive.html @@ -0,0 +1,8 @@ + + + +Ridge live scene + +
+ + diff --git a/harness/scene/ridgeLive.ts b/harness/scene/ridgeLive.ts new file mode 100644 index 00000000..fcab4092 --- /dev/null +++ b/harness/scene/ridgeLive.ts @@ -0,0 +1,71 @@ +// One live ridge scene (tier 'full': the sky plate and the cards on the compositor) filling the window, for a driver to turn and screenshot. Not shipped. +// `?h=214` the heading the scene starts at; `?sun=232:22` the sun's compass azimuth and elevation (degrees); `?sky=night` the stars of now (sun below the horizon); `?lines=1` the constellation lines. +// `?speed=6` degrees a second the view turns (rotation mode 'both'); 0 holds it. The page offers `window.live`: `hold(h)` turns the view by hand, `pose()` is the heading owner's pose now, +// `plate()` the sky plate's element and `left()` its left edge and width on the page. +import { parseManifest } from '../../src/app/features/scene/ridge/manifest'; +import { makePhysicalSky } from '../../src/app/features/scene/ridge/physicalSky'; +import { createBackdrop } from '../../src/app/features/scene/ridge/Backdrop'; +import { createRidgeScene } from '../../src/app/features/scene/ridge/Ridge'; +import { anchor, hold, poseAt } from '../../src/app/features/scene/ridge/heading'; +import { setCamera } from '../../src/app/features/scene/cameraState'; +import { HFOV_MAX_DEG, windowFor } from '../../src/app/features/scene/ridge/view'; +import { paintSky } from '../../src/app/features/scene/ridge/physicalSky'; +import { nightBodies } from '../../src/app/features/scene/ridge/nightBodies'; +import { plateCamera, plateSize, SLACK_MIN_DEG } from '../../src/app/features/scene/ridge/skyTurn'; + +const q = new URLSearchParams(location.search); +/** The main-thread tasks over 50 ms the page saw, ms: `window.longTasks`. */ +const longTasks: number[] = []; +(window as unknown as { longTasks: number[] }).longTasks = longTasks; +try { + new PerformanceObserver((l) => l.getEntries().forEach((e) => longTasks.push(e.duration))).observe({ entryTypes: ['longtask'] }); +} catch { + // No long-task entries in this browser. +} + +async function main() { + const index = await (await fetch('/public/ridge/index.json')).json(); + const dir = `/public/ridge/${index.places[q.get('place') ?? index.default]}/`; + const manifest = parseManifest(await (await fetch(`${dir}manifest.json`)).json(), dir); + const { view } = manifest; + const [az, el] = (q.get('sun') ?? '232:22').split(':').map(Number); + const time = new Date(); + const sun = q.get('sky') === 'night' ? { azimuth: 0, elevation: -30, time } : { azimuth: az, elevation: el, time }; + const physical = makePhysicalSky(sun, 0, view); + const h0 = Number(q.get('h') ?? view.lookAzDeg); + anchor(view.place.id, h0, performance.now()); + setCamera({ mode: 'both', speedDegPerS: Number(q.get('speed') ?? 0), offsetM: 200 }); + const backdrop = createBackdrop(manifest, physical); + await backdrop.ensure({ fromDeg: h0 - HFOV_MAX_DEG, toDeg: h0 + HFOV_MAX_DEG }); + const canvas = document.getElementById('c') as HTMLCanvasElement; + const scene = createRidgeScene({ canvas, tier: 'full', sky: { ...physical.stops, physical }, backdrop, lines: q.get('lines') === '1' }); + const host = document.getElementById('host') as HTMLElement; + // The plate is the host's div whose first child is a canvas (the rig's first child is a div, the rain's has none). + const plate = () => [...host.children].find((c) => c.tagName === 'DIV' && c.firstElementChild?.tagName === 'CANVAS'); + (window as unknown as { live: unknown }).live = { + scene, + hold: (h: number) => hold(h, performance.now()), + pose: () => poseAt(performance.now()), + plate, + /** Mean ms of the main-thread part of painting one plate here (the dome, its pixels and the bodies, not the canvas upscale), over `n` runs. */ + plateCost: (n = 10) => { + const w = innerWidth; + const h = innerHeight; + const win = windowFor(view, w, h); + const { cssW } = plateSize(win, w, h, devicePixelRatio >= 2 ? 2 : 1, SLACK_MIN_DEG); + const t0 = performance.now(); + for (let i = 0; i < n; i += 1) nightBodies(physical, paintSky(physical, cssW, h, plateCamera(win, 214 + i, SLACK_MIN_DEG)), true); + return (performance.now() - t0) / n; + }, + left: () => { + const r = plate()?.getBoundingClientRect(); + return r && { left: r.left, width: r.width }; + }, + }; + document.title = 'ridge live: done'; +} + +main().catch((e) => { + console.error(e); + document.title = `ridge live: failed ${e}`; +}); diff --git a/harness/scene/ridgeSheet.html b/harness/scene/ridgeSheet.html new file mode 100644 index 00000000..9a45924b --- /dev/null +++ b/harness/scene/ridgeSheet.html @@ -0,0 +1,8 @@ + + + +Ridge look sheet + +
+ + diff --git a/harness/scene/ridgeSheet.ts b/harness/scene/ridgeSheet.ts new file mode 100644 index 00000000..440a3a57 --- /dev/null +++ b/harness/scene/ridgeSheet.ts @@ -0,0 +1,279 @@ +// Look sheet for the lit ridge cards: a baked place lit for a grid of sky states (or pinned moments) x looks, each cell a small canvas drawn by the app's own still path +// (`createRidgeScene` at tier 'still', the tiles of the arc round the heading, each card at `cardPose`). Not shipped. +// `?views=214:0:200,0:0:200,100:0:200,214:90:98.2` one column per view `heading:phi:offset` (degrees, degrees, metres) at one sky (`?sky=2`, an index of SKIES, noon by default); a heading +// of 360 or 0 is across north. `&sun=100:6` puts the sun of that sky at azimuth 100, 6 degrees up (the stars are always those of the moment the sheet is opened). The offset is clamped to the place's range as the app does (phi 0: the bake's forward bound, any other phi: the worst-case bound), and a phi other than 0 is the offset-only rotation mode, the camera circling the centre. +// `?place=vienna` the baked place (index.json's default if absent) +// `?preset=all|physical|swiss|poster|painterly|painterly-cel-2|painterly-cel-3|painterly-cel-4` (default all: one row each; painterly is DEFAULT_LOOK); `?looks=` replaces the rows with +// the given `{label, ...partial RidgeLook}` entries (inkKeep and reliefLight merge by key). `?w=480` sets the cell width, 16:9 unless `?h=` gives the height (`?w=375&h=812` is a phone). +// The sky behind a cell is the app's own: `makePhysicalSky` + `paintSky` upscaled smoothly, with the real stars and the moon (`nightBodies`), +// without the sun disc or clouds. Columns are the SKIES below (a sun elevation each, the stars and moon of the moment the sheet was opened), or: +// `?moments=2026-11-24T22:00Z,2026-12-09T20:00Z` explicit UTC moments: the sun, moon and stars are those of the moment, the state follows the sun's elevation +// `?night=1` the night set: the next new moon, first quarter and full moon from today (or from `?from=YYYY-MM-DD`), each at four night hours +// (`?hours=18,21,0,4` UTC), plus deep dusk (sun at -10 degrees) of the evening of the full moon +// `?labels=1` DEBUG: label each constellation chain in frame with its d3-celestial abbreviation (fetched from the source repository at run time; not shipped) +// `?lines=1` constellation lines over the stars, as the Sky menu's hidden toggle does (night cells only) +import { DEFAULT_LOOK, PHYSICAL_LOOK, createLighter } from '../../src/app/features/scene/ridge/lightCards'; +import type { RidgeLook } from '../../src/app/features/scene/ridge/lightCards'; +import { parseIndex, parseManifest } from '../../src/app/features/scene/ridge/manifest'; +import { makePhysicalSky } from '../../src/app/features/scene/ridge/physicalSky'; +import { HFOV_MAX_DEG, windowFor } from '../../src/app/features/scene/ridge/view'; +import { onScreen } from '../../src/app/features/scene/ridge/nightBodies'; +import { createBackdrop } from '../../src/app/features/scene/ridge/Backdrop'; +import { createRidgeScene } from '../../src/app/features/scene/ridge/Ridge'; +import { anchor, hold } from '../../src/app/features/scene/ridge/heading'; +import { setCamera } from '../../src/app/features/scene/cameraState'; +import { sunAt } from '../../src/app/features/scene/ridge/sunAt'; +import { linesAt } from '../../src/app/features/scene/ridge/starCatalogue'; +import { moonPhase } from '../../src/sky/moon.js'; +import { MOMENT_IDS, momentFor } from '../../src/app/features/scene/ridge/skyMoment'; + + +type Override = Partial> & { + label: string; + /** The look the unnamed keys come from (DEFAULT_LOOK, the painterly cel look, if absent). */ + base?: 'physical'; + inkKeep?: Partial; + reliefLight?: Partial; +}; + +interface Column { + label: string; + elevation?: number; + azimuth?: number; + /** A moment: the sun is the real one of it. */ + time?: Date; + /** Where the view faces and the camera stands: heading and phi in degrees, offset in metres. Absent: the rest azimuth, phi 0, the app's default offset. */ + view?: { h: number; phi: number; r: number }; +} + +/** 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[] = [ + { label: 'dawn 2 deg', elevation: 2, azimuth: 100 }, + { label: 'morning 15 deg', elevation: 15, azimuth: 135 }, + { label: 'noon 55 deg', elevation: 55, azimuth: 190 }, + { label: 'golden 6 deg', elevation: 6, azimuth: 244 }, + { label: 'dusk -3 deg', elevation: -3, azimuth: 262 }, + { label: 'night -30 deg', elevation: -30, azimuth: 0 }, +]; + +/** The art directions, chosen by reasoning, not by eye: Self tunes them (values listed in harness/scene/README.md). */ +const PRESETS: Record = { + physical: { label: 'physical', base: 'physical' }, + swiss: { + label: 'swiss', + base: 'physical', + reliefLight: { mix: 0.7, azimuthDeg: -45, elevationDeg: 40 }, + contrastByDistance: 0.9, + hazeScale: 6, + hazeTint: [0, 0.05, 0.25], + nearWarm: 0.5, + inkScale: 0.6, + }, + poster: { + label: 'poster', + base: 'physical', + reliefWeight: 0.15, + cardToneStep: 0.25, + cardGradient: 0.5, + inkKeep: { edge: 0.25, occlude: 0.9, crease: 1 }, + hazeScale: 4, + }, + painterly: { label: 'painterly (default, cel 3)' }, + 'painterly-cel-2': { label: 'painterly-cel-2', celBands: 2 }, + 'painterly-cel-3': { label: 'painterly-cel-3', celBands: 3 }, + 'painterly-cel-4': { label: 'painterly-cel-4', celBands: 4 }, +}; + +const merge = (o: Override): { label: string; look: RidgeLook } => { + const { label, base: baseName, inkKeep, reliefLight, ...rest } = o; + const base = baseName === 'physical' ? PHYSICAL_LOOK : DEFAULT_LOOK; + return { + label, + look: { + ...base, + ...rest, + inkKeep: { ...base.inkKeep, ...inkKeep }, + reliefLight: { ...base.reliefLight, ...reliefLight }, + }, + }; +}; + +function parseLooks(raw: string): Override[] { + const tries = [() => decodeURIComponent(raw), () => atob(raw.replace(/-/g, '+').replace(/_/g, '/'))]; + for (const t of tries) { + try { + const v = JSON.parse(t()); + if (Array.isArray(v)) return v.map((e, i) => ({ label: `look ${i + 1}`, ...e })); + } catch { + // try the next encoding + } + } + throw new Error('looks= is neither a url-encoded nor a base64 JSON array'); +} + +const q = new URLSearchParams(location.search); + +const HOUR = 3_600_000; +/** The first moment at or after `from` the moon's elongation passes `target` degrees (new 0, first quarter 90, full 180). */ +function nextPhase(from: Date, target: number): Date { + const err = (t: number) => ((moonPhase(t).elongationDeg - target + 540) % 360) - 180; + let t = from.getTime(); + while (!(err(t) < 0 && err(t + HOUR) >= 0)) t += HOUR; + let a = t; + let b = t + HOUR; + for (let i = 0; i < 20; i += 1) { + const m = (a + b) / 2; + if (err(m) < 0) a = m; + else b = m; + } + return new Date(b); +} + +/** The first evening moment (UTC hour steps of 10 minutes from `day`) the sun is at `deg` below the horizon, going down. */ +function sunDownTo(place: Parameters[0], day: Date, deg: number): Date { + let t = Date.UTC(day.getUTCFullYear(), day.getUTCMonth(), day.getUTCDate(), 12); + while (sunAt(place, new Date(t)).elevation > -deg) t += 10 * 60_000; + return new Date(t); +} + +const fmt = (d: Date) => d.toISOString().slice(0, 16).replace('T', ' ') + 'Z'; + +function momentsFrom(params: URLSearchParams, place: Parameters[0]): Column[] | undefined { + const list = params.get('moments'); + if (list) + return list.split(',').map((iso) => { + const time = new Date(iso.trim()); + if (Number.isNaN(time.getTime())) throw new Error(`moments=: ${iso} is not a date`); + 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; + 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 cols: Column[] = []; + const phases: [string, number][] = [['new', 0], ['first quarter', 90], ['full', 180]]; + phases.forEach(([name, deg]) => { + const peak = nextPhase(from, deg); + const day = Date.UTC(peak.getUTCFullYear(), peak.getUTCMonth(), peak.getUTCDate()); + hours.forEach((h) => { + // Hours before 12 belong to the night that ends the day of the phase, so the hours run on from the evening. + const time = new Date(day + (h < 12 ? 24 + h : h) * HOUR); + cols.push({ label: `${name} ${fmt(time)}`, time }); + }); + if (deg === 180) cols.push({ label: `deep dusk, full moon ${fmt(sunDownTo(place, peak, 10))}`, time: sunDownTo(place, peak, 10) }); + }); + return cols; +} +/** `?views=h:phi:r,...`: one column per view, all at the sky `?sky=` (default noon), whose sun `?sun=az:el` may put elsewhere (compass degrees, degrees above the horizon). */ +function viewsFrom(params: URLSearchParams): Column[] | undefined { + const list = params.get('views'); + if (!list) return undefined; + const [az, el] = (params.get('sun') ?? '').split(':').map(Number); + const sky = { ...SKIES[Number(params.get('sky') ?? 2)], ...(Number.isFinite(az) && Number.isFinite(el) ? { azimuth: az, elevation: el } : {}) }; + return list.split(',').map((v) => { + const [h, phi, r] = v.split(':').map(Number); + return { ...sky, label: `h ${h} phi ${phi} r ${r}`, view: { h, phi, r } }; + }); +} +const preset = q.get('preset'); +const pinned = q.get('moments') || q.get('night'); +const rows = (q.get('looks') + ? parseLooks(q.get('looks') as string) + : preset && preset !== 'all' + ? [PRESETS[preset] ?? PRESETS.physical] + : pinned + ? [PRESETS.painterly] // a night set is read in the default look unless a preset or looks say otherwise + : Object.values(PRESETS) +).map(merge); +const withLines = q.get('lines') === '1'; +const LINES_JSON = 'https://raw.githubusercontent.com/ofrohn/d3-celestial/master/data/constellations.lines.json'; +/** Debug: the constellation id of each packed chain, in the generator's order (feature by feature, chain by chain). */ +async function chainIds(): Promise { + const gj = await (await fetch(LINES_JSON)).json(); + return gj.features.flatMap((f: { id: string; geometry: { coordinates: unknown[] } }) => f.geometry.coordinates.map(() => f.id)); +} +const W = Number(q.get('w') ?? 480); +const H = q.get('h') ? Number(q.get('h')) : Math.round((W * 9) / 16); +const root = document.getElementById('sheet') as HTMLElement; + +async function main() { + const index = parseIndex(await (await fetch('/public/ridge/index.json')).json()); + const DIR = `/public/ridge/${index.places[q.get('place') ?? index.default] ?? index.places[index.default]}/`; + const manifest = parseManifest(await (await fetch(`${DIR}manifest.json`)).json(), DIR); + const { view } = manifest; + const win = windowFor(view, W, H); + const now = new Date(); + const columns = viewsFrom(q) ?? momentsFrom(q, view.place) ?? SKIES; + const ids = q.get('labels') === '1' ? await chainIds() : undefined; + + const table = document.createElement('table'); + table.style.borderSpacing = '4px'; + root.append(table); + const head = table.insertRow(); + head.insertCell(); + columns.forEach((c) => (head.insertCell().textContent = c.label)); + const tr = rows.map((r) => { + const row = table.insertRow(); + row.insertCell().textContent = r.label; + return row; + }); + + for (const col of columns) { + const time = col.time ?? now; + const sun = + col.time !== undefined + ? sunAt(view.place, col.time) + : { elevation: col.elevation as number, azimuth: col.azimuth as number, time }; + const physical = makePhysicalSky(sun, 0, view); + const sky = { ...physical.stops, physical }; + const v = col.view ?? { h: view.lookAzDeg, phi: 0, r: 200 }; + + for (let r = 0; r < rows.length; r += 1) { + // A host as the page has one: a positioned box of the cell's size holding the canvas the scene paints. + const host = document.createElement('div'); + Object.assign(host.style, { position: 'relative', width: `${W}px`, height: `${H}px`, overflow: 'hidden' }); + const cell = document.createElement('canvas'); + Object.assign(cell.style, { position: 'absolute', left: '0', top: '0', width: '100%', height: '100%' }); + host.append(cell); + tr[r].insertCell().append(host); + + // The heading owner as the app leaves it: this view's heading, the camera on its circle at phi (offset-only rotation), the offset the viewer chose. + const t0 = performance.now() - 3_600_000; + anchor(`sheet-${manifest.bakeId}-${columns.indexOf(col)}-${r}`, v.h, t0); // a key of its own: every cell starts from phi 0 + setCamera({ mode: 'offset', speedDegPerS: 1, offsetM: v.r }, t0); // the offset-only rotation mode for phi seconds at 1 degree per second ... + hold(v.h, t0 + v.phi * 1000); // ... then the view is held at h: the mode is still, the camera stays at phi (phi 0 is the camera on its heading) + + const backdrop = createBackdrop(manifest, physical, { lighter: (m, s) => createLighter(m, s, rows[r].look) }); + await backdrop.ensure({ fromDeg: v.h - HFOV_MAX_DEG, toDeg: v.h + HFOV_MAX_DEG }); + const scene = createRidgeScene({ canvas: cell, tier: 'still', sky, backdrop, lines: withLines }); + scene?.dispose(); + + if (ids) { + // Debug labels: each chain's id at the mean of its vertices that lie in the frame. + const ctx = cell.getContext('2d') as CanvasRenderingContext2D; + ctx.font = '11px monospace'; + ctx.fillStyle = '#ffd24a'; + linesAt(physical.sun.time, view.place.lat, view.place.lon).forEach((chain, i) => { + const pts = chain.map((p) => onScreen(win.camera, p.azimuth, p.elevation)).filter((a) => a.x >= 0 && a.x <= 1 && a.y >= 0 && a.y <= 1); + if (!pts.length) return; + const mx = pts.reduce((a, p) => a + p.x, 0) / pts.length; + const my = pts.reduce((a, p) => a + p.y, 0) / pts.length; + ctx.fillText(`${ids[i]} ${pts.length}/${chain.length}`, mx * W, my * H); + }); + } + } + } + document.title = 'ridge look sheet: done'; +} + +main().catch((e) => { + console.error(e); + root.textContent = `ridge look sheet failed: ${e}`; +}); diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t00-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t00-colour.webp new file mode 100644 index 00000000..c3893ca5 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t00-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t00-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t00-geometry.webp new file mode 100644 index 00000000..5891ae4b Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t00-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t01-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t01-colour.webp new file mode 100644 index 00000000..5fd85171 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t01-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t01-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t01-geometry.webp new file mode 100644 index 00000000..194baac8 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t01-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t02-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t02-colour.webp new file mode 100644 index 00000000..e23b1c6f Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t02-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t02-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t02-geometry.webp new file mode 100644 index 00000000..266918c4 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t02-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t03-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t03-colour.webp new file mode 100644 index 00000000..ae17bebc Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t03-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t03-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t03-geometry.webp new file mode 100644 index 00000000..7e425e50 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t03-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t04-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t04-colour.webp new file mode 100644 index 00000000..6234b1cf Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t04-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t04-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t04-geometry.webp new file mode 100644 index 00000000..c75eaa59 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t04-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t05-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t05-colour.webp new file mode 100644 index 00000000..eec0a22d Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t05-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t05-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t05-geometry.webp new file mode 100644 index 00000000..d1267cca Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t05-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t06-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t06-colour.webp new file mode 100644 index 00000000..2d073a4e Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t06-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t06-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t06-geometry.webp new file mode 100644 index 00000000..527adc45 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t06-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t07-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t07-colour.webp new file mode 100644 index 00000000..7a77c63b Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t07-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t07-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t07-geometry.webp new file mode 100644 index 00000000..f1b332f1 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t07-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t08-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t08-colour.webp new file mode 100644 index 00000000..e8ddebc5 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t08-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t08-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t08-geometry.webp new file mode 100644 index 00000000..5a76a3cb Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t08-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t09-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t09-colour.webp new file mode 100644 index 00000000..dd585bf5 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t09-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t09-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t09-geometry.webp new file mode 100644 index 00000000..6b101d8c Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t09-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t10-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t10-colour.webp new file mode 100644 index 00000000..174ad822 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t10-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t10-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t10-geometry.webp new file mode 100644 index 00000000..fe9bee3b Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t10-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t11-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t11-colour.webp new file mode 100644 index 00000000..554261c4 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t11-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t11-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t11-geometry.webp new file mode 100644 index 00000000..d3acc133 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t11-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t12-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t12-colour.webp new file mode 100644 index 00000000..3119c226 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t12-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t12-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t12-geometry.webp new file mode 100644 index 00000000..ee2d2581 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t12-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t13-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t13-colour.webp new file mode 100644 index 00000000..73e6d523 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t13-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t13-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t13-geometry.webp new file mode 100644 index 00000000..e3ed014b Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t13-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t14-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t14-colour.webp new file mode 100644 index 00000000..ee04ab30 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t14-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t14-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t14-geometry.webp new file mode 100644 index 00000000..b80bef92 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t14-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t15-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t15-colour.webp new file mode 100644 index 00000000..b790a947 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t15-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t15-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t15-geometry.webp new file mode 100644 index 00000000..71562790 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t15-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t16-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t16-colour.webp new file mode 100644 index 00000000..56f4fbf9 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t16-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t16-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t16-geometry.webp new file mode 100644 index 00000000..134352e2 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t16-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t17-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t17-colour.webp new file mode 100644 index 00000000..fb827d7d Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t17-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t17-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t17-geometry.webp new file mode 100644 index 00000000..cda9a5b8 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t17-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t18-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t18-colour.webp new file mode 100644 index 00000000..192dc734 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t18-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t18-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t18-geometry.webp new file mode 100644 index 00000000..db3299d4 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t18-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t19-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t19-colour.webp new file mode 100644 index 00000000..72979ee6 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t19-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t19-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t19-geometry.webp new file mode 100644 index 00000000..60cce1e4 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t19-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t20-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t20-colour.webp new file mode 100644 index 00000000..2fa78159 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t20-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t20-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t20-geometry.webp new file mode 100644 index 00000000..b6e021e4 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t20-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t21-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t21-colour.webp new file mode 100644 index 00000000..c4ae8082 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t21-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t21-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t21-geometry.webp new file mode 100644 index 00000000..2e8d73c1 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t21-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t22-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t22-colour.webp new file mode 100644 index 00000000..9c534ff2 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t22-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t22-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t22-geometry.webp new file mode 100644 index 00000000..0bc194cb Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t22-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t23-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t23-colour.webp new file mode 100644 index 00000000..984c3986 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t23-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t23-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t23-geometry.webp new file mode 100644 index 00000000..bd3ae087 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t23-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t24-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t24-colour.webp new file mode 100644 index 00000000..99940492 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t24-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t24-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t24-geometry.webp new file mode 100644 index 00000000..7ecf00b9 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t24-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t25-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t25-colour.webp new file mode 100644 index 00000000..73bd10bd Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t25-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t25-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t25-geometry.webp new file mode 100644 index 00000000..30d7765a Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t25-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t26-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t26-colour.webp new file mode 100644 index 00000000..a727fd4e Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t26-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t26-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t26-geometry.webp new file mode 100644 index 00000000..8492946e Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t26-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t27-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t27-colour.webp new file mode 100644 index 00000000..f711d597 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t27-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t27-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t27-geometry.webp new file mode 100644 index 00000000..e82b6777 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t27-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t28-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t28-colour.webp new file mode 100644 index 00000000..a2fdf8f3 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t28-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t28-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t28-geometry.webp new file mode 100644 index 00000000..00af24b3 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t28-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t29-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t29-colour.webp new file mode 100644 index 00000000..5d03874e Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t29-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t29-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t29-geometry.webp new file mode 100644 index 00000000..e9cb8e9c Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t29-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t30-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t30-colour.webp new file mode 100644 index 00000000..8ed8439b Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t30-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t30-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t30-geometry.webp new file mode 100644 index 00000000..9230d8a9 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t30-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t31-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t31-colour.webp new file mode 100644 index 00000000..9718a7cb Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t31-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-0-t31-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-0-t31-geometry.webp new file mode 100644 index 00000000..b6ecf444 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-0-t31-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t00-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t00-colour.webp new file mode 100644 index 00000000..865800a1 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t00-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t00-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t00-geometry.webp new file mode 100644 index 00000000..bdfa32a2 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t00-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t01-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t01-colour.webp new file mode 100644 index 00000000..7832010e Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t01-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t01-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t01-geometry.webp new file mode 100644 index 00000000..db8c3fdb Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t01-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t02-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t02-colour.webp new file mode 100644 index 00000000..990440d4 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t02-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t02-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t02-geometry.webp new file mode 100644 index 00000000..f1c399c6 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t02-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t03-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t03-colour.webp new file mode 100644 index 00000000..691e899b Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t03-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t03-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t03-geometry.webp new file mode 100644 index 00000000..9686a023 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t03-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t04-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t04-colour.webp new file mode 100644 index 00000000..f2fd046f Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t04-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t04-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t04-geometry.webp new file mode 100644 index 00000000..20c731a9 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t04-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t05-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t05-colour.webp new file mode 100644 index 00000000..79109c67 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t05-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t05-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t05-geometry.webp new file mode 100644 index 00000000..d4d430fe Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t05-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t06-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t06-colour.webp new file mode 100644 index 00000000..c291b832 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t06-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t06-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t06-geometry.webp new file mode 100644 index 00000000..24053679 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t06-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t07-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t07-colour.webp new file mode 100644 index 00000000..e1af53b0 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t07-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t07-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t07-geometry.webp new file mode 100644 index 00000000..5ba0bffd Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t07-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t08-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t08-colour.webp new file mode 100644 index 00000000..0a5dc617 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t08-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t08-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t08-geometry.webp new file mode 100644 index 00000000..4251abdc Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t08-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t09-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t09-colour.webp new file mode 100644 index 00000000..cd35d1c2 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t09-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t09-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t09-geometry.webp new file mode 100644 index 00000000..40de3a02 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t09-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t10-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t10-colour.webp new file mode 100644 index 00000000..0f8f7483 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t10-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t10-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t10-geometry.webp new file mode 100644 index 00000000..28f5c6d6 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t10-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t11-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t11-colour.webp new file mode 100644 index 00000000..415c3bcb Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t11-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t11-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t11-geometry.webp new file mode 100644 index 00000000..0e49c504 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t11-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t12-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t12-colour.webp new file mode 100644 index 00000000..bd141f76 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t12-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t12-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t12-geometry.webp new file mode 100644 index 00000000..f33dfb18 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t12-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t13-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t13-colour.webp new file mode 100644 index 00000000..5f72df6a Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t13-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t13-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t13-geometry.webp new file mode 100644 index 00000000..bebdcae6 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t13-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t14-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t14-colour.webp new file mode 100644 index 00000000..d6411b5f Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t14-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t14-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t14-geometry.webp new file mode 100644 index 00000000..b9ce811a Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t14-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t15-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t15-colour.webp new file mode 100644 index 00000000..9e851859 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t15-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t15-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t15-geometry.webp new file mode 100644 index 00000000..046d6462 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t15-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t16-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t16-colour.webp new file mode 100644 index 00000000..7c992076 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t16-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t16-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t16-geometry.webp new file mode 100644 index 00000000..91ccbf70 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t16-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t17-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t17-colour.webp new file mode 100644 index 00000000..54bb3e72 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t17-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t17-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t17-geometry.webp new file mode 100644 index 00000000..a6267d64 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t17-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t18-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t18-colour.webp new file mode 100644 index 00000000..c391c1d6 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t18-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t18-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t18-geometry.webp new file mode 100644 index 00000000..58901a4a Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t18-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t19-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t19-colour.webp new file mode 100644 index 00000000..231da848 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t19-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t19-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t19-geometry.webp new file mode 100644 index 00000000..6da6973a Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t19-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t20-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t20-colour.webp new file mode 100644 index 00000000..8dba2bfa Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t20-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t20-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t20-geometry.webp new file mode 100644 index 00000000..03d8361c Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t20-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t21-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t21-colour.webp new file mode 100644 index 00000000..3f3a1b38 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t21-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t21-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t21-geometry.webp new file mode 100644 index 00000000..01e0eb34 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t21-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t22-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t22-colour.webp new file mode 100644 index 00000000..f9fa0382 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t22-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t22-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t22-geometry.webp new file mode 100644 index 00000000..fa374bab Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t22-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t23-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t23-colour.webp new file mode 100644 index 00000000..cb623ab0 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t23-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t23-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t23-geometry.webp new file mode 100644 index 00000000..7e2b271c Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t23-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t24-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t24-colour.webp new file mode 100644 index 00000000..9f76e74f Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t24-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t24-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t24-geometry.webp new file mode 100644 index 00000000..50caa14d Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t24-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t25-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t25-colour.webp new file mode 100644 index 00000000..cfbce358 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t25-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t25-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t25-geometry.webp new file mode 100644 index 00000000..69c31d6a Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t25-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t26-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t26-colour.webp new file mode 100644 index 00000000..e76fe62d Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t26-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t26-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t26-geometry.webp new file mode 100644 index 00000000..e6a81341 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t26-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t27-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t27-colour.webp new file mode 100644 index 00000000..0cf7ddb0 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t27-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t27-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t27-geometry.webp new file mode 100644 index 00000000..243781e0 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t27-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t28-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t28-colour.webp new file mode 100644 index 00000000..60d7ffb0 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t28-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t28-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t28-geometry.webp new file mode 100644 index 00000000..27084cef Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t28-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t29-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t29-colour.webp new file mode 100644 index 00000000..e20ba446 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t29-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t29-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t29-geometry.webp new file mode 100644 index 00000000..98bcd910 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t29-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t30-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t30-colour.webp new file mode 100644 index 00000000..8b37ec6e Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t30-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t30-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t30-geometry.webp new file mode 100644 index 00000000..1de2b58b Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t30-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t31-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t31-colour.webp new file mode 100644 index 00000000..e368eaa2 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t31-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-1-t31-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-1-t31-geometry.webp new file mode 100644 index 00000000..8d1a8759 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-1-t31-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t00-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t00-colour.webp new file mode 100644 index 00000000..93c0093b Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t00-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t00-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t00-geometry.webp new file mode 100644 index 00000000..74594ec5 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t00-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t01-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t01-colour.webp new file mode 100644 index 00000000..1f39071e Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t01-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t01-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t01-geometry.webp new file mode 100644 index 00000000..3a7e8512 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t01-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t02-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t02-colour.webp new file mode 100644 index 00000000..24c31463 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t02-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t02-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t02-geometry.webp new file mode 100644 index 00000000..82a6ae7f Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t02-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t03-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t03-colour.webp new file mode 100644 index 00000000..8f2941bb Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t03-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t03-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t03-geometry.webp new file mode 100644 index 00000000..a56ea57c Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t03-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t04-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t04-colour.webp new file mode 100644 index 00000000..6bf2127d Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t04-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t04-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t04-geometry.webp new file mode 100644 index 00000000..340c19b7 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t04-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t05-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t05-colour.webp new file mode 100644 index 00000000..84eb0c69 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t05-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t05-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t05-geometry.webp new file mode 100644 index 00000000..9d7f0d82 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t05-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t06-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t06-colour.webp new file mode 100644 index 00000000..256a69d4 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t06-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t06-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t06-geometry.webp new file mode 100644 index 00000000..e91016e5 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t06-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t07-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t07-colour.webp new file mode 100644 index 00000000..7f3b93e4 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t07-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t07-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t07-geometry.webp new file mode 100644 index 00000000..7654fa73 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t07-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t08-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t08-colour.webp new file mode 100644 index 00000000..60cd5c1a Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t08-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t08-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t08-geometry.webp new file mode 100644 index 00000000..561a4768 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t08-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t09-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t09-colour.webp new file mode 100644 index 00000000..a18e5331 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t09-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t09-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t09-geometry.webp new file mode 100644 index 00000000..8753533d Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t09-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t10-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t10-colour.webp new file mode 100644 index 00000000..0be83368 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t10-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t10-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t10-geometry.webp new file mode 100644 index 00000000..0ed32ac1 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t10-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t11-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t11-colour.webp new file mode 100644 index 00000000..26afbd42 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t11-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t11-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t11-geometry.webp new file mode 100644 index 00000000..196977ee Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t11-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t12-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t12-colour.webp new file mode 100644 index 00000000..43a5d09e Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t12-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t12-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t12-geometry.webp new file mode 100644 index 00000000..e5b6320f Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t12-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t13-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t13-colour.webp new file mode 100644 index 00000000..14783d3c Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t13-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t13-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t13-geometry.webp new file mode 100644 index 00000000..f027c960 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t13-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t14-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t14-colour.webp new file mode 100644 index 00000000..1846db8f Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t14-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t14-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t14-geometry.webp new file mode 100644 index 00000000..bf9b2329 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t14-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t15-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t15-colour.webp new file mode 100644 index 00000000..416b1684 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t15-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t15-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t15-geometry.webp new file mode 100644 index 00000000..39f228aa Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t15-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t16-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t16-colour.webp new file mode 100644 index 00000000..49b833ea Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t16-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t16-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t16-geometry.webp new file mode 100644 index 00000000..8431805d Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t16-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t17-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t17-colour.webp new file mode 100644 index 00000000..5230f411 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t17-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t17-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t17-geometry.webp new file mode 100644 index 00000000..4305a2f4 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t17-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t18-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t18-colour.webp new file mode 100644 index 00000000..4612a1d3 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t18-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t18-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t18-geometry.webp new file mode 100644 index 00000000..64c1a000 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t18-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t19-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t19-colour.webp new file mode 100644 index 00000000..ed8b4879 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t19-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t19-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t19-geometry.webp new file mode 100644 index 00000000..6a5155db Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t19-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t20-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t20-colour.webp new file mode 100644 index 00000000..496fc9da Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t20-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t20-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t20-geometry.webp new file mode 100644 index 00000000..add706aa Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t20-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t21-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t21-colour.webp new file mode 100644 index 00000000..a7cd3c5a Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t21-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t21-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t21-geometry.webp new file mode 100644 index 00000000..3ed5b201 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t21-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t22-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t22-colour.webp new file mode 100644 index 00000000..a4548917 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t22-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t22-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t22-geometry.webp new file mode 100644 index 00000000..87be9e74 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t22-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t23-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t23-colour.webp new file mode 100644 index 00000000..ee84b831 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t23-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t23-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t23-geometry.webp new file mode 100644 index 00000000..ab9c5738 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t23-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t24-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t24-colour.webp new file mode 100644 index 00000000..44060f9d Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t24-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t24-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t24-geometry.webp new file mode 100644 index 00000000..c7bc525c Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t24-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t25-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t25-colour.webp new file mode 100644 index 00000000..5144f816 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t25-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t25-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t25-geometry.webp new file mode 100644 index 00000000..2aa20203 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t25-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t26-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t26-colour.webp new file mode 100644 index 00000000..c765d30c Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t26-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t26-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t26-geometry.webp new file mode 100644 index 00000000..60a8b652 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t26-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t27-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t27-colour.webp new file mode 100644 index 00000000..ee7bdde0 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t27-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t27-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t27-geometry.webp new file mode 100644 index 00000000..7f09cace Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t27-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t28-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t28-colour.webp new file mode 100644 index 00000000..5ea77269 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t28-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t28-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t28-geometry.webp new file mode 100644 index 00000000..e4b0fbaf Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t28-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t29-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t29-colour.webp new file mode 100644 index 00000000..0cdbdf60 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t29-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t29-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t29-geometry.webp new file mode 100644 index 00000000..2ef8405a Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t29-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t30-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t30-colour.webp new file mode 100644 index 00000000..899fde1b Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t30-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t30-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t30-geometry.webp new file mode 100644 index 00000000..9fdb3c99 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t30-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t31-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t31-colour.webp new file mode 100644 index 00000000..db63f88b Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t31-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-2-t31-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-2-t31-geometry.webp new file mode 100644 index 00000000..344e7577 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-2-t31-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t00-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t00-colour.webp new file mode 100644 index 00000000..8a66ff36 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t00-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t00-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t00-geometry.webp new file mode 100644 index 00000000..56fc3b66 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t00-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t01-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t01-colour.webp new file mode 100644 index 00000000..bb9dca6e Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t01-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t01-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t01-geometry.webp new file mode 100644 index 00000000..2b59a1d3 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t01-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t02-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t02-colour.webp new file mode 100644 index 00000000..1ac1ceea Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t02-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t02-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t02-geometry.webp new file mode 100644 index 00000000..b9aeb249 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t02-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t03-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t03-colour.webp new file mode 100644 index 00000000..d5e17840 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t03-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t03-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t03-geometry.webp new file mode 100644 index 00000000..de8c59e1 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t03-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t04-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t04-colour.webp new file mode 100644 index 00000000..8e8c072b Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t04-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t04-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t04-geometry.webp new file mode 100644 index 00000000..0a5ce836 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t04-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t05-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t05-colour.webp new file mode 100644 index 00000000..f9c058be Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t05-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t05-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t05-geometry.webp new file mode 100644 index 00000000..2d406c5b Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t05-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t06-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t06-colour.webp new file mode 100644 index 00000000..829be4a2 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t06-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t06-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t06-geometry.webp new file mode 100644 index 00000000..2f699234 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t06-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t07-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t07-colour.webp new file mode 100644 index 00000000..ce55b914 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t07-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t07-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t07-geometry.webp new file mode 100644 index 00000000..24057242 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t07-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t08-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t08-colour.webp new file mode 100644 index 00000000..e43f71f9 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t08-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t08-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t08-geometry.webp new file mode 100644 index 00000000..7d645991 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t08-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t09-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t09-colour.webp new file mode 100644 index 00000000..751da748 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t09-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t09-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t09-geometry.webp new file mode 100644 index 00000000..16938aa2 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t09-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t10-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t10-colour.webp new file mode 100644 index 00000000..1ba4f937 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t10-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t10-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t10-geometry.webp new file mode 100644 index 00000000..b90e0a18 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t10-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t11-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t11-colour.webp new file mode 100644 index 00000000..09513ecf Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t11-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t11-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t11-geometry.webp new file mode 100644 index 00000000..c6eb0d18 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t11-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t12-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t12-colour.webp new file mode 100644 index 00000000..4739a331 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t12-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t12-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t12-geometry.webp new file mode 100644 index 00000000..d52d9ce1 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t12-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t13-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t13-colour.webp new file mode 100644 index 00000000..a96c59c6 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t13-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t13-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t13-geometry.webp new file mode 100644 index 00000000..13137b55 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t13-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t14-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t14-colour.webp new file mode 100644 index 00000000..9ce20b22 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t14-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t14-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t14-geometry.webp new file mode 100644 index 00000000..f77989de Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t14-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t15-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t15-colour.webp new file mode 100644 index 00000000..22ee61cd Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t15-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t15-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t15-geometry.webp new file mode 100644 index 00000000..cba0db4d Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t15-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t16-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t16-colour.webp new file mode 100644 index 00000000..c7124cf2 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t16-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t16-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t16-geometry.webp new file mode 100644 index 00000000..9cc64f7d Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t16-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t17-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t17-colour.webp new file mode 100644 index 00000000..3bf36902 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t17-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t17-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t17-geometry.webp new file mode 100644 index 00000000..131ec0ea Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t17-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t18-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t18-colour.webp new file mode 100644 index 00000000..c4e371e5 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t18-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t18-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t18-geometry.webp new file mode 100644 index 00000000..fe6beeb2 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t18-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t19-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t19-colour.webp new file mode 100644 index 00000000..d071749b Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t19-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t19-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t19-geometry.webp new file mode 100644 index 00000000..27d87840 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t19-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t20-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t20-colour.webp new file mode 100644 index 00000000..4cadc5cb Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t20-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t20-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t20-geometry.webp new file mode 100644 index 00000000..521f42bf Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t20-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t21-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t21-colour.webp new file mode 100644 index 00000000..fbeb7e2c Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t21-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t21-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t21-geometry.webp new file mode 100644 index 00000000..3c12322f Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t21-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t22-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t22-colour.webp new file mode 100644 index 00000000..f4652b74 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t22-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t22-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t22-geometry.webp new file mode 100644 index 00000000..a67f8536 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t22-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t23-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t23-colour.webp new file mode 100644 index 00000000..d4abfd22 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t23-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t23-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t23-geometry.webp new file mode 100644 index 00000000..024c1b03 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t23-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t24-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t24-colour.webp new file mode 100644 index 00000000..fd02bc1b Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t24-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t24-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t24-geometry.webp new file mode 100644 index 00000000..15f821ca Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t24-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t25-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t25-colour.webp new file mode 100644 index 00000000..242370d1 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t25-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t25-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t25-geometry.webp new file mode 100644 index 00000000..3dd27b4a Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t25-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t26-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t26-colour.webp new file mode 100644 index 00000000..d3d28854 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t26-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t26-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t26-geometry.webp new file mode 100644 index 00000000..c566de97 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t26-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t27-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t27-colour.webp new file mode 100644 index 00000000..051a929d Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t27-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t27-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t27-geometry.webp new file mode 100644 index 00000000..11059aa9 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t27-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t28-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t28-colour.webp new file mode 100644 index 00000000..719e373c Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t28-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t28-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t28-geometry.webp new file mode 100644 index 00000000..475a0c33 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t28-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t29-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t29-colour.webp new file mode 100644 index 00000000..c63afefd Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t29-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t29-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t29-geometry.webp new file mode 100644 index 00000000..f2eecce0 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t29-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t30-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t30-colour.webp new file mode 100644 index 00000000..feb41172 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t30-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t30-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t30-geometry.webp new file mode 100644 index 00000000..74dd697d Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t30-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t31-colour.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t31-colour.webp new file mode 100644 index 00000000..2fa6d324 Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t31-colour.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/card-3-t31-geometry.webp b/public/ridge/amadablam-fb4b9d3701f8/card-3-t31-geometry.webp new file mode 100644 index 00000000..8b5be64f Binary files /dev/null and b/public/ridge/amadablam-fb4b9d3701f8/card-3-t31-geometry.webp differ diff --git a/public/ridge/amadablam-fb4b9d3701f8/manifest.json b/public/ridge/amadablam-fb4b9d3701f8/manifest.json new file mode 100644 index 00000000..74acd5dc --- /dev/null +++ b/public/ridge/amadablam-fb4b9d3701f8/manifest.json @@ -0,0 +1,1796 @@ +{ + "schema": 3, + "baker_version": 7, + "bake_id": "fb4b9d3701f8", + "place": { + "id": "amadablam", + "name": "Ama Dablam and Everest from Khumjung", + "lat": 27.822000000000003, + "lon": 86.722666666667, + "altitude_km": 3.7819838378893, + "eye_m": 3783.5838378893, + "tz": "Asia/Kathmandu" + }, + "view": { + "look_az_deg": 71.99620826401747, + "plane_h": 600, + "px_per_deg_h": 17.77777777777778, + "px_per_deg_v": 15.211655185147013, + "exaggeration": 0.8556556041645195, + "horizon_row": 450.0, + "sky_row": 24.0, + "near_row": 396.0, + "ring_w": 6400, + "tile_w": 200, + "tiles": 32, + "apron": 2 + }, + "curvature": { + "r_earth_m": 6371000.0, + "k_ref": 0.13 + }, + "encoding": { + "log_d_min": 6.214608098422191, + "log_d_max": 11.00475592466117, + "normal": "rt8" + }, + "camera": { + "r_max_m": 95.8, + "r_max_forward_m": 198.4 + }, + "cards": [ + { + "near_m": null, + "far_m": 2011.718901979742 + }, + { + "near_m": 2011.718901979742, + "far_m": 18998.714628561414 + }, + { + "near_m": 18998.714628561414, + "far_m": 34575.30863870067 + }, + { + "near_m": 34575.30863870067, + "far_m": null + } + ], + "tiles": [ + [ + { + "top": 52, + "h": 548, + "distance_m": 827.252197265625, + "colour": { + "file": "card-0-t00-colour.webp", + "bytes": 1838 + }, + "geometry": { + "file": "card-0-t00-geometry.webp", + "bytes": 28162 + } + }, + { + "top": 67, + "h": 533, + "distance_m": 2306.083984375, + "colour": { + "file": "card-1-t00-colour.webp", + "bytes": 558 + }, + "geometry": { + "file": "card-1-t00-geometry.webp", + "bytes": 326 + } + }, + { + "top": 336, + "h": 264, + "distance_m": 23771.404296875, + "colour": { + "file": "card-2-t00-colour.webp", + "bytes": 1290 + }, + "geometry": { + "file": "card-2-t00-geometry.webp", + "bytes": 4978 + } + }, + { + "top": 377, + "h": 223, + "distance_m": 33055.8046875, + "colour": { + "file": "card-3-t00-colour.webp", + "bytes": 394 + }, + "geometry": { + "file": "card-3-t00-geometry.webp", + "bytes": 1576 + } + } + ], + [ + { + "top": 79, + "h": 521, + "distance_m": 770.1353759765625, + "colour": { + "file": "card-0-t01-colour.webp", + "bytes": 2048 + }, + "geometry": { + "file": "card-0-t01-geometry.webp", + "bytes": 31896 + } + }, + { + "top": 124, + "h": 476, + "distance_m": 1900.0, + "colour": { + "file": "card-1-t01-colour.webp", + "bytes": 550 + }, + "geometry": { + "file": "card-1-t01-geometry.webp", + "bytes": 282 + } + }, + { + "top": 333, + "h": 267, + "distance_m": 21694.78125, + "colour": { + "file": "card-2-t01-colour.webp", + "bytes": 1000 + }, + "geometry": { + "file": "card-2-t01-geometry.webp", + "bytes": 3070 + } + }, + { + "top": 382, + "h": 218, + "distance_m": 32924.10546875, + "colour": { + "file": "card-3-t01-colour.webp", + "bytes": 418 + }, + "geometry": { + "file": "card-3-t01-geometry.webp", + "bytes": 1936 + } + } + ], + [ + { + "top": 143, + "h": 457, + "distance_m": 739.466796875, + "colour": { + "file": "card-0-t02-colour.webp", + "bytes": 1984 + }, + "geometry": { + "file": "card-0-t02-geometry.webp", + "bytes": 25648 + } + }, + { + "top": 226, + "h": 374, + "distance_m": 9601.2099609375, + "colour": { + "file": "card-1-t02-colour.webp", + "bytes": 2024 + }, + "geometry": { + "file": "card-1-t02-geometry.webp", + "bytes": 14730 + } + }, + { + "top": 332, + "h": 268, + "distance_m": 24564.380859375, + "colour": { + "file": "card-2-t02-colour.webp", + "bytes": 1394 + }, + "geometry": { + "file": "card-2-t02-geometry.webp", + "bytes": 5922 + } + }, + { + "top": 372, + "h": 228, + "distance_m": 35593.87890625, + "colour": { + "file": "card-3-t02-colour.webp", + "bytes": 688 + }, + "geometry": { + "file": "card-3-t02-geometry.webp", + "bytes": 3856 + } + } + ], + [ + { + "top": 228, + "h": 372, + "distance_m": 737.2044067382812, + "colour": { + "file": "card-0-t03-colour.webp", + "bytes": 1622 + }, + "geometry": { + "file": "card-0-t03-geometry.webp", + "bytes": 18656 + } + }, + { + "top": 226, + "h": 374, + "distance_m": 5174.55615234375, + "colour": { + "file": "card-1-t03-colour.webp", + "bytes": 3264 + }, + "geometry": { + "file": "card-1-t03-geometry.webp", + "bytes": 27148 + } + }, + { + "top": 301, + "h": 299, + "distance_m": 22038.73828125, + "colour": { + "file": "card-2-t03-colour.webp", + "bytes": 1774 + }, + "geometry": { + "file": "card-2-t03-geometry.webp", + "bytes": 8954 + } + }, + { + "top": 372, + "h": 228, + "distance_m": 33857.1328125, + "colour": { + "file": "card-3-t03-colour.webp", + "bytes": 422 + }, + "geometry": { + "file": "card-3-t03-geometry.webp", + "bytes": 1780 + } + } + ], + [ + { + "top": 343, + "h": 257, + "distance_m": 818.1093139648438, + "colour": { + "file": "card-0-t04-colour.webp", + "bytes": 1776 + }, + "geometry": { + "file": "card-0-t04-geometry.webp", + "bytes": 15200 + } + }, + { + "top": 266, + "h": 334, + "distance_m": 4350.2265625, + "colour": { + "file": "card-1-t04-colour.webp", + "bytes": 2944 + }, + "geometry": { + "file": "card-1-t04-geometry.webp", + "bytes": 30542 + } + }, + { + "top": 295, + "h": 305, + "distance_m": 22713.22265625, + "colour": { + "file": "card-2-t04-colour.webp", + "bytes": 2972 + }, + "geometry": { + "file": "card-2-t04-geometry.webp", + "bytes": 17908 + } + }, + { + "top": 373, + "h": 227, + "distance_m": 35946.43359375, + "colour": { + "file": "card-3-t04-colour.webp", + "bytes": 624 + }, + "geometry": { + "file": "card-3-t04-geometry.webp", + "bytes": 2946 + } + } + ], + [ + { + "top": 447, + "h": 153, + "distance_m": 1052.255859375, + "colour": { + "file": "card-0-t05-colour.webp", + "bytes": 1374 + }, + "geometry": { + "file": "card-0-t05-geometry.webp", + "bytes": 7956 + } + }, + { + "top": 321, + "h": 279, + "distance_m": 3597.237548828125, + "colour": { + "file": "card-1-t05-colour.webp", + "bytes": 2970 + }, + "geometry": { + "file": "card-1-t05-geometry.webp", + "bytes": 37740 + } + }, + { + "top": 319, + "h": 281, + "distance_m": 25097.0, + "colour": { + "file": "card-2-t05-colour.webp", + "bytes": 2224 + }, + "geometry": { + "file": "card-2-t05-geometry.webp", + "bytes": 12520 + } + }, + { + "top": 376, + "h": 224, + "distance_m": 33264.33203125, + "colour": { + "file": "card-3-t05-colour.webp", + "bytes": 536 + }, + "geometry": { + "file": "card-3-t05-geometry.webp", + "bytes": 1356 + } + } + ], + [ + { + "top": 572, + "h": 28, + "distance_m": 1153.4088134765625, + "colour": { + "file": "card-0-t06-colour.webp", + "bytes": 258 + }, + "geometry": { + "file": "card-0-t06-geometry.webp", + "bytes": 408 + } + }, + { + "top": 277, + "h": 323, + "distance_m": 4320.556640625, + "colour": { + "file": "card-1-t06-colour.webp", + "bytes": 3458 + }, + "geometry": { + "file": "card-1-t06-geometry.webp", + "bytes": 46336 + } + }, + { + "top": 335, + "h": 265, + "distance_m": 19104.140625, + "colour": { + "file": "card-2-t06-colour.webp", + "bytes": 988 + }, + "geometry": { + "file": "card-2-t06-geometry.webp", + "bytes": 5090 + } + }, + { + "top": 348, + "h": 252, + "distance_m": 35518.5, + "colour": { + "file": "card-3-t06-colour.webp", + "bytes": 1318 + }, + "geometry": { + "file": "card-3-t06-geometry.webp", + "bytes": 7340 + } + } + ], + [ + { + "top": 546, + "h": 54, + "distance_m": 523.5120849609375, + "colour": { + "file": "card-0-t07-colour.webp", + "bytes": 490 + }, + "geometry": { + "file": "card-0-t07-geometry.webp", + "bytes": 328 + } + }, + { + "top": 289, + "h": 311, + "distance_m": 2965.19775390625, + "colour": { + "file": "card-1-t07-colour.webp", + "bytes": 3514 + }, + "geometry": { + "file": "card-1-t07-geometry.webp", + "bytes": 35732 + } + }, + { + "top": 349, + "h": 251, + "distance_m": 24699.427734375, + "colour": { + "file": "card-2-t07-colour.webp", + "bytes": 582 + }, + "geometry": { + "file": "card-2-t07-geometry.webp", + "bytes": 1650 + } + }, + { + "top": 354, + "h": 246, + "distance_m": 36083.16796875, + "colour": { + "file": "card-3-t07-colour.webp", + "bytes": 1230 + }, + "geometry": { + "file": "card-3-t07-geometry.webp", + "bytes": 6006 + } + } + ], + [ + { + "top": 508, + "h": 92, + "distance_m": 554.8743896484375, + "colour": { + "file": "card-0-t08-colour.webp", + "bytes": 540 + }, + "geometry": { + "file": "card-0-t08-geometry.webp", + "bytes": 732 + } + }, + { + "top": 237, + "h": 363, + "distance_m": 2739.012939453125, + "colour": { + "file": "card-1-t08-colour.webp", + "bytes": 2908 + }, + "geometry": { + "file": "card-1-t08-geometry.webp", + "bytes": 34586 + } + }, + { + "top": 335, + "h": 265, + "distance_m": 25563.431640625, + "colour": { + "file": "card-2-t08-colour.webp", + "bytes": 1146 + }, + "geometry": { + "file": "card-2-t08-geometry.webp", + "bytes": 4426 + } + }, + { + "top": 383, + "h": 217, + "distance_m": 34539.72265625, + "colour": { + "file": "card-3-t08-colour.webp", + "bytes": 834 + }, + "geometry": { + "file": "card-3-t08-geometry.webp", + "bytes": 2590 + } + } + ], + [ + { + "top": 500, + "h": 100, + "distance_m": 552.1141967773438, + "colour": { + "file": "card-0-t09-colour.webp", + "bytes": 370 + }, + "geometry": { + "file": "card-0-t09-geometry.webp", + "bytes": 2318 + } + }, + { + "top": 186, + "h": 414, + "distance_m": 3015.078369140625, + "colour": { + "file": "card-1-t09-colour.webp", + "bytes": 4034 + }, + "geometry": { + "file": "card-1-t09-geometry.webp", + "bytes": 43760 + } + }, + { + "top": 326, + "h": 274, + "distance_m": 18802.935546875, + "colour": { + "file": "card-2-t09-colour.webp", + "bytes": 1470 + }, + "geometry": { + "file": "card-2-t09-geometry.webp", + "bytes": 7174 + } + }, + { + "top": 403, + "h": 197, + "distance_m": 37542.0, + "colour": { + "file": "card-3-t09-colour.webp", + "bytes": 774 + }, + "geometry": { + "file": "card-3-t09-geometry.webp", + "bytes": 2216 + } + } + ], + [ + { + "top": 444, + "h": 156, + "distance_m": 639.7239379882812, + "colour": { + "file": "card-0-t10-colour.webp", + "bytes": 638 + }, + "geometry": { + "file": "card-0-t10-geometry.webp", + "bytes": 2276 + } + }, + { + "top": 123, + "h": 477, + "distance_m": 3232.07958984375, + "colour": { + "file": "card-1-t10-colour.webp", + "bytes": 5368 + }, + "geometry": { + "file": "card-1-t10-geometry.webp", + "bytes": 54868 + } + }, + { + "top": 354, + "h": 246, + "distance_m": 18597.224609375, + "colour": { + "file": "card-2-t10-colour.webp", + "bytes": 1214 + }, + "geometry": { + "file": "card-2-t10-geometry.webp", + "bytes": 6840 + } + }, + { + "top": 419, + "h": 181, + "distance_m": 34387.94140625, + "colour": { + "file": "card-3-t10-colour.webp", + "bytes": 566 + }, + "geometry": { + "file": "card-3-t10-geometry.webp", + "bytes": 2010 + } + } + ], + [ + { + "top": 346, + "h": 254, + "distance_m": 523.1098022460938, + "colour": { + "file": "card-0-t11-colour.webp", + "bytes": 766 + }, + "geometry": { + "file": "card-0-t11-geometry.webp", + "bytes": 2440 + } + }, + { + "top": 167, + "h": 433, + "distance_m": 2894.937744140625, + "colour": { + "file": "card-1-t11-colour.webp", + "bytes": 4430 + }, + "geometry": { + "file": "card-1-t11-geometry.webp", + "bytes": 45170 + } + }, + { + "top": 332, + "h": 268, + "distance_m": 18381.962890625, + "colour": { + "file": "card-2-t11-colour.webp", + "bytes": 1414 + }, + "geometry": { + "file": "card-2-t11-geometry.webp", + "bytes": 7804 + } + }, + { + "top": 413, + "h": 187, + "distance_m": 32349.83203125, + "colour": { + "file": "card-3-t11-colour.webp", + "bytes": 332 + }, + "geometry": { + "file": "card-3-t11-geometry.webp", + "bytes": 304 + } + } + ], + [ + { + "top": 313, + "h": 287, + "distance_m": 523.9810180664062, + "colour": { + "file": "card-0-t12-colour.webp", + "bytes": 678 + }, + "geometry": { + "file": "card-0-t12-geometry.webp", + "bytes": 5612 + } + }, + { + "top": 207, + "h": 393, + "distance_m": 2714.9775390625, + "colour": { + "file": "card-1-t12-colour.webp", + "bytes": 3234 + }, + "geometry": { + "file": "card-1-t12-geometry.webp", + "bytes": 33776 + } + }, + { + "top": 341, + "h": 259, + "distance_m": 18151.8203125, + "colour": { + "file": "card-2-t12-colour.webp", + "bytes": 954 + }, + "geometry": { + "file": "card-2-t12-geometry.webp", + "bytes": 4906 + } + }, + { + "top": 433, + "h": 167, + "distance_m": 34449.2578125, + "colour": { + "file": "card-3-t12-colour.webp", + "bytes": 794 + }, + "geometry": { + "file": "card-3-t12-geometry.webp", + "bytes": 6030 + } + } + ], + [ + { + "top": 345, + "h": 255, + "distance_m": 529.6943969726562, + "colour": { + "file": "card-0-t13-colour.webp", + "bytes": 522 + }, + "geometry": { + "file": "card-0-t13-geometry.webp", + "bytes": 2858 + } + }, + { + "top": 270, + "h": 330, + "distance_m": 2625.431640625, + "colour": { + "file": "card-1-t13-colour.webp", + "bytes": 3816 + }, + "geometry": { + "file": "card-1-t13-geometry.webp", + "bytes": 31634 + } + }, + { + "top": 396, + "h": 204, + "distance_m": 20311.169921875, + "colour": { + "file": "card-2-t13-colour.webp", + "bytes": 760 + }, + "geometry": { + "file": "card-2-t13-geometry.webp", + "bytes": 4466 + } + }, + { + "top": 446, + "h": 154, + "distance_m": 38793.6328125, + "colour": { + "file": "card-3-t13-colour.webp", + "bytes": 1348 + }, + "geometry": { + "file": "card-3-t13-geometry.webp", + "bytes": 10858 + } + } + ], + [ + { + "top": 300, + "h": 300, + "distance_m": 500.0, + "colour": { + "file": "card-0-t14-colour.webp", + "bytes": 688 + }, + "geometry": { + "file": "card-0-t14-geometry.webp", + "bytes": 3402 + } + }, + { + "top": 322, + "h": 278, + "distance_m": 2918.640625, + "colour": { + "file": "card-1-t14-colour.webp", + "bytes": 3414 + }, + "geometry": { + "file": "card-1-t14-geometry.webp", + "bytes": 29566 + } + }, + { + "top": 383, + "h": 217, + "distance_m": 18614.470703125, + "colour": { + "file": "card-2-t14-colour.webp", + "bytes": 1140 + }, + "geometry": { + "file": "card-2-t14-geometry.webp", + "bytes": 7116 + } + }, + { + "top": 457, + "h": 143, + "distance_m": 42439.03125, + "colour": { + "file": "card-3-t14-colour.webp", + "bytes": 1074 + }, + "geometry": { + "file": "card-3-t14-geometry.webp", + "bytes": 8620 + } + } + ], + [ + { + "top": 302, + "h": 298, + "distance_m": 525.7131958007812, + "colour": { + "file": "card-0-t15-colour.webp", + "bytes": 644 + }, + "geometry": { + "file": "card-0-t15-geometry.webp", + "bytes": 5268 + } + }, + { + "top": 405, + "h": 195, + "distance_m": 3244.2470703125, + "colour": { + "file": "card-1-t15-colour.webp", + "bytes": 3522 + }, + "geometry": { + "file": "card-1-t15-geometry.webp", + "bytes": 25236 + } + }, + { + "top": 415, + "h": 185, + "distance_m": 18155.212890625, + "colour": { + "file": "card-2-t15-colour.webp", + "bytes": 1320 + }, + "geometry": { + "file": "card-2-t15-geometry.webp", + "bytes": 7704 + } + }, + { + "top": 466, + "h": 134, + "distance_m": 41500.03515625, + "colour": { + "file": "card-3-t15-colour.webp", + "bytes": 1160 + }, + "geometry": { + "file": "card-3-t15-geometry.webp", + "bytes": 9572 + } + } + ], + [ + { + "top": 357, + "h": 243, + "distance_m": 546.4453735351562, + "colour": { + "file": "card-0-t16-colour.webp", + "bytes": 546 + }, + "geometry": { + "file": "card-0-t16-geometry.webp", + "bytes": 3254 + } + }, + { + "top": 469, + "h": 131, + "distance_m": 6915.326171875, + "colour": { + "file": "card-1-t16-colour.webp", + "bytes": 3182 + }, + "geometry": { + "file": "card-1-t16-geometry.webp", + "bytes": 22194 + } + }, + { + "top": 468, + "h": 132, + "distance_m": 18603.43359375, + "colour": { + "file": "card-2-t16-colour.webp", + "bytes": 1668 + }, + "geometry": { + "file": "card-2-t16-geometry.webp", + "bytes": 12026 + } + }, + { + "top": 468, + "h": 132, + "distance_m": 34757.94140625, + "colour": { + "file": "card-3-t16-colour.webp", + "bytes": 818 + }, + "geometry": { + "file": "card-3-t16-geometry.webp", + "bytes": 5748 + } + } + ], + [ + { + "top": 313, + "h": 287, + "distance_m": 523.0396728515625, + "colour": { + "file": "card-0-t17-colour.webp", + "bytes": 988 + }, + "geometry": { + "file": "card-0-t17-geometry.webp", + "bytes": 7722 + } + }, + { + "top": 388, + "h": 212, + "distance_m": 4265.77197265625, + "colour": { + "file": "card-1-t17-colour.webp", + "bytes": 1906 + }, + "geometry": { + "file": "card-1-t17-geometry.webp", + "bytes": 21338 + } + }, + { + "top": 442, + "h": 158, + "distance_m": 18450.51171875, + "colour": { + "file": "card-2-t17-colour.webp", + "bytes": 774 + }, + "geometry": { + "file": "card-2-t17-geometry.webp", + "bytes": 4476 + } + }, + { + "top": 458, + "h": 142, + "distance_m": 32626.9453125, + "colour": { + "file": "card-3-t17-colour.webp", + "bytes": 282 + }, + "geometry": { + "file": "card-3-t17-geometry.webp", + "bytes": 1672 + } + } + ], + [ + { + "top": 291, + "h": 309, + "distance_m": 500.0, + "colour": { + "file": "card-0-t18-colour.webp", + "bytes": 1032 + }, + "geometry": { + "file": "card-0-t18-geometry.webp", + "bytes": 10594 + } + }, + { + "top": 350, + "h": 250, + "distance_m": 4179.998046875, + "colour": { + "file": "card-1-t18-colour.webp", + "bytes": 1980 + }, + "geometry": { + "file": "card-1-t18-geometry.webp", + "bytes": 24574 + } + }, + { + "top": 406, + "h": 194, + "distance_m": 18500.25, + "colour": { + "file": "card-2-t18-colour.webp", + "bytes": 446 + }, + "geometry": { + "file": "card-2-t18-geometry.webp", + "bytes": 1658 + } + }, + { + "top": 454, + "h": 146, + "distance_m": 34677.88671875, + "colour": { + "file": "card-3-t18-colour.webp", + "bytes": 392 + }, + "geometry": { + "file": "card-3-t18-geometry.webp", + "bytes": 5676 + } + } + ], + [ + { + "top": 307, + "h": 293, + "distance_m": 500.0, + "colour": { + "file": "card-0-t19-colour.webp", + "bytes": 932 + }, + "geometry": { + "file": "card-0-t19-geometry.webp", + "bytes": 10042 + } + }, + { + "top": 254, + "h": 346, + "distance_m": 4489.41259765625, + "colour": { + "file": "card-1-t19-colour.webp", + "bytes": 3160 + }, + "geometry": { + "file": "card-1-t19-geometry.webp", + "bytes": 28840 + } + }, + { + "top": 392, + "h": 208, + "distance_m": 17933.982421875, + "colour": { + "file": "card-2-t19-colour.webp", + "bytes": 442 + }, + "geometry": { + "file": "card-2-t19-geometry.webp", + "bytes": 1906 + } + }, + { + "top": 440, + "h": 160, + "distance_m": 32843.57421875, + "colour": { + "file": "card-3-t19-colour.webp", + "bytes": 352 + }, + "geometry": { + "file": "card-3-t19-geometry.webp", + "bytes": 2892 + } + } + ], + [ + { + "top": 331, + "h": 269, + "distance_m": 500.0, + "colour": { + "file": "card-0-t20-colour.webp", + "bytes": 838 + }, + "geometry": { + "file": "card-0-t20-geometry.webp", + "bytes": 8638 + } + }, + { + "top": 237, + "h": 363, + "distance_m": 6391.69873046875, + "colour": { + "file": "card-1-t20-colour.webp", + "bytes": 5078 + }, + "geometry": { + "file": "card-1-t20-geometry.webp", + "bytes": 38070 + } + }, + { + "top": 373, + "h": 227, + "distance_m": 17875.4140625, + "colour": { + "file": "card-2-t20-colour.webp", + "bytes": 424 + }, + "geometry": { + "file": "card-2-t20-geometry.webp", + "bytes": 1544 + } + }, + { + "top": 444, + "h": 156, + "distance_m": 33320.78125, + "colour": { + "file": "card-3-t20-colour.webp", + "bytes": 564 + }, + "geometry": { + "file": "card-3-t20-geometry.webp", + "bytes": 5586 + } + } + ], + [ + { + "top": 326, + "h": 274, + "distance_m": 923.2710571289062, + "colour": { + "file": "card-0-t21-colour.webp", + "bytes": 974 + }, + "geometry": { + "file": "card-0-t21-geometry.webp", + "bytes": 12070 + } + }, + { + "top": 216, + "h": 384, + "distance_m": 6441.12890625, + "colour": { + "file": "card-1-t21-colour.webp", + "bytes": 3532 + }, + "geometry": { + "file": "card-1-t21-geometry.webp", + "bytes": 30322 + } + }, + { + "top": 339, + "h": 261, + "distance_m": 18364.421875, + "colour": { + "file": "card-2-t21-colour.webp", + "bytes": 602 + }, + "geometry": { + "file": "card-2-t21-geometry.webp", + "bytes": 1468 + } + }, + { + "top": 437, + "h": 163, + "distance_m": 33722.2421875, + "colour": { + "file": "card-3-t21-colour.webp", + "bytes": 652 + }, + "geometry": { + "file": "card-3-t21-geometry.webp", + "bytes": 7230 + } + } + ], + [ + { + "top": 327, + "h": 273, + "distance_m": 911.6795043945312, + "colour": { + "file": "card-0-t22-colour.webp", + "bytes": 974 + }, + "geometry": { + "file": "card-0-t22-geometry.webp", + "bytes": 13546 + } + }, + { + "top": 216, + "h": 384, + "distance_m": 6546.775390625, + "colour": { + "file": "card-1-t22-colour.webp", + "bytes": 3466 + }, + "geometry": { + "file": "card-1-t22-geometry.webp", + "bytes": 26118 + } + }, + { + "top": 351, + "h": 249, + "distance_m": 18930.142578125, + "colour": { + "file": "card-2-t22-colour.webp", + "bytes": 648 + }, + "geometry": { + "file": "card-2-t22-geometry.webp", + "bytes": 2904 + } + }, + { + "top": 422, + "h": 178, + "distance_m": 32402.568359375, + "colour": { + "file": "card-3-t22-colour.webp", + "bytes": 374 + }, + "geometry": { + "file": "card-3-t22-geometry.webp", + "bytes": 512 + } + } + ], + [ + { + "top": 304, + "h": 296, + "distance_m": 2027.4254150390625, + "colour": { + "file": "card-0-t23-colour.webp", + "bytes": 962 + }, + "geometry": { + "file": "card-0-t23-geometry.webp", + "bytes": 16670 + } + }, + { + "top": 271, + "h": 329, + "distance_m": 11896.4462890625, + "colour": { + "file": "card-1-t23-colour.webp", + "bytes": 3394 + }, + "geometry": { + "file": "card-1-t23-geometry.webp", + "bytes": 17558 + } + }, + { + "top": 310, + "h": 290, + "distance_m": 18561.185546875, + "colour": { + "file": "card-2-t23-colour.webp", + "bytes": 1060 + }, + "geometry": { + "file": "card-2-t23-geometry.webp", + "bytes": 3476 + } + }, + { + "top": 414, + "h": 186, + "distance_m": 33320.78125, + "colour": { + "file": "card-3-t23-colour.webp", + "bytes": 368 + }, + "geometry": { + "file": "card-3-t23-geometry.webp", + "bytes": 1318 + } + } + ], + [ + { + "top": 294, + "h": 306, + "distance_m": 1915.7430419921875, + "colour": { + "file": "card-0-t24-colour.webp", + "bytes": 852 + }, + "geometry": { + "file": "card-0-t24-geometry.webp", + "bytes": 15996 + } + }, + { + "top": 312, + "h": 288, + "distance_m": 16016.1455078125, + "colour": { + "file": "card-1-t24-colour.webp", + "bytes": 1746 + }, + "geometry": { + "file": "card-1-t24-geometry.webp", + "bytes": 10906 + } + }, + { + "top": 344, + "h": 256, + "distance_m": 20518.1796875, + "colour": { + "file": "card-2-t24-colour.webp", + "bytes": 464 + }, + "geometry": { + "file": "card-2-t24-geometry.webp", + "bytes": 758 + } + }, + { + "top": 408, + "h": 192, + "distance_m": 33487.234375, + "colour": { + "file": "card-3-t24-colour.webp", + "bytes": 610 + }, + "geometry": { + "file": "card-3-t24-geometry.webp", + "bytes": 2436 + } + } + ], + [ + { + "top": 264, + "h": 336, + "distance_m": 1279.4014892578125, + "colour": { + "file": "card-0-t25-colour.webp", + "bytes": 914 + }, + "geometry": { + "file": "card-0-t25-geometry.webp", + "bytes": 20056 + } + }, + { + "top": 279, + "h": 321, + "distance_m": 4082.07861328125, + "colour": { + "file": "card-1-t25-colour.webp", + "bytes": 2164 + }, + "geometry": { + "file": "card-1-t25-geometry.webp", + "bytes": 13732 + } + }, + { + "top": 322, + "h": 278, + "distance_m": 21545.11328125, + "colour": { + "file": "card-2-t25-colour.webp", + "bytes": 472 + }, + "geometry": { + "file": "card-2-t25-geometry.webp", + "bytes": 406 + } + }, + { + "top": 386, + "h": 214, + "distance_m": 35783.83203125, + "colour": { + "file": "card-3-t25-colour.webp", + "bytes": 914 + }, + "geometry": { + "file": "card-3-t25-geometry.webp", + "bytes": 3836 + } + } + ], + [ + { + "top": 181, + "h": 419, + "distance_m": 1077.19091796875, + "colour": { + "file": "card-0-t26-colour.webp", + "bytes": 1566 + }, + "geometry": { + "file": "card-0-t26-geometry.webp", + "bytes": 27326 + } + }, + { + "top": 207, + "h": 393, + "distance_m": 4019.7578125, + "colour": { + "file": "card-1-t26-colour.webp", + "bytes": 1952 + }, + "geometry": { + "file": "card-1-t26-geometry.webp", + "bytes": 14416 + } + }, + { + "top": 335, + "h": 265, + "distance_m": 18407.029296875, + "colour": { + "file": "card-2-t26-colour.webp", + "bytes": 1274 + }, + "geometry": { + "file": "card-2-t26-geometry.webp", + "bytes": 6502 + } + }, + { + "top": 369, + "h": 231, + "distance_m": 33237.1875, + "colour": { + "file": "card-3-t26-colour.webp", + "bytes": 1180 + }, + "geometry": { + "file": "card-3-t26-geometry.webp", + "bytes": 4466 + } + } + ], + [ + { + "top": 155, + "h": 445, + "distance_m": 1115.248291015625, + "colour": { + "file": "card-0-t27-colour.webp", + "bytes": 1496 + }, + "geometry": { + "file": "card-0-t27-geometry.webp", + "bytes": 28856 + } + }, + { + "top": 161, + "h": 439, + "distance_m": 4460.001953125, + "colour": { + "file": "card-1-t27-colour.webp", + "bytes": 1820 + }, + "geometry": { + "file": "card-1-t27-geometry.webp", + "bytes": 9902 + } + }, + { + "top": 342, + "h": 258, + "distance_m": 21357.478515625, + "colour": { + "file": "card-2-t27-colour.webp", + "bytes": 898 + }, + "geometry": { + "file": "card-2-t27-geometry.webp", + "bytes": 3388 + } + }, + { + "top": 397, + "h": 203, + "distance_m": 32792.93359375, + "colour": { + "file": "card-3-t27-colour.webp", + "bytes": 404 + }, + "geometry": { + "file": "card-3-t27-geometry.webp", + "bytes": 778 + } + } + ], + [ + { + "top": 53, + "h": 547, + "distance_m": 1288.4852294921875, + "colour": { + "file": "card-0-t28-colour.webp", + "bytes": 1978 + }, + "geometry": { + "file": "card-0-t28-geometry.webp", + "bytes": 31906 + } + }, + { + "top": 65, + "h": 535, + "distance_m": 2982.763916015625, + "colour": { + "file": "card-1-t28-colour.webp", + "bytes": 1046 + }, + "geometry": { + "file": "card-1-t28-geometry.webp", + "bytes": 3854 + } + }, + { + "top": 365, + "h": 235, + "distance_m": 20124.375, + "colour": { + "file": "card-2-t28-colour.webp", + "bytes": 1440 + }, + "geometry": { + "file": "card-2-t28-geometry.webp", + "bytes": 8884 + } + }, + { + "top": 398, + "h": 202, + "distance_m": 33286.3515625, + "colour": { + "file": "card-3-t28-colour.webp", + "bytes": 490 + }, + "geometry": { + "file": "card-3-t28-geometry.webp", + "bytes": 2182 + } + } + ], + [ + { + "top": 24, + "h": 576, + "distance_m": 1518.8189697265625, + "colour": { + "file": "card-0-t29-colour.webp", + "bytes": 2624 + }, + "geometry": { + "file": "card-0-t29-geometry.webp", + "bytes": 34324 + } + }, + { + "top": 34, + "h": 566, + "distance_m": 3090.216552734375, + "colour": { + "file": "card-1-t29-colour.webp", + "bytes": 716 + }, + "geometry": { + "file": "card-1-t29-geometry.webp", + "bytes": 1330 + } + }, + { + "top": 356, + "h": 244, + "distance_m": 28378.375, + "colour": { + "file": "card-2-t29-colour.webp", + "bytes": 856 + }, + "geometry": { + "file": "card-2-t29-geometry.webp", + "bytes": 3104 + } + }, + { + "top": 383, + "h": 217, + "distance_m": 33587.88671875, + "colour": { + "file": "card-3-t29-colour.webp", + "bytes": 654 + }, + "geometry": { + "file": "card-3-t29-geometry.webp", + "bytes": 2366 + } + } + ], + [ + { + "top": 24, + "h": 576, + "distance_m": 1460.000244140625, + "colour": { + "file": "card-0-t30-colour.webp", + "bytes": 2684 + }, + "geometry": { + "file": "card-0-t30-geometry.webp", + "bytes": 31042 + } + }, + { + "top": 42, + "h": 558, + "distance_m": 3196.747314453125, + "colour": { + "file": "card-1-t30-colour.webp", + "bytes": 550 + }, + "geometry": { + "file": "card-1-t30-geometry.webp", + "bytes": 330 + } + }, + { + "top": 331, + "h": 269, + "distance_m": 27157.220703125, + "colour": { + "file": "card-2-t30-colour.webp", + "bytes": 2094 + }, + "geometry": { + "file": "card-2-t30-geometry.webp", + "bytes": 12678 + } + }, + { + "top": 351, + "h": 249, + "distance_m": 33010.56640625, + "colour": { + "file": "card-3-t30-colour.webp", + "bytes": 552 + }, + "geometry": { + "file": "card-3-t30-geometry.webp", + "bytes": 894 + } + } + ], + [ + { + "top": 29, + "h": 571, + "distance_m": 1045.033935546875, + "colour": { + "file": "card-0-t31-colour.webp", + "bytes": 2756 + }, + "geometry": { + "file": "card-0-t31-geometry.webp", + "bytes": 31704 + } + }, + { + "top": 48, + "h": 552, + "distance_m": 2780.00048828125, + "colour": { + "file": "card-1-t31-colour.webp", + "bytes": 606 + }, + "geometry": { + "file": "card-1-t31-geometry.webp", + "bytes": 278 + } + }, + { + "top": 332, + "h": 268, + "distance_m": 29552.09765625, + "colour": { + "file": "card-2-t31-colour.webp", + "bytes": 2102 + }, + "geometry": { + "file": "card-2-t31-geometry.webp", + "bytes": 12352 + } + }, + { + "top": 347, + "h": 253, + "distance_m": 32273.474609375, + "colour": { + "file": "card-3-t31-colour.webp", + "bytes": 422 + }, + "geometry": { + "file": "card-3-t31-geometry.webp", + "bytes": 196 + } + } + ] + ], + "bytes": 1700446, + "attribution": { + "credit_line": "Contains modified Copernicus data: DEM \u00a9 DLR e.V. 2010-2014 and \u00a9 Airbus Defence and Space GmbH 2014-2018 provided under COPERNICUS by the European Union and ESA; all rights reserved.", + "licence": "Copernicus DEM licence: free, full and open access, with the credit line shown", + "dem_source": "Copernicus DEM GLO-30 (30 m)", + "url": "https://spacedata.copernicus.eu/collections/copernicus-digital-elevation-model" + } +} diff --git a/public/ridge/fuji-8dac36611b90/card-0-t00-colour.webp b/public/ridge/fuji-8dac36611b90/card-0-t00-colour.webp new file mode 100644 index 00000000..6308056b Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t00-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t00-geometry.webp b/public/ridge/fuji-8dac36611b90/card-0-t00-geometry.webp new file mode 100644 index 00000000..b47faed9 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t00-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t01-colour.webp b/public/ridge/fuji-8dac36611b90/card-0-t01-colour.webp new file mode 100644 index 00000000..9057d08b Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t01-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t01-geometry.webp b/public/ridge/fuji-8dac36611b90/card-0-t01-geometry.webp new file mode 100644 index 00000000..4c47052d Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t01-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t02-colour.webp b/public/ridge/fuji-8dac36611b90/card-0-t02-colour.webp new file mode 100644 index 00000000..d73e6920 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t02-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t02-geometry.webp b/public/ridge/fuji-8dac36611b90/card-0-t02-geometry.webp new file mode 100644 index 00000000..c2d51df1 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t02-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t03-colour.webp b/public/ridge/fuji-8dac36611b90/card-0-t03-colour.webp new file mode 100644 index 00000000..2dbf6053 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t03-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t03-geometry.webp b/public/ridge/fuji-8dac36611b90/card-0-t03-geometry.webp new file mode 100644 index 00000000..a5cf99cf Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t03-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t04-colour.webp b/public/ridge/fuji-8dac36611b90/card-0-t04-colour.webp new file mode 100644 index 00000000..cbec1ac1 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t04-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t04-geometry.webp b/public/ridge/fuji-8dac36611b90/card-0-t04-geometry.webp new file mode 100644 index 00000000..04903f82 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t04-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t05-colour.webp b/public/ridge/fuji-8dac36611b90/card-0-t05-colour.webp new file mode 100644 index 00000000..c9ecda1d Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t05-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t05-geometry.webp b/public/ridge/fuji-8dac36611b90/card-0-t05-geometry.webp new file mode 100644 index 00000000..ca369183 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t05-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t06-colour.webp b/public/ridge/fuji-8dac36611b90/card-0-t06-colour.webp new file mode 100644 index 00000000..0557c2f5 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t06-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t06-geometry.webp b/public/ridge/fuji-8dac36611b90/card-0-t06-geometry.webp new file mode 100644 index 00000000..9976c7ea Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t06-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t07-colour.webp b/public/ridge/fuji-8dac36611b90/card-0-t07-colour.webp new file mode 100644 index 00000000..1afc44f9 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t07-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t07-geometry.webp b/public/ridge/fuji-8dac36611b90/card-0-t07-geometry.webp new file mode 100644 index 00000000..4bd92c12 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t07-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t08-colour.webp b/public/ridge/fuji-8dac36611b90/card-0-t08-colour.webp new file mode 100644 index 00000000..b8ace42b Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t08-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t08-geometry.webp b/public/ridge/fuji-8dac36611b90/card-0-t08-geometry.webp new file mode 100644 index 00000000..8999900e Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t08-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t09-colour.webp b/public/ridge/fuji-8dac36611b90/card-0-t09-colour.webp new file mode 100644 index 00000000..0b43015a Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t09-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t09-geometry.webp b/public/ridge/fuji-8dac36611b90/card-0-t09-geometry.webp new file mode 100644 index 00000000..79b6ce93 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t09-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t10-colour.webp b/public/ridge/fuji-8dac36611b90/card-0-t10-colour.webp new file mode 100644 index 00000000..b8c96a53 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t10-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t10-geometry.webp b/public/ridge/fuji-8dac36611b90/card-0-t10-geometry.webp new file mode 100644 index 00000000..b582015e Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t10-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t11-colour.webp b/public/ridge/fuji-8dac36611b90/card-0-t11-colour.webp new file mode 100644 index 00000000..e136956b Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t11-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t11-geometry.webp b/public/ridge/fuji-8dac36611b90/card-0-t11-geometry.webp new file mode 100644 index 00000000..1477d7b7 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t11-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t12-colour.webp b/public/ridge/fuji-8dac36611b90/card-0-t12-colour.webp new file mode 100644 index 00000000..3709ec91 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t12-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t12-geometry.webp b/public/ridge/fuji-8dac36611b90/card-0-t12-geometry.webp new file mode 100644 index 00000000..5882ff8a Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t12-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t13-colour.webp b/public/ridge/fuji-8dac36611b90/card-0-t13-colour.webp new file mode 100644 index 00000000..1b56889c Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t13-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t13-geometry.webp b/public/ridge/fuji-8dac36611b90/card-0-t13-geometry.webp new file mode 100644 index 00000000..9b6a84d6 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t13-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t14-colour.webp b/public/ridge/fuji-8dac36611b90/card-0-t14-colour.webp new file mode 100644 index 00000000..02970394 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t14-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t14-geometry.webp b/public/ridge/fuji-8dac36611b90/card-0-t14-geometry.webp new file mode 100644 index 00000000..66116abc Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t14-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t15-colour.webp b/public/ridge/fuji-8dac36611b90/card-0-t15-colour.webp new file mode 100644 index 00000000..ac8197d3 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t15-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t15-geometry.webp b/public/ridge/fuji-8dac36611b90/card-0-t15-geometry.webp new file mode 100644 index 00000000..94cbddc4 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t15-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t16-colour.webp b/public/ridge/fuji-8dac36611b90/card-0-t16-colour.webp new file mode 100644 index 00000000..6cddc44d Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t16-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t16-geometry.webp b/public/ridge/fuji-8dac36611b90/card-0-t16-geometry.webp new file mode 100644 index 00000000..fd6a70a7 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t16-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t17-colour.webp b/public/ridge/fuji-8dac36611b90/card-0-t17-colour.webp new file mode 100644 index 00000000..b7163771 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t17-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t17-geometry.webp b/public/ridge/fuji-8dac36611b90/card-0-t17-geometry.webp new file mode 100644 index 00000000..15a8961b Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t17-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t18-colour.webp b/public/ridge/fuji-8dac36611b90/card-0-t18-colour.webp new file mode 100644 index 00000000..74024849 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t18-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t18-geometry.webp b/public/ridge/fuji-8dac36611b90/card-0-t18-geometry.webp new file mode 100644 index 00000000..b95f4c55 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t18-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t19-colour.webp b/public/ridge/fuji-8dac36611b90/card-0-t19-colour.webp new file mode 100644 index 00000000..d1173387 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t19-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t19-geometry.webp b/public/ridge/fuji-8dac36611b90/card-0-t19-geometry.webp new file mode 100644 index 00000000..a3fd26cd Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t19-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t20-colour.webp b/public/ridge/fuji-8dac36611b90/card-0-t20-colour.webp new file mode 100644 index 00000000..8f8d05cc Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t20-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t20-geometry.webp b/public/ridge/fuji-8dac36611b90/card-0-t20-geometry.webp new file mode 100644 index 00000000..8ddc8ae7 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t20-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t21-colour.webp b/public/ridge/fuji-8dac36611b90/card-0-t21-colour.webp new file mode 100644 index 00000000..5501eba7 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t21-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t21-geometry.webp b/public/ridge/fuji-8dac36611b90/card-0-t21-geometry.webp new file mode 100644 index 00000000..8ede69d8 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t21-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t22-colour.webp b/public/ridge/fuji-8dac36611b90/card-0-t22-colour.webp new file mode 100644 index 00000000..49aa6f23 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t22-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t22-geometry.webp b/public/ridge/fuji-8dac36611b90/card-0-t22-geometry.webp new file mode 100644 index 00000000..b508c9ad Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t22-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t23-colour.webp b/public/ridge/fuji-8dac36611b90/card-0-t23-colour.webp new file mode 100644 index 00000000..b0df140c Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t23-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t23-geometry.webp b/public/ridge/fuji-8dac36611b90/card-0-t23-geometry.webp new file mode 100644 index 00000000..73366412 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t23-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t24-colour.webp b/public/ridge/fuji-8dac36611b90/card-0-t24-colour.webp new file mode 100644 index 00000000..f081f2f7 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t24-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t24-geometry.webp b/public/ridge/fuji-8dac36611b90/card-0-t24-geometry.webp new file mode 100644 index 00000000..7a9dbbb1 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t24-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t25-colour.webp b/public/ridge/fuji-8dac36611b90/card-0-t25-colour.webp new file mode 100644 index 00000000..8d3e8fd3 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t25-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t25-geometry.webp b/public/ridge/fuji-8dac36611b90/card-0-t25-geometry.webp new file mode 100644 index 00000000..6237b3f4 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t25-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t26-colour.webp b/public/ridge/fuji-8dac36611b90/card-0-t26-colour.webp new file mode 100644 index 00000000..950659ac Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t26-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t26-geometry.webp b/public/ridge/fuji-8dac36611b90/card-0-t26-geometry.webp new file mode 100644 index 00000000..cb5b5b89 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t26-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t27-colour.webp b/public/ridge/fuji-8dac36611b90/card-0-t27-colour.webp new file mode 100644 index 00000000..b9830b65 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t27-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t27-geometry.webp b/public/ridge/fuji-8dac36611b90/card-0-t27-geometry.webp new file mode 100644 index 00000000..67f996c8 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t27-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t28-colour.webp b/public/ridge/fuji-8dac36611b90/card-0-t28-colour.webp new file mode 100644 index 00000000..dabb1d3d Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t28-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t28-geometry.webp b/public/ridge/fuji-8dac36611b90/card-0-t28-geometry.webp new file mode 100644 index 00000000..349ec1b7 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t28-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t29-colour.webp b/public/ridge/fuji-8dac36611b90/card-0-t29-colour.webp new file mode 100644 index 00000000..5aca96e5 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t29-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t29-geometry.webp b/public/ridge/fuji-8dac36611b90/card-0-t29-geometry.webp new file mode 100644 index 00000000..8983c054 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t29-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t30-colour.webp b/public/ridge/fuji-8dac36611b90/card-0-t30-colour.webp new file mode 100644 index 00000000..56a7f529 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t30-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t30-geometry.webp b/public/ridge/fuji-8dac36611b90/card-0-t30-geometry.webp new file mode 100644 index 00000000..a5dc0beb Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t30-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t31-colour.webp b/public/ridge/fuji-8dac36611b90/card-0-t31-colour.webp new file mode 100644 index 00000000..598bcc93 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t31-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-0-t31-geometry.webp b/public/ridge/fuji-8dac36611b90/card-0-t31-geometry.webp new file mode 100644 index 00000000..0fd49b3b Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-0-t31-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t00-colour.webp b/public/ridge/fuji-8dac36611b90/card-1-t00-colour.webp new file mode 100644 index 00000000..135a10b0 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t00-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t00-geometry.webp b/public/ridge/fuji-8dac36611b90/card-1-t00-geometry.webp new file mode 100644 index 00000000..db4c2d7a Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t00-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t01-colour.webp b/public/ridge/fuji-8dac36611b90/card-1-t01-colour.webp new file mode 100644 index 00000000..6e64e114 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t01-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t01-geometry.webp b/public/ridge/fuji-8dac36611b90/card-1-t01-geometry.webp new file mode 100644 index 00000000..4ff81cb8 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t01-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t02-colour.webp b/public/ridge/fuji-8dac36611b90/card-1-t02-colour.webp new file mode 100644 index 00000000..97991fde Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t02-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t02-geometry.webp b/public/ridge/fuji-8dac36611b90/card-1-t02-geometry.webp new file mode 100644 index 00000000..16ff75d3 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t02-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t03-colour.webp b/public/ridge/fuji-8dac36611b90/card-1-t03-colour.webp new file mode 100644 index 00000000..1918f131 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t03-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t03-geometry.webp b/public/ridge/fuji-8dac36611b90/card-1-t03-geometry.webp new file mode 100644 index 00000000..b8a2f602 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t03-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t04-colour.webp b/public/ridge/fuji-8dac36611b90/card-1-t04-colour.webp new file mode 100644 index 00000000..fbebfbc8 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t04-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t04-geometry.webp b/public/ridge/fuji-8dac36611b90/card-1-t04-geometry.webp new file mode 100644 index 00000000..6f55ce22 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t04-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t05-colour.webp b/public/ridge/fuji-8dac36611b90/card-1-t05-colour.webp new file mode 100644 index 00000000..c8086215 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t05-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t05-geometry.webp b/public/ridge/fuji-8dac36611b90/card-1-t05-geometry.webp new file mode 100644 index 00000000..a36cda8c Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t05-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t06-colour.webp b/public/ridge/fuji-8dac36611b90/card-1-t06-colour.webp new file mode 100644 index 00000000..ad979fab Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t06-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t06-geometry.webp b/public/ridge/fuji-8dac36611b90/card-1-t06-geometry.webp new file mode 100644 index 00000000..13c89c02 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t06-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t07-colour.webp b/public/ridge/fuji-8dac36611b90/card-1-t07-colour.webp new file mode 100644 index 00000000..d7ae25aa Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t07-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t07-geometry.webp b/public/ridge/fuji-8dac36611b90/card-1-t07-geometry.webp new file mode 100644 index 00000000..4b06f6da Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t07-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t08-colour.webp b/public/ridge/fuji-8dac36611b90/card-1-t08-colour.webp new file mode 100644 index 00000000..5b0b5ecd Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t08-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t08-geometry.webp b/public/ridge/fuji-8dac36611b90/card-1-t08-geometry.webp new file mode 100644 index 00000000..e6ee7d76 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t08-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t09-colour.webp b/public/ridge/fuji-8dac36611b90/card-1-t09-colour.webp new file mode 100644 index 00000000..9203eefc Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t09-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t09-geometry.webp b/public/ridge/fuji-8dac36611b90/card-1-t09-geometry.webp new file mode 100644 index 00000000..01203777 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t09-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t10-colour.webp b/public/ridge/fuji-8dac36611b90/card-1-t10-colour.webp new file mode 100644 index 00000000..f423ffd7 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t10-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t10-geometry.webp b/public/ridge/fuji-8dac36611b90/card-1-t10-geometry.webp new file mode 100644 index 00000000..a08ae5b7 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t10-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t11-colour.webp b/public/ridge/fuji-8dac36611b90/card-1-t11-colour.webp new file mode 100644 index 00000000..548c3dd2 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t11-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t11-geometry.webp b/public/ridge/fuji-8dac36611b90/card-1-t11-geometry.webp new file mode 100644 index 00000000..dd2e577f Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t11-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t12-colour.webp b/public/ridge/fuji-8dac36611b90/card-1-t12-colour.webp new file mode 100644 index 00000000..3c822749 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t12-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t12-geometry.webp b/public/ridge/fuji-8dac36611b90/card-1-t12-geometry.webp new file mode 100644 index 00000000..4160e4e8 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t12-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t13-colour.webp b/public/ridge/fuji-8dac36611b90/card-1-t13-colour.webp new file mode 100644 index 00000000..184fbc95 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t13-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t13-geometry.webp b/public/ridge/fuji-8dac36611b90/card-1-t13-geometry.webp new file mode 100644 index 00000000..72d7dc9d Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t13-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t14-colour.webp b/public/ridge/fuji-8dac36611b90/card-1-t14-colour.webp new file mode 100644 index 00000000..7c4337a7 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t14-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t14-geometry.webp b/public/ridge/fuji-8dac36611b90/card-1-t14-geometry.webp new file mode 100644 index 00000000..db5c32d8 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t14-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t15-colour.webp b/public/ridge/fuji-8dac36611b90/card-1-t15-colour.webp new file mode 100644 index 00000000..43b85978 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t15-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t15-geometry.webp b/public/ridge/fuji-8dac36611b90/card-1-t15-geometry.webp new file mode 100644 index 00000000..6c122045 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t15-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t16-colour.webp b/public/ridge/fuji-8dac36611b90/card-1-t16-colour.webp new file mode 100644 index 00000000..6218b7ec Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t16-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t16-geometry.webp b/public/ridge/fuji-8dac36611b90/card-1-t16-geometry.webp new file mode 100644 index 00000000..c3db236b Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t16-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t17-colour.webp b/public/ridge/fuji-8dac36611b90/card-1-t17-colour.webp new file mode 100644 index 00000000..52f6fc8e Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t17-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t17-geometry.webp b/public/ridge/fuji-8dac36611b90/card-1-t17-geometry.webp new file mode 100644 index 00000000..a447c805 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t17-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t18-colour.webp b/public/ridge/fuji-8dac36611b90/card-1-t18-colour.webp new file mode 100644 index 00000000..d72c9a9f Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t18-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t18-geometry.webp b/public/ridge/fuji-8dac36611b90/card-1-t18-geometry.webp new file mode 100644 index 00000000..7267267d Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t18-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t19-colour.webp b/public/ridge/fuji-8dac36611b90/card-1-t19-colour.webp new file mode 100644 index 00000000..390021be Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t19-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t19-geometry.webp b/public/ridge/fuji-8dac36611b90/card-1-t19-geometry.webp new file mode 100644 index 00000000..e06925d1 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t19-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t20-colour.webp b/public/ridge/fuji-8dac36611b90/card-1-t20-colour.webp new file mode 100644 index 00000000..1a2c4fd5 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t20-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t20-geometry.webp b/public/ridge/fuji-8dac36611b90/card-1-t20-geometry.webp new file mode 100644 index 00000000..bf03cd35 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t20-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t21-colour.webp b/public/ridge/fuji-8dac36611b90/card-1-t21-colour.webp new file mode 100644 index 00000000..1b93a9dc Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t21-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t21-geometry.webp b/public/ridge/fuji-8dac36611b90/card-1-t21-geometry.webp new file mode 100644 index 00000000..03da01dc Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t21-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t22-colour.webp b/public/ridge/fuji-8dac36611b90/card-1-t22-colour.webp new file mode 100644 index 00000000..699c2c53 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t22-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t22-geometry.webp b/public/ridge/fuji-8dac36611b90/card-1-t22-geometry.webp new file mode 100644 index 00000000..41c9fd99 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t22-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t23-colour.webp b/public/ridge/fuji-8dac36611b90/card-1-t23-colour.webp new file mode 100644 index 00000000..16c4ef24 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t23-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t23-geometry.webp b/public/ridge/fuji-8dac36611b90/card-1-t23-geometry.webp new file mode 100644 index 00000000..8ce25409 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t23-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t24-colour.webp b/public/ridge/fuji-8dac36611b90/card-1-t24-colour.webp new file mode 100644 index 00000000..f1bec22d Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t24-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t24-geometry.webp b/public/ridge/fuji-8dac36611b90/card-1-t24-geometry.webp new file mode 100644 index 00000000..b4daf9ad Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t24-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t25-colour.webp b/public/ridge/fuji-8dac36611b90/card-1-t25-colour.webp new file mode 100644 index 00000000..3053a4fb Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t25-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t25-geometry.webp b/public/ridge/fuji-8dac36611b90/card-1-t25-geometry.webp new file mode 100644 index 00000000..06a79501 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t25-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t26-colour.webp b/public/ridge/fuji-8dac36611b90/card-1-t26-colour.webp new file mode 100644 index 00000000..871a729d Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t26-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t26-geometry.webp b/public/ridge/fuji-8dac36611b90/card-1-t26-geometry.webp new file mode 100644 index 00000000..e98e34aa Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t26-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t27-colour.webp b/public/ridge/fuji-8dac36611b90/card-1-t27-colour.webp new file mode 100644 index 00000000..ab26b8ad Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t27-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t27-geometry.webp b/public/ridge/fuji-8dac36611b90/card-1-t27-geometry.webp new file mode 100644 index 00000000..5bf2dc6c Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t27-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t28-colour.webp b/public/ridge/fuji-8dac36611b90/card-1-t28-colour.webp new file mode 100644 index 00000000..85826778 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t28-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t28-geometry.webp b/public/ridge/fuji-8dac36611b90/card-1-t28-geometry.webp new file mode 100644 index 00000000..acae5476 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t28-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t29-colour.webp b/public/ridge/fuji-8dac36611b90/card-1-t29-colour.webp new file mode 100644 index 00000000..b9b05ce5 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t29-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t29-geometry.webp b/public/ridge/fuji-8dac36611b90/card-1-t29-geometry.webp new file mode 100644 index 00000000..14b61be6 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t29-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t30-colour.webp b/public/ridge/fuji-8dac36611b90/card-1-t30-colour.webp new file mode 100644 index 00000000..d38d1838 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t30-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t30-geometry.webp b/public/ridge/fuji-8dac36611b90/card-1-t30-geometry.webp new file mode 100644 index 00000000..a707c046 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t30-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t31-colour.webp b/public/ridge/fuji-8dac36611b90/card-1-t31-colour.webp new file mode 100644 index 00000000..cc888dc0 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t31-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-1-t31-geometry.webp b/public/ridge/fuji-8dac36611b90/card-1-t31-geometry.webp new file mode 100644 index 00000000..c64b6664 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-1-t31-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t00-colour.webp b/public/ridge/fuji-8dac36611b90/card-2-t00-colour.webp new file mode 100644 index 00000000..f0e5f75d Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t00-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t00-geometry.webp b/public/ridge/fuji-8dac36611b90/card-2-t00-geometry.webp new file mode 100644 index 00000000..45e08f46 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t00-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t01-colour.webp b/public/ridge/fuji-8dac36611b90/card-2-t01-colour.webp new file mode 100644 index 00000000..7d8bd71a Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t01-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t01-geometry.webp b/public/ridge/fuji-8dac36611b90/card-2-t01-geometry.webp new file mode 100644 index 00000000..1a2bf22c Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t01-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t02-colour.webp b/public/ridge/fuji-8dac36611b90/card-2-t02-colour.webp new file mode 100644 index 00000000..843153d0 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t02-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t02-geometry.webp b/public/ridge/fuji-8dac36611b90/card-2-t02-geometry.webp new file mode 100644 index 00000000..46836d85 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t02-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t03-colour.webp b/public/ridge/fuji-8dac36611b90/card-2-t03-colour.webp new file mode 100644 index 00000000..60d8dbb5 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t03-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t03-geometry.webp b/public/ridge/fuji-8dac36611b90/card-2-t03-geometry.webp new file mode 100644 index 00000000..03abdb9a Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t03-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t04-colour.webp b/public/ridge/fuji-8dac36611b90/card-2-t04-colour.webp new file mode 100644 index 00000000..9f4a0707 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t04-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t04-geometry.webp b/public/ridge/fuji-8dac36611b90/card-2-t04-geometry.webp new file mode 100644 index 00000000..077851e9 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t04-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t05-colour.webp b/public/ridge/fuji-8dac36611b90/card-2-t05-colour.webp new file mode 100644 index 00000000..253733c3 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t05-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t05-geometry.webp b/public/ridge/fuji-8dac36611b90/card-2-t05-geometry.webp new file mode 100644 index 00000000..2d1981b4 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t05-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t06-colour.webp b/public/ridge/fuji-8dac36611b90/card-2-t06-colour.webp new file mode 100644 index 00000000..8167d70a Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t06-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t06-geometry.webp b/public/ridge/fuji-8dac36611b90/card-2-t06-geometry.webp new file mode 100644 index 00000000..c78b28ce Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t06-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t07-colour.webp b/public/ridge/fuji-8dac36611b90/card-2-t07-colour.webp new file mode 100644 index 00000000..f6b904e0 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t07-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t07-geometry.webp b/public/ridge/fuji-8dac36611b90/card-2-t07-geometry.webp new file mode 100644 index 00000000..15378b66 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t07-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t08-colour.webp b/public/ridge/fuji-8dac36611b90/card-2-t08-colour.webp new file mode 100644 index 00000000..1e6c6530 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t08-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t08-geometry.webp b/public/ridge/fuji-8dac36611b90/card-2-t08-geometry.webp new file mode 100644 index 00000000..913101cb Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t08-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t09-colour.webp b/public/ridge/fuji-8dac36611b90/card-2-t09-colour.webp new file mode 100644 index 00000000..0f1ce310 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t09-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t09-geometry.webp b/public/ridge/fuji-8dac36611b90/card-2-t09-geometry.webp new file mode 100644 index 00000000..87c55475 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t09-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t10-colour.webp b/public/ridge/fuji-8dac36611b90/card-2-t10-colour.webp new file mode 100644 index 00000000..4a180866 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t10-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t10-geometry.webp b/public/ridge/fuji-8dac36611b90/card-2-t10-geometry.webp new file mode 100644 index 00000000..41b6f73e Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t10-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t11-colour.webp b/public/ridge/fuji-8dac36611b90/card-2-t11-colour.webp new file mode 100644 index 00000000..b355c20c Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t11-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t11-geometry.webp b/public/ridge/fuji-8dac36611b90/card-2-t11-geometry.webp new file mode 100644 index 00000000..964fd6f8 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t11-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t12-colour.webp b/public/ridge/fuji-8dac36611b90/card-2-t12-colour.webp new file mode 100644 index 00000000..0b3766e4 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t12-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t12-geometry.webp b/public/ridge/fuji-8dac36611b90/card-2-t12-geometry.webp new file mode 100644 index 00000000..84c139d8 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t12-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t13-colour.webp b/public/ridge/fuji-8dac36611b90/card-2-t13-colour.webp new file mode 100644 index 00000000..fdd9b0cd Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t13-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t13-geometry.webp b/public/ridge/fuji-8dac36611b90/card-2-t13-geometry.webp new file mode 100644 index 00000000..3e446e23 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t13-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t14-colour.webp b/public/ridge/fuji-8dac36611b90/card-2-t14-colour.webp new file mode 100644 index 00000000..4a250c52 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t14-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t14-geometry.webp b/public/ridge/fuji-8dac36611b90/card-2-t14-geometry.webp new file mode 100644 index 00000000..73247286 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t14-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t15-colour.webp b/public/ridge/fuji-8dac36611b90/card-2-t15-colour.webp new file mode 100644 index 00000000..e3b1f40d Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t15-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t15-geometry.webp b/public/ridge/fuji-8dac36611b90/card-2-t15-geometry.webp new file mode 100644 index 00000000..d760e140 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t15-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t16-colour.webp b/public/ridge/fuji-8dac36611b90/card-2-t16-colour.webp new file mode 100644 index 00000000..5c9d1233 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t16-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t16-geometry.webp b/public/ridge/fuji-8dac36611b90/card-2-t16-geometry.webp new file mode 100644 index 00000000..2a020593 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t16-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t17-colour.webp b/public/ridge/fuji-8dac36611b90/card-2-t17-colour.webp new file mode 100644 index 00000000..1d00ef23 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t17-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t17-geometry.webp b/public/ridge/fuji-8dac36611b90/card-2-t17-geometry.webp new file mode 100644 index 00000000..411b9793 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t17-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t18-colour.webp b/public/ridge/fuji-8dac36611b90/card-2-t18-colour.webp new file mode 100644 index 00000000..e28c3383 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t18-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t18-geometry.webp b/public/ridge/fuji-8dac36611b90/card-2-t18-geometry.webp new file mode 100644 index 00000000..c61774ee Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t18-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t19-colour.webp b/public/ridge/fuji-8dac36611b90/card-2-t19-colour.webp new file mode 100644 index 00000000..223bc9c1 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t19-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t19-geometry.webp b/public/ridge/fuji-8dac36611b90/card-2-t19-geometry.webp new file mode 100644 index 00000000..dc62e04e Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t19-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t20-colour.webp b/public/ridge/fuji-8dac36611b90/card-2-t20-colour.webp new file mode 100644 index 00000000..6003dadb Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t20-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t20-geometry.webp b/public/ridge/fuji-8dac36611b90/card-2-t20-geometry.webp new file mode 100644 index 00000000..a646cacc Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t20-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t21-colour.webp b/public/ridge/fuji-8dac36611b90/card-2-t21-colour.webp new file mode 100644 index 00000000..79e3d279 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t21-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t21-geometry.webp b/public/ridge/fuji-8dac36611b90/card-2-t21-geometry.webp new file mode 100644 index 00000000..3cba62ce Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t21-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t22-colour.webp b/public/ridge/fuji-8dac36611b90/card-2-t22-colour.webp new file mode 100644 index 00000000..26cb1f74 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t22-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t22-geometry.webp b/public/ridge/fuji-8dac36611b90/card-2-t22-geometry.webp new file mode 100644 index 00000000..84dcf595 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t22-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t23-colour.webp b/public/ridge/fuji-8dac36611b90/card-2-t23-colour.webp new file mode 100644 index 00000000..e6db6a47 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t23-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t23-geometry.webp b/public/ridge/fuji-8dac36611b90/card-2-t23-geometry.webp new file mode 100644 index 00000000..fd0052c7 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t23-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t24-colour.webp b/public/ridge/fuji-8dac36611b90/card-2-t24-colour.webp new file mode 100644 index 00000000..663c44d4 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t24-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t24-geometry.webp b/public/ridge/fuji-8dac36611b90/card-2-t24-geometry.webp new file mode 100644 index 00000000..23d3264d Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t24-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t25-colour.webp b/public/ridge/fuji-8dac36611b90/card-2-t25-colour.webp new file mode 100644 index 00000000..ec455997 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t25-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t25-geometry.webp b/public/ridge/fuji-8dac36611b90/card-2-t25-geometry.webp new file mode 100644 index 00000000..98b1a692 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t25-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t26-colour.webp b/public/ridge/fuji-8dac36611b90/card-2-t26-colour.webp new file mode 100644 index 00000000..9d69adb5 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t26-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t26-geometry.webp b/public/ridge/fuji-8dac36611b90/card-2-t26-geometry.webp new file mode 100644 index 00000000..82bb08c1 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t26-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t27-colour.webp b/public/ridge/fuji-8dac36611b90/card-2-t27-colour.webp new file mode 100644 index 00000000..6d1f461c Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t27-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t27-geometry.webp b/public/ridge/fuji-8dac36611b90/card-2-t27-geometry.webp new file mode 100644 index 00000000..78bff6b1 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t27-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t28-colour.webp b/public/ridge/fuji-8dac36611b90/card-2-t28-colour.webp new file mode 100644 index 00000000..cbc2953f Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t28-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t28-geometry.webp b/public/ridge/fuji-8dac36611b90/card-2-t28-geometry.webp new file mode 100644 index 00000000..c22aee68 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t28-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t29-colour.webp b/public/ridge/fuji-8dac36611b90/card-2-t29-colour.webp new file mode 100644 index 00000000..458a13cb Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t29-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t29-geometry.webp b/public/ridge/fuji-8dac36611b90/card-2-t29-geometry.webp new file mode 100644 index 00000000..cb6f1fd6 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t29-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t30-colour.webp b/public/ridge/fuji-8dac36611b90/card-2-t30-colour.webp new file mode 100644 index 00000000..08c84bd9 Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t30-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t30-geometry.webp b/public/ridge/fuji-8dac36611b90/card-2-t30-geometry.webp new file mode 100644 index 00000000..d87ffe2d Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t30-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t31-colour.webp b/public/ridge/fuji-8dac36611b90/card-2-t31-colour.webp new file mode 100644 index 00000000..7c8f34dc Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t31-colour.webp differ diff --git a/public/ridge/fuji-8dac36611b90/card-2-t31-geometry.webp b/public/ridge/fuji-8dac36611b90/card-2-t31-geometry.webp new file mode 100644 index 00000000..ec121bab Binary files /dev/null and b/public/ridge/fuji-8dac36611b90/card-2-t31-geometry.webp differ diff --git a/public/ridge/fuji-8dac36611b90/manifest.json b/public/ridge/fuji-8dac36611b90/manifest.json new file mode 100644 index 00000000..3d40b7b8 --- /dev/null +++ b/public/ridge/fuji-8dac36611b90/manifest.json @@ -0,0 +1,1376 @@ +{ + "schema": 3, + "baker_version": 7, + "bake_id": "8dac36611b90", + "place": { + "id": "fuji", + "name": "Fuji from Shiraito Falls", + "lat": 35.312467222222494, + "lon": 138.587223194445, + "altitude_km": 0.486932967116363, + "eye_m": 488.53296711636307, + "tz": "Asia/Tokyo" + }, + "view": { + "look_az_deg": 67.161576536126, + "plane_h": 600, + "px_per_deg_h": 17.77777777777778, + "px_per_deg_v": 26.57953416522506, + "exaggeration": 1.4950987967939096, + "horizon_row": 377.3786586364885, + "sky_row": 24.0, + "near_row": 396.0, + "ring_w": 6400, + "tile_w": 200, + "tiles": 32, + "apron": 2 + }, + "curvature": { + "r_earth_m": 6371000.0, + "k_ref": 0.13 + }, + "encoding": { + "log_d_min": 6.214608098422191, + "log_d_max": 11.00475592466117, + "normal": "rt8" + }, + "camera": { + "r_max_m": 95.8, + "r_max_forward_m": 198.4 + }, + "cards": [ + { + "near_m": null, + "far_m": 1583.253869396531 + }, + { + "near_m": 1583.253869396531, + "far_m": 15874.92439468983 + }, + { + "near_m": 15874.92439468983, + "far_m": null + } + ], + "tiles": [ + [ + { + "top": 301, + "h": 299, + "distance_m": 1165.49267578125, + "colour": { + "file": "card-0-t00-colour.webp", + "bytes": 550 + }, + "geometry": { + "file": "card-0-t00-geometry.webp", + "bytes": 1446 + } + }, + { + "top": 283, + "h": 317, + "distance_m": 3045.256103515625, + "colour": { + "file": "card-1-t00-colour.webp", + "bytes": 808 + }, + "geometry": { + "file": "card-1-t00-geometry.webp", + "bytes": 3490 + } + }, + { + "top": 313, + "h": 287, + "distance_m": 18859.54296875, + "colour": { + "file": "card-2-t00-colour.webp", + "bytes": 864 + }, + "geometry": { + "file": "card-2-t00-geometry.webp", + "bytes": 4160 + } + } + ], + [ + { + "top": 291, + "h": 309, + "distance_m": 859.9998779296875, + "colour": { + "file": "card-0-t01-colour.webp", + "bytes": 650 + }, + "geometry": { + "file": "card-0-t01-geometry.webp", + "bytes": 3810 + } + }, + { + "top": 284, + "h": 316, + "distance_m": 6953.26611328125, + "colour": { + "file": "card-1-t01-colour.webp", + "bytes": 716 + }, + "geometry": { + "file": "card-1-t01-geometry.webp", + "bytes": 4140 + } + }, + { + "top": 292, + "h": 308, + "distance_m": 23120.55078125, + "colour": { + "file": "card-2-t01-colour.webp", + "bytes": 790 + }, + "geometry": { + "file": "card-2-t01-geometry.webp", + "bytes": 3384 + } + } + ], + [ + { + "top": 284, + "h": 316, + "distance_m": 676.6893920898438, + "colour": { + "file": "card-0-t02-colour.webp", + "bytes": 672 + }, + "geometry": { + "file": "card-0-t02-geometry.webp", + "bytes": 4652 + } + }, + { + "top": 260, + "h": 340, + "distance_m": 6780.00048828125, + "colour": { + "file": "card-1-t02-colour.webp", + "bytes": 834 + }, + "geometry": { + "file": "card-1-t02-geometry.webp", + "bytes": 7466 + } + }, + { + "top": 287, + "h": 313, + "distance_m": 15794.0107421875, + "colour": { + "file": "card-2-t02-colour.webp", + "bytes": 518 + }, + "geometry": { + "file": "card-2-t02-geometry.webp", + "bytes": 376 + } + } + ], + [ + { + "top": 271, + "h": 329, + "distance_m": 533.1802978515625, + "colour": { + "file": "card-0-t03-colour.webp", + "bytes": 744 + }, + "geometry": { + "file": "card-0-t03-geometry.webp", + "bytes": 6446 + } + }, + { + "top": 219, + "h": 381, + "distance_m": 7060.0029296875, + "colour": { + "file": "card-1-t03-colour.webp", + "bytes": 1026 + }, + "geometry": { + "file": "card-1-t03-geometry.webp", + "bytes": 16660 + } + }, + { + "top": 262, + "h": 338, + "distance_m": 15731.759765625, + "colour": { + "file": "card-2-t03-colour.webp", + "bytes": 454 + }, + "geometry": { + "file": "card-2-t03-geometry.webp", + "bytes": 176 + } + } + ], + [ + { + "top": 273, + "h": 327, + "distance_m": 733.8682250976562, + "colour": { + "file": "card-0-t04-colour.webp", + "bytes": 598 + }, + "geometry": { + "file": "card-0-t04-geometry.webp", + "bytes": 7574 + } + }, + { + "top": 143, + "h": 457, + "distance_m": 7140.001953125, + "colour": { + "file": "card-1-t04-colour.webp", + "bytes": 1650 + }, + "geometry": { + "file": "card-1-t04-geometry.webp", + "bytes": 33048 + } + }, + { + "top": 194, + "h": 406, + "distance_m": 15731.759765625, + "colour": { + "file": "card-2-t04-colour.webp", + "bytes": 780 + }, + "geometry": { + "file": "card-2-t04-geometry.webp", + "bytes": 168 + } + } + ], + [ + { + "top": 291, + "h": 309, + "distance_m": 620.0, + "colour": { + "file": "card-0-t05-colour.webp", + "bytes": 834 + }, + "geometry": { + "file": "card-0-t05-geometry.webp", + "bytes": 8660 + } + }, + { + "top": 24, + "h": 576, + "distance_m": 9899.9970703125, + "colour": { + "file": "card-1-t05-colour.webp", + "bytes": 3946 + }, + "geometry": { + "file": "card-1-t05-geometry.webp", + "bytes": 56096 + } + }, + { + "top": 131, + "h": 469, + "distance_m": 15731.759765625, + "colour": { + "file": "card-2-t05-colour.webp", + "bytes": 514 + }, + "geometry": { + "file": "card-2-t05-geometry.webp", + "bytes": 176 + } + } + ], + [ + { + "top": 305, + "h": 295, + "distance_m": 671.1244506835938, + "colour": { + "file": "card-0-t06-colour.webp", + "bytes": 1014 + }, + "geometry": { + "file": "card-0-t06-geometry.webp", + "bytes": 10652 + } + }, + { + "top": 25, + "h": 575, + "distance_m": 9121.8095703125, + "colour": { + "file": "card-1-t06-colour.webp", + "bytes": 2732 + }, + "geometry": { + "file": "card-1-t06-geometry.webp", + "bytes": 50750 + } + }, + { + "top": 135, + "h": 465, + "distance_m": 15326.396484375, + "colour": { + "file": "card-2-t06-colour.webp", + "bytes": 500 + }, + "geometry": { + "file": "card-2-t06-geometry.webp", + "bytes": 376 + } + } + ], + [ + { + "top": 329, + "h": 271, + "distance_m": 842.284423828125, + "colour": { + "file": "card-0-t07-colour.webp", + "bytes": 632 + }, + "geometry": { + "file": "card-0-t07-geometry.webp", + "bytes": 7864 + } + }, + { + "top": 167, + "h": 433, + "distance_m": 5535.31689453125, + "colour": { + "file": "card-1-t07-colour.webp", + "bytes": 1508 + }, + "geometry": { + "file": "card-1-t07-geometry.webp", + "bytes": 32304 + } + }, + { + "top": 184, + "h": 416, + "distance_m": 14936.1650390625, + "colour": { + "file": "card-2-t07-colour.webp", + "bytes": 814 + }, + "geometry": { + "file": "card-2-t07-geometry.webp", + "bytes": 358 + } + } + ], + [ + { + "top": 347, + "h": 253, + "distance_m": 822.8244018554688, + "colour": { + "file": "card-0-t08-colour.webp", + "bytes": 656 + }, + "geometry": { + "file": "card-0-t08-geometry.webp", + "bytes": 5594 + } + }, + { + "top": 237, + "h": 363, + "distance_m": 4411.3466796875, + "colour": { + "file": "card-1-t08-colour.webp", + "bytes": 1054 + }, + "geometry": { + "file": "card-1-t08-geometry.webp", + "bytes": 22196 + } + }, + { + "top": 262, + "h": 338, + "distance_m": 14903.5107421875, + "colour": { + "file": "card-2-t08-colour.webp", + "bytes": 564 + }, + "geometry": { + "file": "card-2-t08-geometry.webp", + "bytes": 282 + } + } + ], + [ + { + "top": 348, + "h": 252, + "distance_m": 761.4862060546875, + "colour": { + "file": "card-0-t09-colour.webp", + "bytes": 726 + }, + "geometry": { + "file": "card-0-t09-geometry.webp", + "bytes": 8744 + } + }, + { + "top": 287, + "h": 313, + "distance_m": 4339.99951171875, + "colour": { + "file": "card-1-t09-colour.webp", + "bytes": 986 + }, + "geometry": { + "file": "card-1-t09-geometry.webp", + "bytes": 16712 + } + }, + { + "top": 305, + "h": 295, + "distance_m": 19806.669921875, + "colour": { + "file": "card-2-t09-colour.webp", + "bytes": 582 + }, + "geometry": { + "file": "card-2-t09-geometry.webp", + "bytes": 1658 + } + } + ], + [ + { + "top": 352, + "h": 248, + "distance_m": 500.0, + "colour": { + "file": "card-0-t10-colour.webp", + "bytes": 754 + }, + "geometry": { + "file": "card-0-t10-geometry.webp", + "bytes": 11398 + } + }, + { + "top": 326, + "h": 274, + "distance_m": 4207.16943359375, + "colour": { + "file": "card-1-t10-colour.webp", + "bytes": 756 + }, + "geometry": { + "file": "card-1-t10-geometry.webp", + "bytes": 10954 + } + }, + { + "top": 304, + "h": 296, + "distance_m": 19358.07421875, + "colour": { + "file": "card-2-t10-colour.webp", + "bytes": 1618 + }, + "geometry": { + "file": "card-2-t10-geometry.webp", + "bytes": 10682 + } + } + ], + [ + { + "top": 347, + "h": 253, + "distance_m": 527.2754516601562, + "colour": { + "file": "card-0-t11-colour.webp", + "bytes": 1012 + }, + "geometry": { + "file": "card-0-t11-geometry.webp", + "bytes": 8924 + } + }, + { + "top": 358, + "h": 242, + "distance_m": 4933.00732421875, + "colour": { + "file": "card-1-t11-colour.webp", + "bytes": 478 + }, + "geometry": { + "file": "card-1-t11-geometry.webp", + "bytes": 5326 + } + }, + { + "top": 342, + "h": 258, + "distance_m": 19438.56640625, + "colour": { + "file": "card-2-t11-colour.webp", + "bytes": 770 + }, + "geometry": { + "file": "card-2-t11-geometry.webp", + "bytes": 4296 + } + } + ], + [ + { + "top": 352, + "h": 248, + "distance_m": 520.909423828125, + "colour": { + "file": "card-0-t12-colour.webp", + "bytes": 998 + }, + "geometry": { + "file": "card-0-t12-geometry.webp", + "bytes": 7092 + } + }, + { + "top": 388, + "h": 212, + "distance_m": 1597.173583984375, + "colour": { + "file": "card-1-t12-colour.webp", + "bytes": 458 + }, + "geometry": { + "file": "card-1-t12-geometry.webp", + "bytes": 4096 + } + }, + { + "top": 370, + "h": 230, + "distance_m": 43464.87890625, + "colour": { + "file": "card-2-t12-colour.webp", + "bytes": 834 + }, + "geometry": { + "file": "card-2-t12-geometry.webp", + "bytes": 8064 + } + } + ], + [ + { + "top": 384, + "h": 216, + "distance_m": 641.1549682617188, + "colour": { + "file": "card-0-t13-colour.webp", + "bytes": 816 + }, + "geometry": { + "file": "card-0-t13-geometry.webp", + "bytes": 5824 + } + }, + { + "top": 409, + "h": 191, + "distance_m": 7060.0029296875, + "colour": { + "file": "card-1-t13-colour.webp", + "bytes": 504 + }, + "geometry": { + "file": "card-1-t13-geometry.webp", + "bytes": 3526 + } + }, + { + "top": 366, + "h": 234, + "distance_m": 39014.42578125, + "colour": { + "file": "card-2-t13-colour.webp", + "bytes": 1242 + }, + "geometry": { + "file": "card-2-t13-geometry.webp", + "bytes": 13042 + } + } + ], + [ + { + "top": 403, + "h": 197, + "distance_m": 580.0, + "colour": { + "file": "card-0-t14-colour.webp", + "bytes": 780 + }, + "geometry": { + "file": "card-0-t14-geometry.webp", + "bytes": 7612 + } + }, + { + "top": 413, + "h": 187, + "distance_m": 1765.88525390625, + "colour": { + "file": "card-1-t14-colour.webp", + "bytes": 810 + }, + "geometry": { + "file": "card-1-t14-geometry.webp", + "bytes": 4132 + } + }, + { + "top": 377, + "h": 223, + "distance_m": 32016.8203125, + "colour": { + "file": "card-2-t14-colour.webp", + "bytes": 864 + }, + "geometry": { + "file": "card-2-t14-geometry.webp", + "bytes": 6880 + } + } + ], + [ + { + "top": 403, + "h": 197, + "distance_m": 686.8928833007812, + "colour": { + "file": "card-0-t15-colour.webp", + "bytes": 966 + }, + "geometry": { + "file": "card-0-t15-geometry.webp", + "bytes": 5516 + } + }, + { + "top": 405, + "h": 195, + "distance_m": 2099.999755859375, + "colour": { + "file": "card-1-t15-colour.webp", + "bytes": 1122 + }, + "geometry": { + "file": "card-1-t15-geometry.webp", + "bytes": 7516 + } + }, + { + "top": 369, + "h": 231, + "distance_m": 16337.44140625, + "colour": { + "file": "card-2-t15-colour.webp", + "bytes": 1056 + }, + "geometry": { + "file": "card-2-t15-geometry.webp", + "bytes": 9850 + } + } + ], + [ + { + "top": 325, + "h": 275, + "distance_m": 540.0000610351562, + "colour": { + "file": "card-0-t16-colour.webp", + "bytes": 946 + }, + "geometry": { + "file": "card-0-t16-geometry.webp", + "bytes": 5460 + } + }, + { + "top": 372, + "h": 228, + "distance_m": 7220.0, + "colour": { + "file": "card-1-t16-colour.webp", + "bytes": 2730 + }, + "geometry": { + "file": "card-1-t16-geometry.webp", + "bytes": 17512 + } + }, + { + "top": 372, + "h": 228, + "distance_m": 15879.7060546875, + "colour": { + "file": "card-2-t16-colour.webp", + "bytes": 1036 + }, + "geometry": { + "file": "card-2-t16-geometry.webp", + "bytes": 9366 + } + } + ], + [ + { + "top": 298, + "h": 302, + "distance_m": 540.0000610351562, + "colour": { + "file": "card-0-t17-colour.webp", + "bytes": 594 + }, + "geometry": { + "file": "card-0-t17-geometry.webp", + "bytes": 6552 + } + }, + { + "top": 370, + "h": 230, + "distance_m": 9510.94140625, + "colour": { + "file": "card-1-t17-colour.webp", + "bytes": 1516 + }, + "geometry": { + "file": "card-1-t17-geometry.webp", + "bytes": 9820 + } + }, + { + "top": 365, + "h": 235, + "distance_m": 18620.474609375, + "colour": { + "file": "card-2-t17-colour.webp", + "bytes": 1144 + }, + "geometry": { + "file": "card-2-t17-geometry.webp", + "bytes": 11254 + } + } + ], + [ + { + "top": 283, + "h": 317, + "distance_m": 540.0000610351562, + "colour": { + "file": "card-0-t18-colour.webp", + "bytes": 574 + }, + "geometry": { + "file": "card-0-t18-geometry.webp", + "bytes": 6636 + } + }, + { + "top": 351, + "h": 249, + "distance_m": 1855.5841064453125, + "colour": { + "file": "card-1-t18-colour.webp", + "bytes": 1424 + }, + "geometry": { + "file": "card-1-t18-geometry.webp", + "bytes": 9330 + } + }, + { + "top": 340, + "h": 260, + "distance_m": 16873.72265625, + "colour": { + "file": "card-2-t18-colour.webp", + "bytes": 1352 + }, + "geometry": { + "file": "card-2-t18-geometry.webp", + "bytes": 14144 + } + } + ], + [ + { + "top": 246, + "h": 354, + "distance_m": 526.8663330078125, + "colour": { + "file": "card-0-t19-colour.webp", + "bytes": 756 + }, + "geometry": { + "file": "card-0-t19-geometry.webp", + "bytes": 7000 + } + }, + { + "top": 328, + "h": 272, + "distance_m": 3539.998779296875, + "colour": { + "file": "card-1-t19-colour.webp", + "bytes": 2300 + }, + "geometry": { + "file": "card-1-t19-geometry.webp", + "bytes": 10532 + } + }, + { + "top": 323, + "h": 277, + "distance_m": 15921.30078125, + "colour": { + "file": "card-2-t19-colour.webp", + "bytes": 1756 + }, + "geometry": { + "file": "card-2-t19-geometry.webp", + "bytes": 17248 + } + } + ], + [ + { + "top": 232, + "h": 368, + "distance_m": 500.0, + "colour": { + "file": "card-0-t20-colour.webp", + "bytes": 906 + }, + "geometry": { + "file": "card-0-t20-geometry.webp", + "bytes": 7026 + } + }, + { + "top": 236, + "h": 364, + "distance_m": 2882.576171875, + "colour": { + "file": "card-1-t20-colour.webp", + "bytes": 1652 + }, + "geometry": { + "file": "card-1-t20-geometry.webp", + "bytes": 16248 + } + }, + { + "top": 303, + "h": 297, + "distance_m": 18978.27734375, + "colour": { + "file": "card-2-t20-colour.webp", + "bytes": 2164 + }, + "geometry": { + "file": "card-2-t20-geometry.webp", + "bytes": 23390 + } + } + ], + [ + { + "top": 299, + "h": 301, + "distance_m": 523.988037109375, + "colour": { + "file": "card-0-t21-colour.webp", + "bytes": 516 + }, + "geometry": { + "file": "card-0-t21-geometry.webp", + "bytes": 4618 + } + }, + { + "top": 181, + "h": 419, + "distance_m": 2487.41748046875, + "colour": { + "file": "card-1-t21-colour.webp", + "bytes": 1948 + }, + "geometry": { + "file": "card-1-t21-geometry.webp", + "bytes": 21030 + } + }, + { + "top": 285, + "h": 315, + "distance_m": 15885.142578125, + "colour": { + "file": "card-2-t21-colour.webp", + "bytes": 1832 + }, + "geometry": { + "file": "card-2-t21-geometry.webp", + "bytes": 19512 + } + } + ], + [ + { + "top": 217, + "h": 383, + "distance_m": 540.0000610351562, + "colour": { + "file": "card-0-t22-colour.webp", + "bytes": 930 + }, + "geometry": { + "file": "card-0-t22-geometry.webp", + "bytes": 9268 + } + }, + { + "top": 187, + "h": 413, + "distance_m": 2460.0, + "colour": { + "file": "card-1-t22-colour.webp", + "bytes": 1940 + }, + "geometry": { + "file": "card-1-t22-geometry.webp", + "bytes": 21596 + } + }, + { + "top": 285, + "h": 315, + "distance_m": 18933.138671875, + "colour": { + "file": "card-2-t22-colour.webp", + "bytes": 2002 + }, + "geometry": { + "file": "card-2-t22-geometry.webp", + "bytes": 23052 + } + } + ], + [ + { + "top": 214, + "h": 386, + "distance_m": 500.0, + "colour": { + "file": "card-0-t23-colour.webp", + "bytes": 856 + }, + "geometry": { + "file": "card-0-t23-geometry.webp", + "bytes": 6918 + } + }, + { + "top": 196, + "h": 404, + "distance_m": 2266.6904296875, + "colour": { + "file": "card-1-t23-colour.webp", + "bytes": 2018 + }, + "geometry": { + "file": "card-1-t23-geometry.webp", + "bytes": 19508 + } + }, + { + "top": 289, + "h": 311, + "distance_m": 17854.271484375, + "colour": { + "file": "card-2-t23-colour.webp", + "bytes": 2088 + }, + "geometry": { + "file": "card-2-t23-geometry.webp", + "bytes": 24602 + } + } + ], + [ + { + "top": 257, + "h": 343, + "distance_m": 500.0, + "colour": { + "file": "card-0-t24-colour.webp", + "bytes": 432 + }, + "geometry": { + "file": "card-0-t24-geometry.webp", + "bytes": 3410 + } + }, + { + "top": 163, + "h": 437, + "distance_m": 3320.263916015625, + "colour": { + "file": "card-1-t24-colour.webp", + "bytes": 2316 + }, + "geometry": { + "file": "card-1-t24-geometry.webp", + "bytes": 24600 + } + }, + { + "top": 281, + "h": 319, + "distance_m": 18784.22265625, + "colour": { + "file": "card-2-t24-colour.webp", + "bytes": 2162 + }, + "geometry": { + "file": "card-2-t24-geometry.webp", + "bytes": 26604 + } + } + ], + [ + { + "top": 261, + "h": 339, + "distance_m": 500.0, + "colour": { + "file": "card-0-t25-colour.webp", + "bytes": 430 + }, + "geometry": { + "file": "card-0-t25-geometry.webp", + "bytes": 3604 + } + }, + { + "top": 118, + "h": 482, + "distance_m": 3844.12060546875, + "colour": { + "file": "card-1-t25-colour.webp", + "bytes": 2480 + }, + "geometry": { + "file": "card-1-t25-geometry.webp", + "bytes": 29602 + } + }, + { + "top": 277, + "h": 323, + "distance_m": 18950.58984375, + "colour": { + "file": "card-2-t25-colour.webp", + "bytes": 2524 + }, + "geometry": { + "file": "card-2-t25-geometry.webp", + "bytes": 29858 + } + } + ], + [ + { + "top": 262, + "h": 338, + "distance_m": 500.0, + "colour": { + "file": "card-0-t26-colour.webp", + "bytes": 390 + }, + "geometry": { + "file": "card-0-t26-geometry.webp", + "bytes": 4218 + } + }, + { + "top": 126, + "h": 474, + "distance_m": 3865.76318359375, + "colour": { + "file": "card-1-t26-colour.webp", + "bytes": 2324 + }, + "geometry": { + "file": "card-1-t26-geometry.webp", + "bytes": 23298 + } + }, + { + "top": 280, + "h": 320, + "distance_m": 17852.943359375, + "colour": { + "file": "card-2-t26-colour.webp", + "bytes": 3190 + }, + "geometry": { + "file": "card-2-t26-geometry.webp", + "bytes": 33020 + } + } + ], + [ + { + "top": 254, + "h": 346, + "distance_m": 500.0, + "colour": { + "file": "card-0-t27-colour.webp", + "bytes": 570 + }, + "geometry": { + "file": "card-0-t27-geometry.webp", + "bytes": 2916 + } + }, + { + "top": 152, + "h": 448, + "distance_m": 2996.300537109375, + "colour": { + "file": "card-1-t27-colour.webp", + "bytes": 2110 + }, + "geometry": { + "file": "card-1-t27-geometry.webp", + "bytes": 18668 + } + }, + { + "top": 300, + "h": 300, + "distance_m": 24081.75, + "colour": { + "file": "card-2-t27-colour.webp", + "bytes": 2670 + }, + "geometry": { + "file": "card-2-t27-geometry.webp", + "bytes": 26822 + } + } + ], + [ + { + "top": 238, + "h": 362, + "distance_m": 521.66259765625, + "colour": { + "file": "card-0-t28-colour.webp", + "bytes": 684 + }, + "geometry": { + "file": "card-0-t28-geometry.webp", + "bytes": 2578 + } + }, + { + "top": 197, + "h": 403, + "distance_m": 4912.1728515625, + "colour": { + "file": "card-1-t28-colour.webp", + "bytes": 2348 + }, + "geometry": { + "file": "card-1-t28-geometry.webp", + "bytes": 21618 + } + }, + { + "top": 300, + "h": 300, + "distance_m": 29091.6875, + "colour": { + "file": "card-2-t28-colour.webp", + "bytes": 2870 + }, + "geometry": { + "file": "card-2-t28-geometry.webp", + "bytes": 21314 + } + } + ], + [ + { + "top": 251, + "h": 349, + "distance_m": 933.6327514648438, + "colour": { + "file": "card-0-t29-colour.webp", + "bytes": 666 + }, + "geometry": { + "file": "card-0-t29-geometry.webp", + "bytes": 2446 + } + }, + { + "top": 196, + "h": 404, + "distance_m": 9113.6005859375, + "colour": { + "file": "card-1-t29-colour.webp", + "bytes": 1968 + }, + "geometry": { + "file": "card-1-t29-geometry.webp", + "bytes": 19576 + } + }, + { + "top": 275, + "h": 325, + "distance_m": 15211.173828125, + "colour": { + "file": "card-2-t29-colour.webp", + "bytes": 866 + }, + "geometry": { + "file": "card-2-t29-geometry.webp", + "bytes": 1954 + } + } + ], + [ + { + "top": 262, + "h": 338, + "distance_m": 889.6878662109375, + "colour": { + "file": "card-0-t30-colour.webp", + "bytes": 740 + }, + "geometry": { + "file": "card-0-t30-geometry.webp", + "bytes": 4290 + } + }, + { + "top": 194, + "h": 406, + "distance_m": 11419.8154296875, + "colour": { + "file": "card-1-t30-colour.webp", + "bytes": 1604 + }, + "geometry": { + "file": "card-1-t30-geometry.webp", + "bytes": 19036 + } + }, + { + "top": 279, + "h": 321, + "distance_m": 14933.046875, + "colour": { + "file": "card-2-t30-colour.webp", + "bytes": 760 + }, + "geometry": { + "file": "card-2-t30-geometry.webp", + "bytes": 994 + } + } + ], + [ + { + "top": 287, + "h": 313, + "distance_m": 1129.969482421875, + "colour": { + "file": "card-0-t31-colour.webp", + "bytes": 688 + }, + "geometry": { + "file": "card-0-t31-geometry.webp", + "bytes": 2380 + } + }, + { + "top": 228, + "h": 372, + "distance_m": 12246.369140625, + "colour": { + "file": "card-1-t31-colour.webp", + "bytes": 1378 + }, + "geometry": { + "file": "card-1-t31-geometry.webp", + "bytes": 8344 + } + }, + { + "top": 288, + "h": 312, + "distance_m": 15459.7197265625, + "colour": { + "file": "card-2-t31-colour.webp", + "bytes": 856 + }, + "geometry": { + "file": "card-2-t31-geometry.webp", + "bytes": 2992 + } + } + ] + ], + "bytes": 1226472, + "attribution": { + "credit_line": "Contains modified Copernicus data: DEM \u00a9 DLR e.V. 2010-2014 and \u00a9 Airbus Defence and Space GmbH 2014-2018 provided under COPERNICUS by the European Union and ESA; all rights reserved.", + "licence": "Copernicus DEM licence: free, full and open access, with the credit line shown", + "dem_source": "Copernicus DEM GLO-30 (30 m)", + "url": "https://spacedata.copernicus.eu/collections/copernicus-digital-elevation-model" + } +} diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t00-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t00-colour.webp new file mode 100644 index 00000000..e6750b35 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t00-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t00-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t00-geometry.webp new file mode 100644 index 00000000..3952ce57 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t00-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t01-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t01-colour.webp new file mode 100644 index 00000000..dfc99bd8 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t01-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t01-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t01-geometry.webp new file mode 100644 index 00000000..8aa7d441 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t01-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t02-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t02-colour.webp new file mode 100644 index 00000000..55cb4b76 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t02-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t02-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t02-geometry.webp new file mode 100644 index 00000000..8168684e Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t02-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t03-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t03-colour.webp new file mode 100644 index 00000000..adc44e89 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t03-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t03-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t03-geometry.webp new file mode 100644 index 00000000..18d5ef0b Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t03-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t04-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t04-colour.webp new file mode 100644 index 00000000..5addeddf Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t04-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t04-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t04-geometry.webp new file mode 100644 index 00000000..6c8c422b Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t04-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t05-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t05-colour.webp new file mode 100644 index 00000000..d00315c8 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t05-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t05-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t05-geometry.webp new file mode 100644 index 00000000..70c7eea1 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t05-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t06-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t06-colour.webp new file mode 100644 index 00000000..5b9341ff Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t06-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t06-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t06-geometry.webp new file mode 100644 index 00000000..391d0c00 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t06-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t07-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t07-colour.webp new file mode 100644 index 00000000..7a65030d Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t07-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t07-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t07-geometry.webp new file mode 100644 index 00000000..437f582a Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t07-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t08-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t08-colour.webp new file mode 100644 index 00000000..9445eb99 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t08-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t08-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t08-geometry.webp new file mode 100644 index 00000000..76a5f1b2 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t08-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t09-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t09-colour.webp new file mode 100644 index 00000000..c51bf5aa Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t09-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t09-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t09-geometry.webp new file mode 100644 index 00000000..6d8086b4 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t09-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t10-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t10-colour.webp new file mode 100644 index 00000000..aa755b56 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t10-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t10-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t10-geometry.webp new file mode 100644 index 00000000..d8f5e11c Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t10-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t11-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t11-colour.webp new file mode 100644 index 00000000..753ad83a Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t11-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t11-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t11-geometry.webp new file mode 100644 index 00000000..419ef76d Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t11-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t12-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t12-colour.webp new file mode 100644 index 00000000..4919df09 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t12-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t12-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t12-geometry.webp new file mode 100644 index 00000000..1f85f858 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t12-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t13-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t13-colour.webp new file mode 100644 index 00000000..2cdfb3ad Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t13-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t13-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t13-geometry.webp new file mode 100644 index 00000000..0911c831 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t13-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t14-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t14-colour.webp new file mode 100644 index 00000000..a5152898 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t14-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t14-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t14-geometry.webp new file mode 100644 index 00000000..3b05d507 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t14-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t15-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t15-colour.webp new file mode 100644 index 00000000..02aa7f36 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t15-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t15-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t15-geometry.webp new file mode 100644 index 00000000..552e9517 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t15-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t16-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t16-colour.webp new file mode 100644 index 00000000..11ed84a6 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t16-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t16-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t16-geometry.webp new file mode 100644 index 00000000..f50806b9 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t16-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t17-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t17-colour.webp new file mode 100644 index 00000000..08faaeab Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t17-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t17-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t17-geometry.webp new file mode 100644 index 00000000..08c1d196 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t17-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t18-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t18-colour.webp new file mode 100644 index 00000000..9541cd3b Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t18-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t18-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t18-geometry.webp new file mode 100644 index 00000000..46ac2a97 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t18-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t19-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t19-colour.webp new file mode 100644 index 00000000..886dfcf6 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t19-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t19-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t19-geometry.webp new file mode 100644 index 00000000..de650849 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t19-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t20-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t20-colour.webp new file mode 100644 index 00000000..91ac93b6 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t20-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t20-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t20-geometry.webp new file mode 100644 index 00000000..da82875f Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t20-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t21-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t21-colour.webp new file mode 100644 index 00000000..e1e799bf Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t21-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t21-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t21-geometry.webp new file mode 100644 index 00000000..4ce52bfa Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t21-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t22-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t22-colour.webp new file mode 100644 index 00000000..9d116e5b Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t22-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t22-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t22-geometry.webp new file mode 100644 index 00000000..6a49b359 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t22-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t23-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t23-colour.webp new file mode 100644 index 00000000..ca356783 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t23-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t23-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t23-geometry.webp new file mode 100644 index 00000000..357323b6 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t23-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t24-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t24-colour.webp new file mode 100644 index 00000000..a6da9764 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t24-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t24-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t24-geometry.webp new file mode 100644 index 00000000..536a8e36 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t24-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t25-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t25-colour.webp new file mode 100644 index 00000000..e2ff23ff Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t25-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t25-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t25-geometry.webp new file mode 100644 index 00000000..00bd7b53 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t25-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t26-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t26-colour.webp new file mode 100644 index 00000000..7a6ee65e Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t26-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t26-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t26-geometry.webp new file mode 100644 index 00000000..926b6d03 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t26-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t27-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t27-colour.webp new file mode 100644 index 00000000..85fe9c67 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t27-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t27-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t27-geometry.webp new file mode 100644 index 00000000..3e069ad9 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t27-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t28-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t28-colour.webp new file mode 100644 index 00000000..9a66e945 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t28-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t28-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t28-geometry.webp new file mode 100644 index 00000000..f992fa67 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t28-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t29-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t29-colour.webp new file mode 100644 index 00000000..df876b58 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t29-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t29-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t29-geometry.webp new file mode 100644 index 00000000..9bc80668 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t29-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t30-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t30-colour.webp new file mode 100644 index 00000000..16ffb281 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t30-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t30-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t30-geometry.webp new file mode 100644 index 00000000..2ff74765 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t30-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t31-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t31-colour.webp new file mode 100644 index 00000000..162a857d Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t31-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t31-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t31-geometry.webp new file mode 100644 index 00000000..5e124463 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-0-t31-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t00-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t00-colour.webp new file mode 100644 index 00000000..9d4a98f5 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t00-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t00-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t00-geometry.webp new file mode 100644 index 00000000..697c5955 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t00-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t01-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t01-colour.webp new file mode 100644 index 00000000..647be0e6 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t01-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t01-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t01-geometry.webp new file mode 100644 index 00000000..8049b634 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t01-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t02-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t02-colour.webp new file mode 100644 index 00000000..c4e96dc4 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t02-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t02-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t02-geometry.webp new file mode 100644 index 00000000..68e2575b Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t02-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t03-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t03-colour.webp new file mode 100644 index 00000000..60a0bc16 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t03-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t03-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t03-geometry.webp new file mode 100644 index 00000000..cacb760c Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t03-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t04-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t04-colour.webp new file mode 100644 index 00000000..2294dca4 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t04-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t04-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t04-geometry.webp new file mode 100644 index 00000000..7a025acd Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t04-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t05-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t05-colour.webp new file mode 100644 index 00000000..81a9c1e3 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t05-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t05-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t05-geometry.webp new file mode 100644 index 00000000..ad7acf0a Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t05-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t06-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t06-colour.webp new file mode 100644 index 00000000..819346db Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t06-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t06-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t06-geometry.webp new file mode 100644 index 00000000..29d957cf Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t06-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t07-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t07-colour.webp new file mode 100644 index 00000000..283ba321 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t07-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t07-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t07-geometry.webp new file mode 100644 index 00000000..49612dfc Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t07-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t08-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t08-colour.webp new file mode 100644 index 00000000..807fc2fc Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t08-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t08-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t08-geometry.webp new file mode 100644 index 00000000..7ef8d89d Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t08-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t09-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t09-colour.webp new file mode 100644 index 00000000..b2880f5f Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t09-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t09-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t09-geometry.webp new file mode 100644 index 00000000..3ce6d740 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t09-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t10-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t10-colour.webp new file mode 100644 index 00000000..cd1a6854 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t10-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t10-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t10-geometry.webp new file mode 100644 index 00000000..e7c86450 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t10-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t11-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t11-colour.webp new file mode 100644 index 00000000..8d792fc0 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t11-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t11-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t11-geometry.webp new file mode 100644 index 00000000..bc9c0e4e Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t11-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t12-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t12-colour.webp new file mode 100644 index 00000000..ab123852 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t12-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t12-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t12-geometry.webp new file mode 100644 index 00000000..177d2b6c Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t12-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t13-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t13-colour.webp new file mode 100644 index 00000000..88a9dc5d Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t13-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t13-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t13-geometry.webp new file mode 100644 index 00000000..1f930146 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t13-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t14-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t14-colour.webp new file mode 100644 index 00000000..cc8f51de Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t14-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t14-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t14-geometry.webp new file mode 100644 index 00000000..8eb04a7f Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t14-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t15-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t15-colour.webp new file mode 100644 index 00000000..4f8a10d3 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t15-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t15-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t15-geometry.webp new file mode 100644 index 00000000..5b805c53 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t15-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t16-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t16-colour.webp new file mode 100644 index 00000000..ac49ee5e Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t16-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t16-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t16-geometry.webp new file mode 100644 index 00000000..c4309d1f Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t16-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t17-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t17-colour.webp new file mode 100644 index 00000000..746caf11 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t17-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t17-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t17-geometry.webp new file mode 100644 index 00000000..4ddc5b19 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t17-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t18-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t18-colour.webp new file mode 100644 index 00000000..9aa6837f Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t18-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t18-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t18-geometry.webp new file mode 100644 index 00000000..5428f77e Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t18-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t19-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t19-colour.webp new file mode 100644 index 00000000..d11fc994 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t19-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t19-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t19-geometry.webp new file mode 100644 index 00000000..919003fa Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t19-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t20-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t20-colour.webp new file mode 100644 index 00000000..1dbb939f Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t20-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t20-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t20-geometry.webp new file mode 100644 index 00000000..d3f25a11 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t20-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t21-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t21-colour.webp new file mode 100644 index 00000000..bf774fb0 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t21-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t21-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t21-geometry.webp new file mode 100644 index 00000000..dc8e3b7b Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t21-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t22-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t22-colour.webp new file mode 100644 index 00000000..98befef4 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t22-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t22-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t22-geometry.webp new file mode 100644 index 00000000..0de93dea Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t22-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t23-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t23-colour.webp new file mode 100644 index 00000000..8ab8edb0 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t23-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t23-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t23-geometry.webp new file mode 100644 index 00000000..9e122c49 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t23-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t24-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t24-colour.webp new file mode 100644 index 00000000..94f56e6b Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t24-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t24-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t24-geometry.webp new file mode 100644 index 00000000..560089f2 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t24-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t25-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t25-colour.webp new file mode 100644 index 00000000..6e68c5f4 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t25-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t25-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t25-geometry.webp new file mode 100644 index 00000000..15ffc046 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t25-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t26-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t26-colour.webp new file mode 100644 index 00000000..7ea67a2a Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t26-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t26-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t26-geometry.webp new file mode 100644 index 00000000..6ff2fedc Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t26-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t27-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t27-colour.webp new file mode 100644 index 00000000..216d6729 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t27-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t27-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t27-geometry.webp new file mode 100644 index 00000000..753894aa Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t27-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t28-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t28-colour.webp new file mode 100644 index 00000000..f1af01e0 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t28-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t28-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t28-geometry.webp new file mode 100644 index 00000000..b844dd04 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t28-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t29-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t29-colour.webp new file mode 100644 index 00000000..f65b9632 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t29-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t29-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t29-geometry.webp new file mode 100644 index 00000000..da95eb9c Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t29-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t30-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t30-colour.webp new file mode 100644 index 00000000..f69cb8c8 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t30-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t30-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t30-geometry.webp new file mode 100644 index 00000000..ea24cc5b Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t30-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t31-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t31-colour.webp new file mode 100644 index 00000000..2720e5c1 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t31-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t31-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t31-geometry.webp new file mode 100644 index 00000000..a219a425 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-1-t31-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t00-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t00-colour.webp new file mode 100644 index 00000000..99b21d9f Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t00-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t00-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t00-geometry.webp new file mode 100644 index 00000000..11103c8e Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t00-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t01-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t01-colour.webp new file mode 100644 index 00000000..2163ca50 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t01-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t01-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t01-geometry.webp new file mode 100644 index 00000000..68777d69 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t01-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t02-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t02-colour.webp new file mode 100644 index 00000000..4a5d8db1 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t02-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t02-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t02-geometry.webp new file mode 100644 index 00000000..5a66912b Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t02-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t03-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t03-colour.webp new file mode 100644 index 00000000..2f15fc28 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t03-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t03-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t03-geometry.webp new file mode 100644 index 00000000..6089b895 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t03-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t04-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t04-colour.webp new file mode 100644 index 00000000..5ede46ad Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t04-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t04-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t04-geometry.webp new file mode 100644 index 00000000..deccd7d5 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t04-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t05-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t05-colour.webp new file mode 100644 index 00000000..790f83b8 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t05-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t05-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t05-geometry.webp new file mode 100644 index 00000000..196d075d Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t05-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t06-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t06-colour.webp new file mode 100644 index 00000000..9e026522 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t06-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t06-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t06-geometry.webp new file mode 100644 index 00000000..85e38180 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t06-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t07-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t07-colour.webp new file mode 100644 index 00000000..c12322f8 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t07-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t07-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t07-geometry.webp new file mode 100644 index 00000000..411a61d2 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t07-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t08-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t08-colour.webp new file mode 100644 index 00000000..499ef01f Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t08-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t08-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t08-geometry.webp new file mode 100644 index 00000000..895dbe12 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t08-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t09-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t09-colour.webp new file mode 100644 index 00000000..c4e075e5 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t09-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t09-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t09-geometry.webp new file mode 100644 index 00000000..b0a8fcc0 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t09-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t10-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t10-colour.webp new file mode 100644 index 00000000..74c47232 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t10-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t10-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t10-geometry.webp new file mode 100644 index 00000000..0ef9a57a Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t10-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t11-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t11-colour.webp new file mode 100644 index 00000000..e42baa29 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t11-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t11-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t11-geometry.webp new file mode 100644 index 00000000..5f42dab8 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t11-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t12-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t12-colour.webp new file mode 100644 index 00000000..4c577383 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t12-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t12-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t12-geometry.webp new file mode 100644 index 00000000..94e21f96 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t12-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t13-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t13-colour.webp new file mode 100644 index 00000000..6fde1297 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t13-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t13-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t13-geometry.webp new file mode 100644 index 00000000..212fe130 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t13-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t14-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t14-colour.webp new file mode 100644 index 00000000..f714d328 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t14-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t14-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t14-geometry.webp new file mode 100644 index 00000000..271a5ab7 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t14-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t15-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t15-colour.webp new file mode 100644 index 00000000..02086f10 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t15-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t15-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t15-geometry.webp new file mode 100644 index 00000000..6540159f Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t15-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t16-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t16-colour.webp new file mode 100644 index 00000000..574c0fd8 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t16-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t16-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t16-geometry.webp new file mode 100644 index 00000000..d6d979cb Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t16-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t17-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t17-colour.webp new file mode 100644 index 00000000..59f1eab7 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t17-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t17-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t17-geometry.webp new file mode 100644 index 00000000..9b974504 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t17-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t18-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t18-colour.webp new file mode 100644 index 00000000..939507f8 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t18-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t18-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t18-geometry.webp new file mode 100644 index 00000000..3e4edcc4 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t18-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t19-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t19-colour.webp new file mode 100644 index 00000000..5827a615 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t19-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t19-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t19-geometry.webp new file mode 100644 index 00000000..6a519924 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t19-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t20-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t20-colour.webp new file mode 100644 index 00000000..8b66193c Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t20-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t20-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t20-geometry.webp new file mode 100644 index 00000000..8c5104e8 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t20-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t21-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t21-colour.webp new file mode 100644 index 00000000..6e51c86a Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t21-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t21-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t21-geometry.webp new file mode 100644 index 00000000..3a67c175 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t21-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t22-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t22-colour.webp new file mode 100644 index 00000000..90d3662e Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t22-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t22-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t22-geometry.webp new file mode 100644 index 00000000..29da5c81 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t22-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t23-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t23-colour.webp new file mode 100644 index 00000000..afc49856 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t23-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t23-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t23-geometry.webp new file mode 100644 index 00000000..a5482271 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t23-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t24-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t24-colour.webp new file mode 100644 index 00000000..240bb07b Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t24-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t24-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t24-geometry.webp new file mode 100644 index 00000000..cbd26836 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t24-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t25-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t25-colour.webp new file mode 100644 index 00000000..f47ba866 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t25-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t25-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t25-geometry.webp new file mode 100644 index 00000000..c7ad1598 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t25-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t26-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t26-colour.webp new file mode 100644 index 00000000..e5986bbf Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t26-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t26-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t26-geometry.webp new file mode 100644 index 00000000..bf94c2ae Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t26-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t27-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t27-colour.webp new file mode 100644 index 00000000..de0ff18b Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t27-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t27-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t27-geometry.webp new file mode 100644 index 00000000..02cca7ee Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t27-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t28-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t28-colour.webp new file mode 100644 index 00000000..cdf70c38 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t28-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t28-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t28-geometry.webp new file mode 100644 index 00000000..4ddf6845 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t28-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t29-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t29-colour.webp new file mode 100644 index 00000000..ba31e182 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t29-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t29-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t29-geometry.webp new file mode 100644 index 00000000..b5616356 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t29-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t30-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t30-colour.webp new file mode 100644 index 00000000..29cc2e12 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t30-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t30-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t30-geometry.webp new file mode 100644 index 00000000..e06c7602 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t30-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t31-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t31-colour.webp new file mode 100644 index 00000000..b20e4e5b Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t31-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t31-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t31-geometry.webp new file mode 100644 index 00000000..6eb0285f Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-2-t31-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t00-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t00-colour.webp new file mode 100644 index 00000000..2c17b67d Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t00-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t00-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t00-geometry.webp new file mode 100644 index 00000000..1a1c8cfa Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t00-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t01-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t01-colour.webp new file mode 100644 index 00000000..b802e413 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t01-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t01-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t01-geometry.webp new file mode 100644 index 00000000..43046c48 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t01-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t02-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t02-colour.webp new file mode 100644 index 00000000..fdc079b7 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t02-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t02-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t02-geometry.webp new file mode 100644 index 00000000..32a036dd Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t02-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t03-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t03-colour.webp new file mode 100644 index 00000000..0f2262d7 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t03-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t03-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t03-geometry.webp new file mode 100644 index 00000000..3bcc55ef Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t03-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t04-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t04-colour.webp new file mode 100644 index 00000000..94dac22d Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t04-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t04-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t04-geometry.webp new file mode 100644 index 00000000..e54d037c Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t04-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t05-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t05-colour.webp new file mode 100644 index 00000000..4d21f1e3 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t05-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t05-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t05-geometry.webp new file mode 100644 index 00000000..cdc9659c Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t05-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t06-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t06-colour.webp new file mode 100644 index 00000000..5e58ff43 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t06-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t06-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t06-geometry.webp new file mode 100644 index 00000000..c47c58e8 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t06-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t07-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t07-colour.webp new file mode 100644 index 00000000..9a343e21 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t07-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t07-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t07-geometry.webp new file mode 100644 index 00000000..246edc76 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t07-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t08-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t08-colour.webp new file mode 100644 index 00000000..8cac13da Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t08-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t08-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t08-geometry.webp new file mode 100644 index 00000000..ecdfbe8d Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t08-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t09-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t09-colour.webp new file mode 100644 index 00000000..379e95bd Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t09-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t09-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t09-geometry.webp new file mode 100644 index 00000000..ecdfbe8d Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t09-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t10-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t10-colour.webp new file mode 100644 index 00000000..f5889e43 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t10-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t10-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t10-geometry.webp new file mode 100644 index 00000000..717a9188 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t10-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t11-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t11-colour.webp new file mode 100644 index 00000000..81c7d723 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t11-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t11-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t11-geometry.webp new file mode 100644 index 00000000..774c3af1 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t11-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t12-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t12-colour.webp new file mode 100644 index 00000000..4c9b707e Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t12-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t12-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t12-geometry.webp new file mode 100644 index 00000000..3de8626e Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t12-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t13-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t13-colour.webp new file mode 100644 index 00000000..43795f6e Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t13-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t13-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t13-geometry.webp new file mode 100644 index 00000000..6bfd9ede Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t13-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t14-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t14-colour.webp new file mode 100644 index 00000000..41c99f4c Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t14-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t14-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t14-geometry.webp new file mode 100644 index 00000000..bc9df623 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t14-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t15-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t15-colour.webp new file mode 100644 index 00000000..38baedc8 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t15-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t15-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t15-geometry.webp new file mode 100644 index 00000000..bc9df623 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t15-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t16-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t16-colour.webp new file mode 100644 index 00000000..66059d81 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t16-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t16-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t16-geometry.webp new file mode 100644 index 00000000..6497ba32 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t16-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t17-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t17-colour.webp new file mode 100644 index 00000000..443cc1a8 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t17-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t17-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t17-geometry.webp new file mode 100644 index 00000000..bc9df623 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t17-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t18-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t18-colour.webp new file mode 100644 index 00000000..21e8bf90 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t18-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t18-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t18-geometry.webp new file mode 100644 index 00000000..bc9df623 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t18-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t19-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t19-colour.webp new file mode 100644 index 00000000..000ee760 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t19-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t19-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t19-geometry.webp new file mode 100644 index 00000000..bc9df623 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t19-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t20-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t20-colour.webp new file mode 100644 index 00000000..61c631f4 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t20-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t20-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t20-geometry.webp new file mode 100644 index 00000000..6497ba32 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t20-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t21-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t21-colour.webp new file mode 100644 index 00000000..75c5aa10 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t21-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t21-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t21-geometry.webp new file mode 100644 index 00000000..14c2e95e Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t21-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t22-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t22-colour.webp new file mode 100644 index 00000000..8c3efc40 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t22-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t22-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t22-geometry.webp new file mode 100644 index 00000000..17b2c0a7 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t22-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t23-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t23-colour.webp new file mode 100644 index 00000000..b2633ce9 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t23-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t23-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t23-geometry.webp new file mode 100644 index 00000000..2e8eff72 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t23-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t24-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t24-colour.webp new file mode 100644 index 00000000..7a17b1c6 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t24-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t24-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t24-geometry.webp new file mode 100644 index 00000000..6a8f7a47 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t24-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t25-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t25-colour.webp new file mode 100644 index 00000000..a358a853 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t25-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t25-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t25-geometry.webp new file mode 100644 index 00000000..b4b144fc Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t25-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t26-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t26-colour.webp new file mode 100644 index 00000000..8fdfef54 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t26-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t26-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t26-geometry.webp new file mode 100644 index 00000000..0f5a6904 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t26-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t27-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t27-colour.webp new file mode 100644 index 00000000..829fc1ff Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t27-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t27-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t27-geometry.webp new file mode 100644 index 00000000..5d9023b4 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t27-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t28-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t28-colour.webp new file mode 100644 index 00000000..89c823b8 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t28-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t28-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t28-geometry.webp new file mode 100644 index 00000000..85099502 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t28-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t29-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t29-colour.webp new file mode 100644 index 00000000..40ff6b88 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t29-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t29-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t29-geometry.webp new file mode 100644 index 00000000..d2e8f2a7 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t29-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t30-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t30-colour.webp new file mode 100644 index 00000000..98ed8f11 Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t30-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t30-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t30-geometry.webp new file mode 100644 index 00000000..c8c89c4f Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t30-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t31-colour.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t31-colour.webp new file mode 100644 index 00000000..ba031e6f Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t31-colour.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t31-geometry.webp b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t31-geometry.webp new file mode 100644 index 00000000..88fe821a Binary files /dev/null and b/public/ridge/grandcanyon-dcfa7cc15fdd/card-3-t31-geometry.webp differ diff --git a/public/ridge/grandcanyon-dcfa7cc15fdd/manifest.json b/public/ridge/grandcanyon-dcfa7cc15fdd/manifest.json new file mode 100644 index 00000000..3cf044de --- /dev/null +++ b/public/ridge/grandcanyon-dcfa7cc15fdd/manifest.json @@ -0,0 +1,1796 @@ +{ + "schema": 3, + "baker_version": 7, + "bake_id": "dcfa7cc15fdd", + "place": { + "id": "grandcanyon", + "name": "Grand Canyon from Unkar and Cardenas", + "lat": 36.0817, + "lon": -111.8551, + "altitude_km": 0.9182969562014661, + "eye_m": 919.8969562014662, + "tz": "America/Phoenix" + }, + "view": { + "look_az_deg": 290, + "plane_h": 600, + "px_per_deg_h": 17.77777777777778, + "px_per_deg_v": 15.039939126168882, + "exaggeration": 0.8459965758469996, + "horizon_row": 450.0, + "sky_row": 24.0, + "near_row": 396.0, + "ring_w": 6400, + "tile_w": 200, + "tiles": 32, + "apron": 2 + }, + "curvature": { + "r_earth_m": 6371000.0, + "k_ref": 0.13 + }, + "encoding": { + "log_d_min": 6.214608098422191, + "log_d_max": 10.310144223761654, + "normal": "rt8" + }, + "camera": { + "r_max_m": 95.8, + "r_max_forward_m": 198.4 + }, + "cards": [ + { + "near_m": null, + "far_m": 12741.776324217612 + }, + { + "near_m": 12741.776324217612, + "far_m": 19190.966661904076 + }, + { + "near_m": 19190.966661904076, + "far_m": 28904.38444742736 + }, + { + "near_m": 28904.38444742736, + "far_m": null + } + ], + "tiles": [ + [ + { + "top": 331, + "h": 269, + "distance_m": 1563.0859375, + "colour": { + "file": "card-0-t00-colour.webp", + "bytes": 1064 + }, + "geometry": { + "file": "card-0-t00-geometry.webp", + "bytes": 24708 + } + }, + { + "top": 386, + "h": 214, + "distance_m": 12087.9375, + "colour": { + "file": "card-1-t00-colour.webp", + "bytes": 688 + }, + "geometry": { + "file": "card-1-t00-geometry.webp", + "bytes": 2540 + } + }, + { + "top": 410, + "h": 190, + "distance_m": 19672.74609375, + "colour": { + "file": "card-2-t00-colour.webp", + "bytes": 950 + }, + "geometry": { + "file": "card-2-t00-geometry.webp", + "bytes": 7464 + } + }, + { + "top": 423, + "h": 177, + "distance_m": 28594.23828125, + "colour": { + "file": "card-3-t00-colour.webp", + "bytes": 428 + }, + "geometry": { + "file": "card-3-t00-geometry.webp", + "bytes": 420 + } + } + ], + [ + { + "top": 338, + "h": 262, + "distance_m": 1620.000244140625, + "colour": { + "file": "card-0-t01-colour.webp", + "bytes": 1156 + }, + "geometry": { + "file": "card-0-t01-geometry.webp", + "bytes": 25874 + } + }, + { + "top": 378, + "h": 222, + "distance_m": 13092.62109375, + "colour": { + "file": "card-1-t01-colour.webp", + "bytes": 1014 + }, + "geometry": { + "file": "card-1-t01-geometry.webp", + "bytes": 9498 + } + }, + { + "top": 406, + "h": 194, + "distance_m": 18308.744140625, + "colour": { + "file": "card-2-t01-colour.webp", + "bytes": 474 + }, + "geometry": { + "file": "card-2-t01-geometry.webp", + "bytes": 498 + } + }, + { + "top": 423, + "h": 177, + "distance_m": 26966.732421875, + "colour": { + "file": "card-3-t01-colour.webp", + "bytes": 362 + }, + "geometry": { + "file": "card-3-t01-geometry.webp", + "bytes": 46 + } + } + ], + [ + { + "top": 353, + "h": 247, + "distance_m": 2692.403564453125, + "colour": { + "file": "card-0-t02-colour.webp", + "bytes": 1228 + }, + "geometry": { + "file": "card-0-t02-geometry.webp", + "bytes": 24332 + } + }, + { + "top": 382, + "h": 218, + "distance_m": 16212.6201171875, + "colour": { + "file": "card-1-t02-colour.webp", + "bytes": 678 + }, + "geometry": { + "file": "card-1-t02-geometry.webp", + "bytes": 224 + } + }, + { + "top": 406, + "h": 194, + "distance_m": 17946.91796875, + "colour": { + "file": "card-2-t02-colour.webp", + "bytes": 524 + }, + "geometry": { + "file": "card-2-t02-geometry.webp", + "bytes": 152 + } + }, + { + "top": 424, + "h": 176, + "distance_m": 26966.732421875, + "colour": { + "file": "card-3-t02-colour.webp", + "bytes": 280 + }, + "geometry": { + "file": "card-3-t02-geometry.webp", + "bytes": 46 + } + } + ], + [ + { + "top": 349, + "h": 251, + "distance_m": 5589.978515625, + "colour": { + "file": "card-0-t03-colour.webp", + "bytes": 1156 + }, + "geometry": { + "file": "card-0-t03-geometry.webp", + "bytes": 26140 + } + }, + { + "top": 385, + "h": 215, + "distance_m": 11896.4462890625, + "colour": { + "file": "card-1-t03-colour.webp", + "bytes": 436 + }, + "geometry": { + "file": "card-1-t03-geometry.webp", + "bytes": 72 + } + }, + { + "top": 409, + "h": 191, + "distance_m": 18148.931640625, + "colour": { + "file": "card-2-t03-colour.webp", + "bytes": 530 + }, + "geometry": { + "file": "card-2-t03-geometry.webp", + "bytes": 2094 + } + }, + { + "top": 424, + "h": 176, + "distance_m": 29900.13671875, + "colour": { + "file": "card-3-t03-colour.webp", + "bytes": 264 + }, + "geometry": { + "file": "card-3-t03-geometry.webp", + "bytes": 114 + } + } + ], + [ + { + "top": 326, + "h": 274, + "distance_m": 5400.00048828125, + "colour": { + "file": "card-0-t04-colour.webp", + "bytes": 1428 + }, + "geometry": { + "file": "card-0-t04-geometry.webp", + "bytes": 23666 + } + }, + { + "top": 387, + "h": 213, + "distance_m": 11896.4462890625, + "colour": { + "file": "card-1-t04-colour.webp", + "bytes": 280 + }, + "geometry": { + "file": "card-1-t04-geometry.webp", + "bytes": 72 + } + }, + { + "top": 414, + "h": 186, + "distance_m": 18644.55078125, + "colour": { + "file": "card-2-t04-colour.webp", + "bytes": 868 + }, + "geometry": { + "file": "card-2-t04-geometry.webp", + "bytes": 5726 + } + }, + { + "top": 427, + "h": 173, + "distance_m": 26966.732421875, + "colour": { + "file": "card-3-t04-colour.webp", + "bytes": 260 + }, + "geometry": { + "file": "card-3-t04-geometry.webp", + "bytes": 116 + } + } + ], + [ + { + "top": 296, + "h": 304, + "distance_m": 6250.08154296875, + "colour": { + "file": "card-0-t05-colour.webp", + "bytes": 1668 + }, + "geometry": { + "file": "card-0-t05-geometry.webp", + "bytes": 17214 + } + }, + { + "top": 390, + "h": 210, + "distance_m": 11934.1728515625, + "colour": { + "file": "card-1-t05-colour.webp", + "bytes": 332 + }, + "geometry": { + "file": "card-1-t05-geometry.webp", + "bytes": 200 + } + }, + { + "top": 415, + "h": 185, + "distance_m": 19785.46875, + "colour": { + "file": "card-2-t05-colour.webp", + "bytes": 462 + }, + "geometry": { + "file": "card-2-t05-geometry.webp", + "bytes": 588 + } + }, + { + "top": 429, + "h": 171, + "distance_m": 26966.732421875, + "colour": { + "file": "card-3-t05-colour.webp", + "bytes": 318 + }, + "geometry": { + "file": "card-3-t05-geometry.webp", + "bytes": 122 + } + } + ], + [ + { + "top": 240, + "h": 360, + "distance_m": 4626.02001953125, + "colour": { + "file": "card-0-t06-colour.webp", + "bytes": 1558 + }, + "geometry": { + "file": "card-0-t06-geometry.webp", + "bytes": 11530 + } + }, + { + "top": 394, + "h": 206, + "distance_m": 11896.4462890625, + "colour": { + "file": "card-1-t06-colour.webp", + "bytes": 364 + }, + "geometry": { + "file": "card-1-t06-geometry.webp", + "bytes": 96 + } + }, + { + "top": 418, + "h": 182, + "distance_m": 17946.91796875, + "colour": { + "file": "card-2-t06-colour.webp", + "bytes": 322 + }, + "geometry": { + "file": "card-2-t06-geometry.webp", + "bytes": 66 + } + }, + { + "top": 429, + "h": 171, + "distance_m": 27179.58203125, + "colour": { + "file": "card-3-t06-colour.webp", + "bytes": 356 + }, + "geometry": { + "file": "card-3-t06-geometry.webp", + "bytes": 228 + } + } + ], + [ + { + "top": 168, + "h": 432, + "distance_m": 580.0, + "colour": { + "file": "card-0-t07-colour.webp", + "bytes": 1522 + }, + "geometry": { + "file": "card-0-t07-geometry.webp", + "bytes": 3948 + } + }, + { + "top": 399, + "h": 201, + "distance_m": 11896.4462890625, + "colour": { + "file": "card-1-t07-colour.webp", + "bytes": 338 + }, + "geometry": { + "file": "card-1-t07-geometry.webp", + "bytes": 106 + } + }, + { + "top": 421, + "h": 179, + "distance_m": 18163.146484375, + "colour": { + "file": "card-2-t07-colour.webp", + "bytes": 436 + }, + "geometry": { + "file": "card-2-t07-geometry.webp", + "bytes": 1330 + } + }, + { + "top": 432, + "h": 168, + "distance_m": 27182.900390625, + "colour": { + "file": "card-3-t07-colour.webp", + "bytes": 216 + }, + "geometry": { + "file": "card-3-t07-geometry.webp", + "bytes": 134 + } + } + ], + [ + { + "top": 66, + "h": 534, + "distance_m": 557.5186157226562, + "colour": { + "file": "card-0-t08-colour.webp", + "bytes": 1704 + }, + "geometry": { + "file": "card-0-t08-geometry.webp", + "bytes": 4234 + } + }, + { + "top": 394, + "h": 206, + "distance_m": 11896.4462890625, + "colour": { + "file": "card-1-t08-colour.webp", + "bytes": 318 + }, + "geometry": { + "file": "card-1-t08-geometry.webp", + "bytes": 164 + } + }, + { + "top": 420, + "h": 180, + "distance_m": 18251.51171875, + "colour": { + "file": "card-2-t08-colour.webp", + "bytes": 990 + }, + "geometry": { + "file": "card-2-t08-geometry.webp", + "bytes": 3768 + } + }, + { + "top": 431, + "h": 169, + "distance_m": 26966.732421875, + "colour": { + "file": "card-3-t08-colour.webp", + "bytes": 286 + }, + "geometry": { + "file": "card-3-t08-geometry.webp", + "bytes": 46 + } + } + ], + [ + { + "top": 24, + "h": 576, + "distance_m": 527.2847290039062, + "colour": { + "file": "card-0-t09-colour.webp", + "bytes": 1224 + }, + "geometry": { + "file": "card-0-t09-geometry.webp", + "bytes": 4474 + } + }, + { + "top": 391, + "h": 209, + "distance_m": 12120.7451171875, + "colour": { + "file": "card-1-t09-colour.webp", + "bytes": 312 + }, + "geometry": { + "file": "card-1-t09-geometry.webp", + "bytes": 160 + } + }, + { + "top": 415, + "h": 185, + "distance_m": 18090.78125, + "colour": { + "file": "card-2-t09-colour.webp", + "bytes": 442 + }, + "geometry": { + "file": "card-2-t09-geometry.webp", + "bytes": 1402 + } + }, + { + "top": 431, + "h": 169, + "distance_m": 26966.732421875, + "colour": { + "file": "card-3-t09-colour.webp", + "bytes": 306 + }, + "geometry": { + "file": "card-3-t09-geometry.webp", + "bytes": 46 + } + } + ], + [ + { + "top": 24, + "h": 576, + "distance_m": 579.9200439453125, + "colour": { + "file": "card-0-t10-colour.webp", + "bytes": 1336 + }, + "geometry": { + "file": "card-0-t10-geometry.webp", + "bytes": 8156 + } + }, + { + "top": 388, + "h": 212, + "distance_m": 11896.4462890625, + "colour": { + "file": "card-1-t10-colour.webp", + "bytes": 314 + }, + "geometry": { + "file": "card-1-t10-geometry.webp", + "bytes": 110 + } + }, + { + "top": 415, + "h": 185, + "distance_m": 18521.453125, + "colour": { + "file": "card-2-t10-colour.webp", + "bytes": 840 + }, + "geometry": { + "file": "card-2-t10-geometry.webp", + "bytes": 4534 + } + }, + { + "top": 428, + "h": 172, + "distance_m": 27291.634765625, + "colour": { + "file": "card-3-t10-colour.webp", + "bytes": 400 + }, + "geometry": { + "file": "card-3-t10-geometry.webp", + "bytes": 278 + } + } + ], + [ + { + "top": 53, + "h": 547, + "distance_m": 630.2824096679688, + "colour": { + "file": "card-0-t11-colour.webp", + "bytes": 1366 + }, + "geometry": { + "file": "card-0-t11-geometry.webp", + "bytes": 11310 + } + }, + { + "top": 369, + "h": 231, + "distance_m": 12087.9375, + "colour": { + "file": "card-1-t11-colour.webp", + "bytes": 688 + }, + "geometry": { + "file": "card-1-t11-geometry.webp", + "bytes": 660 + } + }, + { + "top": 409, + "h": 191, + "distance_m": 18737.1328125, + "colour": { + "file": "card-2-t11-colour.webp", + "bytes": 528 + }, + "geometry": { + "file": "card-2-t11-geometry.webp", + "bytes": 1636 + } + }, + { + "top": 412, + "h": 188, + "distance_m": 27481.455078125, + "colour": { + "file": "card-3-t11-colour.webp", + "bytes": 724 + }, + "geometry": { + "file": "card-3-t11-geometry.webp", + "bytes": 1352 + } + } + ], + [ + { + "top": 82, + "h": 518, + "distance_m": 727.6077880859375, + "colour": { + "file": "card-0-t12-colour.webp", + "bytes": 1272 + }, + "geometry": { + "file": "card-0-t12-geometry.webp", + "bytes": 11624 + } + }, + { + "top": 367, + "h": 233, + "distance_m": 11896.4462890625, + "colour": { + "file": "card-1-t12-colour.webp", + "bytes": 428 + }, + "geometry": { + "file": "card-1-t12-geometry.webp", + "bytes": 72 + } + }, + { + "top": 403, + "h": 197, + "distance_m": 23856.0, + "colour": { + "file": "card-2-t12-colour.webp", + "bytes": 450 + }, + "geometry": { + "file": "card-2-t12-geometry.webp", + "bytes": 386 + } + }, + { + "top": 412, + "h": 188, + "distance_m": 26966.732421875, + "colour": { + "file": "card-3-t12-colour.webp", + "bytes": 446 + }, + "geometry": { + "file": "card-3-t12-geometry.webp", + "bytes": 146 + } + } + ], + [ + { + "top": 67, + "h": 533, + "distance_m": 774.0208740234375, + "colour": { + "file": "card-0-t13-colour.webp", + "bytes": 1234 + }, + "geometry": { + "file": "card-0-t13-geometry.webp", + "bytes": 13684 + } + }, + { + "top": 368, + "h": 232, + "distance_m": 11896.4462890625, + "colour": { + "file": "card-1-t13-colour.webp", + "bytes": 672 + }, + "geometry": { + "file": "card-1-t13-geometry.webp", + "bytes": 84 + } + }, + { + "top": 402, + "h": 198, + "distance_m": 20803.544921875, + "colour": { + "file": "card-2-t13-colour.webp", + "bytes": 408 + }, + "geometry": { + "file": "card-2-t13-geometry.webp", + "bytes": 468 + } + }, + { + "top": 414, + "h": 186, + "distance_m": 26966.732421875, + "colour": { + "file": "card-3-t13-colour.webp", + "bytes": 396 + }, + "geometry": { + "file": "card-3-t13-geometry.webp", + "bytes": 76 + } + } + ], + [ + { + "top": 81, + "h": 519, + "distance_m": 713.8606567382812, + "colour": { + "file": "card-0-t14-colour.webp", + "bytes": 1300 + }, + "geometry": { + "file": "card-0-t14-geometry.webp", + "bytes": 18872 + } + }, + { + "top": 369, + "h": 231, + "distance_m": 11896.4462890625, + "colour": { + "file": "card-1-t14-colour.webp", + "bytes": 414 + }, + "geometry": { + "file": "card-1-t14-geometry.webp", + "bytes": 76 + } + }, + { + "top": 399, + "h": 201, + "distance_m": 20683.802734375, + "colour": { + "file": "card-2-t14-colour.webp", + "bytes": 514 + }, + "geometry": { + "file": "card-2-t14-geometry.webp", + "bytes": 892 + } + }, + { + "top": 414, + "h": 186, + "distance_m": 26966.732421875, + "colour": { + "file": "card-3-t14-colour.webp", + "bytes": 216 + }, + "geometry": { + "file": "card-3-t14-geometry.webp", + "bytes": 48 + } + } + ], + [ + { + "top": 117, + "h": 483, + "distance_m": 699.9999389648438, + "colour": { + "file": "card-0-t15-colour.webp", + "bytes": 1420 + }, + "geometry": { + "file": "card-0-t15-geometry.webp", + "bytes": 17850 + } + }, + { + "top": 369, + "h": 231, + "distance_m": 11896.4462890625, + "colour": { + "file": "card-1-t15-colour.webp", + "bytes": 522 + }, + "geometry": { + "file": "card-1-t15-geometry.webp", + "bytes": 50 + } + }, + { + "top": 397, + "h": 203, + "distance_m": 20034.69921875, + "colour": { + "file": "card-2-t15-colour.webp", + "bytes": 490 + }, + "geometry": { + "file": "card-2-t15-geometry.webp", + "bytes": 1432 + } + }, + { + "top": 414, + "h": 186, + "distance_m": 26966.732421875, + "colour": { + "file": "card-3-t15-colour.webp", + "bytes": 206 + }, + "geometry": { + "file": "card-3-t15-geometry.webp", + "bytes": 48 + } + } + ], + [ + { + "top": 228, + "h": 372, + "distance_m": 902.6199951171875, + "colour": { + "file": "card-0-t16-colour.webp", + "bytes": 1294 + }, + "geometry": { + "file": "card-0-t16-geometry.webp", + "bytes": 15780 + } + }, + { + "top": 366, + "h": 234, + "distance_m": 11896.4462890625, + "colour": { + "file": "card-1-t16-colour.webp", + "bytes": 486 + }, + "geometry": { + "file": "card-1-t16-geometry.webp", + "bytes": 68 + } + }, + { + "top": 393, + "h": 207, + "distance_m": 19963.576171875, + "colour": { + "file": "card-2-t16-colour.webp", + "bytes": 550 + }, + "geometry": { + "file": "card-2-t16-geometry.webp", + "bytes": 1096 + } + }, + { + "top": 415, + "h": 185, + "distance_m": 26966.732421875, + "colour": { + "file": "card-3-t16-colour.webp", + "bytes": 360 + }, + "geometry": { + "file": "card-3-t16-geometry.webp", + "bytes": 48 + } + } + ], + [ + { + "top": 273, + "h": 327, + "distance_m": 4008.74755859375, + "colour": { + "file": "card-0-t17-colour.webp", + "bytes": 1174 + }, + "geometry": { + "file": "card-0-t17-geometry.webp", + "bytes": 18432 + } + }, + { + "top": 363, + "h": 237, + "distance_m": 11896.4462890625, + "colour": { + "file": "card-1-t17-colour.webp", + "bytes": 282 + }, + "geometry": { + "file": "card-1-t17-geometry.webp", + "bytes": 72 + } + }, + { + "top": 387, + "h": 213, + "distance_m": 18090.78125, + "colour": { + "file": "card-2-t17-colour.webp", + "bytes": 386 + }, + "geometry": { + "file": "card-2-t17-geometry.webp", + "bytes": 282 + } + }, + { + "top": 414, + "h": 186, + "distance_m": 26966.732421875, + "colour": { + "file": "card-3-t17-colour.webp", + "bytes": 212 + }, + "geometry": { + "file": "card-3-t17-geometry.webp", + "bytes": 48 + } + } + ], + [ + { + "top": 300, + "h": 300, + "distance_m": 540.0000610351562, + "colour": { + "file": "card-0-t18-colour.webp", + "bytes": 716 + }, + "geometry": { + "file": "card-0-t18-geometry.webp", + "bytes": 13732 + } + }, + { + "top": 362, + "h": 238, + "distance_m": 11896.4462890625, + "colour": { + "file": "card-1-t18-colour.webp", + "bytes": 304 + }, + "geometry": { + "file": "card-1-t18-geometry.webp", + "bytes": 62 + } + }, + { + "top": 386, + "h": 214, + "distance_m": 17946.91796875, + "colour": { + "file": "card-2-t18-colour.webp", + "bytes": 244 + }, + "geometry": { + "file": "card-2-t18-geometry.webp", + "bytes": 58 + } + }, + { + "top": 414, + "h": 186, + "distance_m": 26966.732421875, + "colour": { + "file": "card-3-t18-colour.webp", + "bytes": 212 + }, + "geometry": { + "file": "card-3-t18-geometry.webp", + "bytes": 48 + } + } + ], + [ + { + "top": 324, + "h": 276, + "distance_m": 533.6065673828125, + "colour": { + "file": "card-0-t19-colour.webp", + "bytes": 632 + }, + "geometry": { + "file": "card-0-t19-geometry.webp", + "bytes": 8752 + } + }, + { + "top": 362, + "h": 238, + "distance_m": 13381.708984375, + "colour": { + "file": "card-1-t19-colour.webp", + "bytes": 958 + }, + "geometry": { + "file": "card-1-t19-geometry.webp", + "bytes": 2906 + } + }, + { + "top": 387, + "h": 213, + "distance_m": 17946.91796875, + "colour": { + "file": "card-2-t19-colour.webp", + "bytes": 222 + }, + "geometry": { + "file": "card-2-t19-geometry.webp", + "bytes": 48 + } + }, + { + "top": 414, + "h": 186, + "distance_m": 26966.732421875, + "colour": { + "file": "card-3-t19-colour.webp", + "bytes": 250 + }, + "geometry": { + "file": "card-3-t19-geometry.webp", + "bytes": 48 + } + } + ], + [ + { + "top": 349, + "h": 251, + "distance_m": 528.2322387695312, + "colour": { + "file": "card-0-t20-colour.webp", + "bytes": 588 + }, + "geometry": { + "file": "card-0-t20-geometry.webp", + "bytes": 5564 + } + }, + { + "top": 375, + "h": 225, + "distance_m": 13652.9033203125, + "colour": { + "file": "card-1-t20-colour.webp", + "bytes": 1170 + }, + "geometry": { + "file": "card-1-t20-geometry.webp", + "bytes": 12072 + } + }, + { + "top": 387, + "h": 213, + "distance_m": 17946.91796875, + "colour": { + "file": "card-2-t20-colour.webp", + "bytes": 242 + }, + "geometry": { + "file": "card-2-t20-geometry.webp", + "bytes": 92 + } + }, + { + "top": 415, + "h": 185, + "distance_m": 26966.732421875, + "colour": { + "file": "card-3-t20-colour.webp", + "bytes": 590 + }, + "geometry": { + "file": "card-3-t20-geometry.webp", + "bytes": 48 + } + } + ], + [ + { + "top": 362, + "h": 238, + "distance_m": 548.2117919921875, + "colour": { + "file": "card-0-t21-colour.webp", + "bytes": 718 + }, + "geometry": { + "file": "card-0-t21-geometry.webp", + "bytes": 6532 + } + }, + { + "top": 380, + "h": 220, + "distance_m": 14602.0859375, + "colour": { + "file": "card-1-t21-colour.webp", + "bytes": 2110 + }, + "geometry": { + "file": "card-1-t21-geometry.webp", + "bytes": 10528 + } + }, + { + "top": 388, + "h": 212, + "distance_m": 18265.353515625, + "colour": { + "file": "card-2-t21-colour.webp", + "bytes": 776 + }, + "geometry": { + "file": "card-2-t21-geometry.webp", + "bytes": 4600 + } + }, + { + "top": 416, + "h": 184, + "distance_m": 26966.732421875, + "colour": { + "file": "card-3-t21-colour.webp", + "bytes": 374 + }, + "geometry": { + "file": "card-3-t21-geometry.webp", + "bytes": 48 + } + } + ], + [ + { + "top": 352, + "h": 248, + "distance_m": 573.6212158203125, + "colour": { + "file": "card-0-t22-colour.webp", + "bytes": 1126 + }, + "geometry": { + "file": "card-0-t22-geometry.webp", + "bytes": 13124 + } + }, + { + "top": 391, + "h": 209, + "distance_m": 16038.8134765625, + "colour": { + "file": "card-1-t22-colour.webp", + "bytes": 2864 + }, + "geometry": { + "file": "card-1-t22-geometry.webp", + "bytes": 12814 + } + }, + { + "top": 391, + "h": 209, + "distance_m": 18698.236328125, + "colour": { + "file": "card-2-t22-colour.webp", + "bytes": 994 + }, + "geometry": { + "file": "card-2-t22-geometry.webp", + "bytes": 7916 + } + }, + { + "top": 415, + "h": 185, + "distance_m": 26966.732421875, + "colour": { + "file": "card-3-t22-colour.webp", + "bytes": 570 + }, + "geometry": { + "file": "card-3-t22-geometry.webp", + "bytes": 58 + } + } + ], + [ + { + "top": 308, + "h": 292, + "distance_m": 4001.017333984375, + "colour": { + "file": "card-0-t23-colour.webp", + "bytes": 1436 + }, + "geometry": { + "file": "card-0-t23-geometry.webp", + "bytes": 24328 + } + }, + { + "top": 395, + "h": 205, + "distance_m": 13116.75390625, + "colour": { + "file": "card-1-t23-colour.webp", + "bytes": 1740 + }, + "geometry": { + "file": "card-1-t23-geometry.webp", + "bytes": 8016 + } + }, + { + "top": 395, + "h": 205, + "distance_m": 19894.794921875, + "colour": { + "file": "card-2-t23-colour.webp", + "bytes": 1066 + }, + "geometry": { + "file": "card-2-t23-geometry.webp", + "bytes": 5726 + } + }, + { + "top": 413, + "h": 187, + "distance_m": 28205.7734375, + "colour": { + "file": "card-3-t23-colour.webp", + "bytes": 610 + }, + "geometry": { + "file": "card-3-t23-geometry.webp", + "bytes": 194 + } + } + ], + [ + { + "top": 293, + "h": 307, + "distance_m": 2579.48681640625, + "colour": { + "file": "card-0-t24-colour.webp", + "bytes": 1744 + }, + "geometry": { + "file": "card-0-t24-geometry.webp", + "bytes": 32102 + } + }, + { + "top": 374, + "h": 226, + "distance_m": 12125.716796875, + "colour": { + "file": "card-1-t24-colour.webp", + "bytes": 970 + }, + "geometry": { + "file": "card-1-t24-geometry.webp", + "bytes": 3954 + } + }, + { + "top": 420, + "h": 180, + "distance_m": 19130.62890625, + "colour": { + "file": "card-2-t24-colour.webp", + "bytes": 822 + }, + "geometry": { + "file": "card-2-t24-geometry.webp", + "bytes": 2584 + } + }, + { + "top": 425, + "h": 175, + "distance_m": 28424.0390625, + "colour": { + "file": "card-3-t24-colour.webp", + "bytes": 788 + }, + "geometry": { + "file": "card-3-t24-geometry.webp", + "bytes": 3666 + } + } + ], + [ + { + "top": 322, + "h": 278, + "distance_m": 1288.96923828125, + "colour": { + "file": "card-0-t25-colour.webp", + "bytes": 1714 + }, + "geometry": { + "file": "card-0-t25-geometry.webp", + "bytes": 32830 + } + }, + { + "top": 386, + "h": 214, + "distance_m": 13197.5732421875, + "colour": { + "file": "card-1-t25-colour.webp", + "bytes": 1190 + }, + "geometry": { + "file": "card-1-t25-geometry.webp", + "bytes": 6308 + } + }, + { + "top": 404, + "h": 196, + "distance_m": 22927.611328125, + "colour": { + "file": "card-2-t25-colour.webp", + "bytes": 1144 + }, + "geometry": { + "file": "card-2-t25-geometry.webp", + "bytes": 1844 + } + }, + { + "top": 409, + "h": 191, + "distance_m": 28034.6015625, + "colour": { + "file": "card-3-t25-colour.webp", + "bytes": 1058 + }, + "geometry": { + "file": "card-3-t25-geometry.webp", + "bytes": 4570 + } + } + ], + [ + { + "top": 313, + "h": 287, + "distance_m": 1936.9310302734375, + "colour": { + "file": "card-0-t26-colour.webp", + "bytes": 1708 + }, + "geometry": { + "file": "card-0-t26-geometry.webp", + "bytes": 33300 + } + }, + { + "top": 341, + "h": 259, + "distance_m": 12153.501953125, + "colour": { + "file": "card-1-t26-colour.webp", + "bytes": 808 + }, + "geometry": { + "file": "card-1-t26-geometry.webp", + "bytes": 2644 + } + }, + { + "top": 386, + "h": 214, + "distance_m": 21626.201171875, + "colour": { + "file": "card-2-t26-colour.webp", + "bytes": 1238 + }, + "geometry": { + "file": "card-2-t26-geometry.webp", + "bytes": 4116 + } + }, + { + "top": 403, + "h": 197, + "distance_m": 27097.666015625, + "colour": { + "file": "card-3-t26-colour.webp", + "bytes": 432 + }, + "geometry": { + "file": "card-3-t26-geometry.webp", + "bytes": 184 + } + } + ], + [ + { + "top": 313, + "h": 287, + "distance_m": 1789.509033203125, + "colour": { + "file": "card-0-t27-colour.webp", + "bytes": 1118 + }, + "geometry": { + "file": "card-0-t27-geometry.webp", + "bytes": 29232 + } + }, + { + "top": 339, + "h": 261, + "distance_m": 11896.4462890625, + "colour": { + "file": "card-1-t27-colour.webp", + "bytes": 302 + }, + "geometry": { + "file": "card-1-t27-geometry.webp", + "bytes": 136 + } + }, + { + "top": 375, + "h": 225, + "distance_m": 22704.583984375, + "colour": { + "file": "card-2-t27-colour.webp", + "bytes": 916 + }, + "geometry": { + "file": "card-2-t27-geometry.webp", + "bytes": 1298 + } + }, + { + "top": 398, + "h": 202, + "distance_m": 26966.732421875, + "colour": { + "file": "card-3-t27-colour.webp", + "bytes": 278 + }, + "geometry": { + "file": "card-3-t27-geometry.webp", + "bytes": 152 + } + } + ], + [ + { + "top": 286, + "h": 314, + "distance_m": 1824.2069091796875, + "colour": { + "file": "card-0-t28-colour.webp", + "bytes": 1422 + }, + "geometry": { + "file": "card-0-t28-geometry.webp", + "bytes": 32734 + } + }, + { + "top": 338, + "h": 262, + "distance_m": 12100.0244140625, + "colour": { + "file": "card-1-t28-colour.webp", + "bytes": 678 + }, + "geometry": { + "file": "card-1-t28-geometry.webp", + "bytes": 2906 + } + }, + { + "top": 372, + "h": 228, + "distance_m": 17946.91796875, + "colour": { + "file": "card-2-t28-colour.webp", + "bytes": 278 + }, + "geometry": { + "file": "card-2-t28-geometry.webp", + "bytes": 126 + } + }, + { + "top": 395, + "h": 205, + "distance_m": 27400.80078125, + "colour": { + "file": "card-3-t28-colour.webp", + "bytes": 292 + }, + "geometry": { + "file": "card-3-t28-geometry.webp", + "bytes": 232 + } + } + ], + [ + { + "top": 259, + "h": 341, + "distance_m": 1952.825439453125, + "colour": { + "file": "card-0-t29-colour.webp", + "bytes": 1474 + }, + "geometry": { + "file": "card-0-t29-geometry.webp", + "bytes": 35160 + } + }, + { + "top": 341, + "h": 259, + "distance_m": 12648.30078125, + "colour": { + "file": "card-1-t29-colour.webp", + "bytes": 1260 + }, + "geometry": { + "file": "card-1-t29-geometry.webp", + "bytes": 8392 + } + }, + { + "top": 372, + "h": 228, + "distance_m": 18018.396484375, + "colour": { + "file": "card-2-t29-colour.webp", + "bytes": 640 + }, + "geometry": { + "file": "card-2-t29-geometry.webp", + "bytes": 630 + } + }, + { + "top": 395, + "h": 205, + "distance_m": 27240.720703125, + "colour": { + "file": "card-3-t29-colour.webp", + "bytes": 414 + }, + "geometry": { + "file": "card-3-t29-geometry.webp", + "bytes": 1446 + } + } + ], + [ + { + "top": 293, + "h": 307, + "distance_m": 1380.0001220703125, + "colour": { + "file": "card-0-t30-colour.webp", + "bytes": 1314 + }, + "geometry": { + "file": "card-0-t30-geometry.webp", + "bytes": 28478 + } + }, + { + "top": 358, + "h": 242, + "distance_m": 12885.2138671875, + "colour": { + "file": "card-1-t30-colour.webp", + "bytes": 1170 + }, + "geometry": { + "file": "card-1-t30-geometry.webp", + "bytes": 7834 + } + }, + { + "top": 392, + "h": 208, + "distance_m": 18018.70703125, + "colour": { + "file": "card-2-t30-colour.webp", + "bytes": 914 + }, + "geometry": { + "file": "card-2-t30-geometry.webp", + "bytes": 1218 + } + }, + { + "top": 400, + "h": 200, + "distance_m": 27202.21875, + "colour": { + "file": "card-3-t30-colour.webp", + "bytes": 850 + }, + "geometry": { + "file": "card-3-t30-geometry.webp", + "bytes": 1606 + } + } + ], + [ + { + "top": 299, + "h": 301, + "distance_m": 1280.1490478515625, + "colour": { + "file": "card-0-t31-colour.webp", + "bytes": 1124 + }, + "geometry": { + "file": "card-0-t31-geometry.webp", + "bytes": 24824 + } + }, + { + "top": 376, + "h": 224, + "distance_m": 12544.7021484375, + "colour": { + "file": "card-1-t31-colour.webp", + "bytes": 1176 + }, + "geometry": { + "file": "card-1-t31-geometry.webp", + "bytes": 7268 + } + }, + { + "top": 410, + "h": 190, + "distance_m": 20441.794921875, + "colour": { + "file": "card-2-t31-colour.webp", + "bytes": 1130 + }, + "geometry": { + "file": "card-2-t31-geometry.webp", + "bytes": 5750 + } + }, + { + "top": 411, + "h": 189, + "distance_m": 27730.93359375, + "colour": { + "file": "card-3-t31-colour.webp", + "bytes": 818 + }, + "geometry": { + "file": "card-3-t31-geometry.webp", + "bytes": 1224 + } + } + ] + ], + "bytes": 889956, + "attribution": { + "credit_line": "Contains modified Copernicus data: DEM \u00a9 DLR e.V. 2010-2014 and \u00a9 Airbus Defence and Space GmbH 2014-2018 provided under COPERNICUS by the European Union and ESA; all rights reserved.", + "licence": "Copernicus DEM licence: free, full and open access, with the credit line shown", + "dem_source": "Copernicus DEM GLO-30 (30 m)", + "url": "https://spacedata.copernicus.eu/collections/copernicus-digital-elevation-model" + } +} diff --git a/public/ridge/index.json b/public/ridge/index.json new file mode 100644 index 00000000..1b522087 --- /dev/null +++ b/public/ridge/index.json @@ -0,0 +1,11 @@ +{ + "schema": 1, + "default": "vienna", + "places": { + "vienna": "vienna-f50ec31ee950", + "fuji": "fuji-8dac36611b90", + "matterhorn": "matterhorn-f4fa1ba3556c", + "amadablam": "amadablam-fb4b9d3701f8", + "grandcanyon": "grandcanyon-dcfa7cc15fdd" + } +} diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t00-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t00-colour.webp new file mode 100644 index 00000000..c173391d Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t00-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t00-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t00-geometry.webp new file mode 100644 index 00000000..b307fd19 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t00-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t01-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t01-colour.webp new file mode 100644 index 00000000..4feed37d Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t01-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t01-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t01-geometry.webp new file mode 100644 index 00000000..b8753439 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t01-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t02-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t02-colour.webp new file mode 100644 index 00000000..a7694a1f Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t02-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t02-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t02-geometry.webp new file mode 100644 index 00000000..14e07e74 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t02-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t03-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t03-colour.webp new file mode 100644 index 00000000..e960d331 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t03-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t03-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t03-geometry.webp new file mode 100644 index 00000000..6b65138f Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t03-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t04-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t04-colour.webp new file mode 100644 index 00000000..bad5a964 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t04-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t04-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t04-geometry.webp new file mode 100644 index 00000000..1b523f03 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t04-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t05-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t05-colour.webp new file mode 100644 index 00000000..2e0876cb Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t05-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t05-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t05-geometry.webp new file mode 100644 index 00000000..781a5fa7 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t05-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t06-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t06-colour.webp new file mode 100644 index 00000000..f37725fc Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t06-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t06-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t06-geometry.webp new file mode 100644 index 00000000..51bda1e0 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t06-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t07-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t07-colour.webp new file mode 100644 index 00000000..af1a77f9 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t07-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t07-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t07-geometry.webp new file mode 100644 index 00000000..5777463e Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t07-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t08-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t08-colour.webp new file mode 100644 index 00000000..037aa415 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t08-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t08-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t08-geometry.webp new file mode 100644 index 00000000..760b2f51 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t08-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t09-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t09-colour.webp new file mode 100644 index 00000000..ea1f3551 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t09-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t09-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t09-geometry.webp new file mode 100644 index 00000000..1e79ac7d Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t09-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t10-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t10-colour.webp new file mode 100644 index 00000000..d9774521 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t10-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t10-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t10-geometry.webp new file mode 100644 index 00000000..d706dafe Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t10-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t11-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t11-colour.webp new file mode 100644 index 00000000..90e94574 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t11-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t11-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t11-geometry.webp new file mode 100644 index 00000000..1722bfdb Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t11-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t12-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t12-colour.webp new file mode 100644 index 00000000..cea24ecd Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t12-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t12-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t12-geometry.webp new file mode 100644 index 00000000..8e081495 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t12-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t13-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t13-colour.webp new file mode 100644 index 00000000..7de285bc Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t13-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t13-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t13-geometry.webp new file mode 100644 index 00000000..2f69d037 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t13-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t14-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t14-colour.webp new file mode 100644 index 00000000..a605c3e4 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t14-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t14-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t14-geometry.webp new file mode 100644 index 00000000..b74195e9 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t14-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t15-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t15-colour.webp new file mode 100644 index 00000000..c746c2c3 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t15-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t15-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t15-geometry.webp new file mode 100644 index 00000000..2fbfb850 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t15-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t16-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t16-colour.webp new file mode 100644 index 00000000..5b49d603 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t16-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t16-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t16-geometry.webp new file mode 100644 index 00000000..47fc0546 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t16-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t17-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t17-colour.webp new file mode 100644 index 00000000..14304969 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t17-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t17-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t17-geometry.webp new file mode 100644 index 00000000..78374333 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t17-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t18-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t18-colour.webp new file mode 100644 index 00000000..baa9015c Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t18-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t18-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t18-geometry.webp new file mode 100644 index 00000000..29815f06 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t18-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t19-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t19-colour.webp new file mode 100644 index 00000000..1d47b113 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t19-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t19-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t19-geometry.webp new file mode 100644 index 00000000..a04c07db Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t19-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t20-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t20-colour.webp new file mode 100644 index 00000000..bfae6412 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t20-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t20-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t20-geometry.webp new file mode 100644 index 00000000..2dd694b5 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t20-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t21-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t21-colour.webp new file mode 100644 index 00000000..e7ea10ba Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t21-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t21-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t21-geometry.webp new file mode 100644 index 00000000..eb4cc7a3 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t21-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t22-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t22-colour.webp new file mode 100644 index 00000000..ddc5f0bb Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t22-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t22-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t22-geometry.webp new file mode 100644 index 00000000..7df790b6 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t22-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t23-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t23-colour.webp new file mode 100644 index 00000000..0bad763d Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t23-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t23-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t23-geometry.webp new file mode 100644 index 00000000..6028ecc3 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t23-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t24-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t24-colour.webp new file mode 100644 index 00000000..4a07f61c Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t24-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t24-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t24-geometry.webp new file mode 100644 index 00000000..415b7004 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t24-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t25-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t25-colour.webp new file mode 100644 index 00000000..693d5fed Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t25-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t25-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t25-geometry.webp new file mode 100644 index 00000000..dca26970 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t25-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t26-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t26-colour.webp new file mode 100644 index 00000000..61d38177 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t26-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t26-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t26-geometry.webp new file mode 100644 index 00000000..37d8783b Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t26-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t27-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t27-colour.webp new file mode 100644 index 00000000..d3238c33 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t27-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t27-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t27-geometry.webp new file mode 100644 index 00000000..24854685 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t27-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t28-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t28-colour.webp new file mode 100644 index 00000000..bb344d6c Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t28-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t28-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t28-geometry.webp new file mode 100644 index 00000000..0f80cf45 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t28-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t29-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t29-colour.webp new file mode 100644 index 00000000..0c50afa5 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t29-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t29-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t29-geometry.webp new file mode 100644 index 00000000..caa1156a Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t29-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t30-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t30-colour.webp new file mode 100644 index 00000000..68b04fc5 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t30-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t30-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t30-geometry.webp new file mode 100644 index 00000000..7a4bb6f2 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t30-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t31-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t31-colour.webp new file mode 100644 index 00000000..93f88317 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t31-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-0-t31-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t31-geometry.webp new file mode 100644 index 00000000..73867067 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-0-t31-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t00-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t00-colour.webp new file mode 100644 index 00000000..da7d3b5f Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t00-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t00-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t00-geometry.webp new file mode 100644 index 00000000..ed1a33d8 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t00-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t01-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t01-colour.webp new file mode 100644 index 00000000..5d5d53e8 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t01-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t01-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t01-geometry.webp new file mode 100644 index 00000000..e4ab11ed Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t01-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t02-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t02-colour.webp new file mode 100644 index 00000000..fad78400 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t02-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t02-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t02-geometry.webp new file mode 100644 index 00000000..a4e5aa87 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t02-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t03-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t03-colour.webp new file mode 100644 index 00000000..c64c485c Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t03-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t03-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t03-geometry.webp new file mode 100644 index 00000000..8e0ab0f8 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t03-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t04-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t04-colour.webp new file mode 100644 index 00000000..d8a8e317 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t04-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t04-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t04-geometry.webp new file mode 100644 index 00000000..4e869919 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t04-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t05-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t05-colour.webp new file mode 100644 index 00000000..5a3bd786 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t05-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t05-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t05-geometry.webp new file mode 100644 index 00000000..82306738 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t05-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t06-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t06-colour.webp new file mode 100644 index 00000000..dd86e9e4 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t06-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t06-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t06-geometry.webp new file mode 100644 index 00000000..94195d8b Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t06-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t07-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t07-colour.webp new file mode 100644 index 00000000..0f35e691 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t07-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t07-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t07-geometry.webp new file mode 100644 index 00000000..50b7627b Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t07-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t08-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t08-colour.webp new file mode 100644 index 00000000..b0e40c1d Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t08-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t08-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t08-geometry.webp new file mode 100644 index 00000000..af7f5882 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t08-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t09-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t09-colour.webp new file mode 100644 index 00000000..1739d8fd Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t09-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t09-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t09-geometry.webp new file mode 100644 index 00000000..c338c11e Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t09-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t10-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t10-colour.webp new file mode 100644 index 00000000..a2b7ce3b Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t10-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t10-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t10-geometry.webp new file mode 100644 index 00000000..e2cc72e1 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t10-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t11-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t11-colour.webp new file mode 100644 index 00000000..f6d75091 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t11-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t11-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t11-geometry.webp new file mode 100644 index 00000000..8644ac1f Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t11-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t12-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t12-colour.webp new file mode 100644 index 00000000..88156530 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t12-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t12-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t12-geometry.webp new file mode 100644 index 00000000..d5020b21 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t12-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t13-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t13-colour.webp new file mode 100644 index 00000000..893f1005 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t13-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t13-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t13-geometry.webp new file mode 100644 index 00000000..91e7f64d Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t13-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t14-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t14-colour.webp new file mode 100644 index 00000000..762eca45 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t14-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t14-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t14-geometry.webp new file mode 100644 index 00000000..6f6e74a0 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t14-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t15-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t15-colour.webp new file mode 100644 index 00000000..3eeff891 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t15-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t15-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t15-geometry.webp new file mode 100644 index 00000000..31888cb8 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t15-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t16-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t16-colour.webp new file mode 100644 index 00000000..3a0085cc Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t16-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t16-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t16-geometry.webp new file mode 100644 index 00000000..e6d0b342 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t16-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t17-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t17-colour.webp new file mode 100644 index 00000000..ecaed1b4 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t17-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t17-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t17-geometry.webp new file mode 100644 index 00000000..49e2acad Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t17-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t18-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t18-colour.webp new file mode 100644 index 00000000..4fee1e57 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t18-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t18-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t18-geometry.webp new file mode 100644 index 00000000..fcd4b469 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t18-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t19-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t19-colour.webp new file mode 100644 index 00000000..8ac70995 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t19-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t19-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t19-geometry.webp new file mode 100644 index 00000000..0aff65f2 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t19-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t20-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t20-colour.webp new file mode 100644 index 00000000..7e647ec8 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t20-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t20-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t20-geometry.webp new file mode 100644 index 00000000..7621b1dc Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t20-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t21-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t21-colour.webp new file mode 100644 index 00000000..5b877861 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t21-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t21-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t21-geometry.webp new file mode 100644 index 00000000..ff674d72 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t21-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t22-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t22-colour.webp new file mode 100644 index 00000000..a6208ef1 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t22-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t22-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t22-geometry.webp new file mode 100644 index 00000000..7d27887f Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t22-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t23-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t23-colour.webp new file mode 100644 index 00000000..af33f56e Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t23-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t23-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t23-geometry.webp new file mode 100644 index 00000000..8027c0d7 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t23-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t24-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t24-colour.webp new file mode 100644 index 00000000..dfd4a96a Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t24-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t24-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t24-geometry.webp new file mode 100644 index 00000000..f352841d Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t24-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t25-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t25-colour.webp new file mode 100644 index 00000000..c04ba97b Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t25-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t25-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t25-geometry.webp new file mode 100644 index 00000000..94418a77 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t25-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t26-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t26-colour.webp new file mode 100644 index 00000000..eb945dc7 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t26-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t26-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t26-geometry.webp new file mode 100644 index 00000000..357a19e3 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t26-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t27-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t27-colour.webp new file mode 100644 index 00000000..a20b5c60 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t27-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t27-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t27-geometry.webp new file mode 100644 index 00000000..3fe3f0bc Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t27-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t28-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t28-colour.webp new file mode 100644 index 00000000..259f8b1d Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t28-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t28-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t28-geometry.webp new file mode 100644 index 00000000..0c551fce Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t28-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t29-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t29-colour.webp new file mode 100644 index 00000000..0748aea2 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t29-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t29-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t29-geometry.webp new file mode 100644 index 00000000..4490fa54 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t29-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t30-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t30-colour.webp new file mode 100644 index 00000000..e24ccf9c Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t30-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t30-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t30-geometry.webp new file mode 100644 index 00000000..b8d5fbdc Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t30-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t31-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t31-colour.webp new file mode 100644 index 00000000..7605f0f1 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t31-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-1-t31-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t31-geometry.webp new file mode 100644 index 00000000..ac70b30a Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-1-t31-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t00-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t00-colour.webp new file mode 100644 index 00000000..fa9cbde6 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t00-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t00-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t00-geometry.webp new file mode 100644 index 00000000..6b258017 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t00-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t01-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t01-colour.webp new file mode 100644 index 00000000..53d430a5 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t01-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t01-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t01-geometry.webp new file mode 100644 index 00000000..6e3f71c7 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t01-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t02-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t02-colour.webp new file mode 100644 index 00000000..9926656b Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t02-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t02-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t02-geometry.webp new file mode 100644 index 00000000..12446c04 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t02-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t03-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t03-colour.webp new file mode 100644 index 00000000..63fe2211 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t03-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t03-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t03-geometry.webp new file mode 100644 index 00000000..c71e8124 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t03-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t04-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t04-colour.webp new file mode 100644 index 00000000..930918d2 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t04-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t04-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t04-geometry.webp new file mode 100644 index 00000000..bbd52f53 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t04-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t05-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t05-colour.webp new file mode 100644 index 00000000..b8086dda Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t05-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t05-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t05-geometry.webp new file mode 100644 index 00000000..0034898d Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t05-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t06-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t06-colour.webp new file mode 100644 index 00000000..c5f93158 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t06-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t06-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t06-geometry.webp new file mode 100644 index 00000000..5076009e Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t06-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t07-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t07-colour.webp new file mode 100644 index 00000000..701ab7de Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t07-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t07-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t07-geometry.webp new file mode 100644 index 00000000..82c94309 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t07-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t08-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t08-colour.webp new file mode 100644 index 00000000..233541ce Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t08-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t08-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t08-geometry.webp new file mode 100644 index 00000000..3dea5a38 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t08-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t09-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t09-colour.webp new file mode 100644 index 00000000..f1cbd7c5 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t09-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t09-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t09-geometry.webp new file mode 100644 index 00000000..07f5e202 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t09-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t10-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t10-colour.webp new file mode 100644 index 00000000..349f7bfe Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t10-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t10-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t10-geometry.webp new file mode 100644 index 00000000..f71940a7 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t10-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t11-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t11-colour.webp new file mode 100644 index 00000000..62a0448a Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t11-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t11-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t11-geometry.webp new file mode 100644 index 00000000..235d1534 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t11-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t12-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t12-colour.webp new file mode 100644 index 00000000..fa4fb566 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t12-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t12-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t12-geometry.webp new file mode 100644 index 00000000..d03cc8fd Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t12-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t13-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t13-colour.webp new file mode 100644 index 00000000..85656767 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t13-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t13-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t13-geometry.webp new file mode 100644 index 00000000..d0495a71 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t13-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t14-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t14-colour.webp new file mode 100644 index 00000000..09106ff2 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t14-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t14-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t14-geometry.webp new file mode 100644 index 00000000..5d59e676 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t14-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t15-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t15-colour.webp new file mode 100644 index 00000000..399d9e9f Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t15-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t15-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t15-geometry.webp new file mode 100644 index 00000000..39c78fd8 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t15-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t16-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t16-colour.webp new file mode 100644 index 00000000..34916d80 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t16-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t16-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t16-geometry.webp new file mode 100644 index 00000000..0141464c Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t16-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t17-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t17-colour.webp new file mode 100644 index 00000000..fd5aa34c Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t17-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t17-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t17-geometry.webp new file mode 100644 index 00000000..018dd78a Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t17-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t18-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t18-colour.webp new file mode 100644 index 00000000..fcf00415 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t18-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t18-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t18-geometry.webp new file mode 100644 index 00000000..7788a160 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t18-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t19-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t19-colour.webp new file mode 100644 index 00000000..3ca580bc Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t19-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t19-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t19-geometry.webp new file mode 100644 index 00000000..7e58b465 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t19-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t20-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t20-colour.webp new file mode 100644 index 00000000..83d75920 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t20-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t20-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t20-geometry.webp new file mode 100644 index 00000000..008f6b06 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t20-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t21-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t21-colour.webp new file mode 100644 index 00000000..57a8d604 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t21-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t21-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t21-geometry.webp new file mode 100644 index 00000000..863d6b6f Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t21-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t22-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t22-colour.webp new file mode 100644 index 00000000..f1b1f013 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t22-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t22-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t22-geometry.webp new file mode 100644 index 00000000..22d9b34d Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t22-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t23-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t23-colour.webp new file mode 100644 index 00000000..185a406d Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t23-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t23-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t23-geometry.webp new file mode 100644 index 00000000..6cfb4391 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t23-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t24-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t24-colour.webp new file mode 100644 index 00000000..1968682a Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t24-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t24-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t24-geometry.webp new file mode 100644 index 00000000..b3c47663 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t24-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t25-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t25-colour.webp new file mode 100644 index 00000000..407f588c Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t25-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t25-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t25-geometry.webp new file mode 100644 index 00000000..bc9a5a43 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t25-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t26-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t26-colour.webp new file mode 100644 index 00000000..a2aa3a85 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t26-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t26-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t26-geometry.webp new file mode 100644 index 00000000..0428d6a7 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t26-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t27-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t27-colour.webp new file mode 100644 index 00000000..4bfd3e0f Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t27-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t27-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t27-geometry.webp new file mode 100644 index 00000000..0e032949 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t27-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t28-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t28-colour.webp new file mode 100644 index 00000000..950dfda7 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t28-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t28-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t28-geometry.webp new file mode 100644 index 00000000..1021d2c1 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t28-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t29-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t29-colour.webp new file mode 100644 index 00000000..2944b652 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t29-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t29-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t29-geometry.webp new file mode 100644 index 00000000..d99d5d6f Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t29-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t30-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t30-colour.webp new file mode 100644 index 00000000..00da71c7 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t30-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t30-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t30-geometry.webp new file mode 100644 index 00000000..65e9ce2b Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t30-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t31-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t31-colour.webp new file mode 100644 index 00000000..4721ce12 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t31-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-2-t31-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t31-geometry.webp new file mode 100644 index 00000000..1f651ebb Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-2-t31-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t00-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t00-colour.webp new file mode 100644 index 00000000..48cbd186 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t00-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t00-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t00-geometry.webp new file mode 100644 index 00000000..7dec2d16 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t00-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t01-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t01-colour.webp new file mode 100644 index 00000000..ffde24c9 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t01-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t01-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t01-geometry.webp new file mode 100644 index 00000000..659ce87f Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t01-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t02-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t02-colour.webp new file mode 100644 index 00000000..d3d3e7f9 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t02-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t02-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t02-geometry.webp new file mode 100644 index 00000000..1e8de4dd Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t02-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t03-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t03-colour.webp new file mode 100644 index 00000000..329be34a Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t03-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t03-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t03-geometry.webp new file mode 100644 index 00000000..88417117 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t03-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t04-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t04-colour.webp new file mode 100644 index 00000000..3370202a Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t04-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t04-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t04-geometry.webp new file mode 100644 index 00000000..cc4f5f54 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t04-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t05-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t05-colour.webp new file mode 100644 index 00000000..f48f9232 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t05-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t05-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t05-geometry.webp new file mode 100644 index 00000000..06a51e37 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t05-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t06-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t06-colour.webp new file mode 100644 index 00000000..460fd200 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t06-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t06-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t06-geometry.webp new file mode 100644 index 00000000..2c1433ef Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t06-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t07-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t07-colour.webp new file mode 100644 index 00000000..ac10f644 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t07-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t07-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t07-geometry.webp new file mode 100644 index 00000000..bf903c8a Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t07-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t08-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t08-colour.webp new file mode 100644 index 00000000..cc22612f Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t08-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t08-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t08-geometry.webp new file mode 100644 index 00000000..0ad712ec Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t08-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t09-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t09-colour.webp new file mode 100644 index 00000000..c66ec659 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t09-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t09-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t09-geometry.webp new file mode 100644 index 00000000..285b1d1b Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t09-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t10-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t10-colour.webp new file mode 100644 index 00000000..8a915a21 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t10-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t10-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t10-geometry.webp new file mode 100644 index 00000000..b25742dc Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t10-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t11-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t11-colour.webp new file mode 100644 index 00000000..69bf2264 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t11-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t11-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t11-geometry.webp new file mode 100644 index 00000000..52be9f57 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t11-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t12-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t12-colour.webp new file mode 100644 index 00000000..de22ac7f Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t12-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t12-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t12-geometry.webp new file mode 100644 index 00000000..35854887 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t12-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t13-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t13-colour.webp new file mode 100644 index 00000000..ff49516f Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t13-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t13-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t13-geometry.webp new file mode 100644 index 00000000..8b22b55f Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t13-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t14-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t14-colour.webp new file mode 100644 index 00000000..d2fe52ef Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t14-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t14-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t14-geometry.webp new file mode 100644 index 00000000..4c79fb05 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t14-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t15-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t15-colour.webp new file mode 100644 index 00000000..f1ca5156 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t15-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t15-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t15-geometry.webp new file mode 100644 index 00000000..a1883501 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t15-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t16-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t16-colour.webp new file mode 100644 index 00000000..b3e79ec4 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t16-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t16-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t16-geometry.webp new file mode 100644 index 00000000..b6cd82e3 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t16-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t17-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t17-colour.webp new file mode 100644 index 00000000..c3df3db3 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t17-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t17-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t17-geometry.webp new file mode 100644 index 00000000..001a05ad Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t17-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t18-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t18-colour.webp new file mode 100644 index 00000000..7b15e54a Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t18-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t18-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t18-geometry.webp new file mode 100644 index 00000000..13da6721 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t18-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t19-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t19-colour.webp new file mode 100644 index 00000000..cf33cc80 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t19-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t19-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t19-geometry.webp new file mode 100644 index 00000000..365814ea Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t19-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t20-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t20-colour.webp new file mode 100644 index 00000000..245b0d51 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t20-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t20-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t20-geometry.webp new file mode 100644 index 00000000..1c6c39a1 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t20-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t21-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t21-colour.webp new file mode 100644 index 00000000..0e74973a Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t21-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t21-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t21-geometry.webp new file mode 100644 index 00000000..ed3051df Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t21-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t22-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t22-colour.webp new file mode 100644 index 00000000..9b4fb9a5 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t22-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t22-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t22-geometry.webp new file mode 100644 index 00000000..09c108a9 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t22-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t23-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t23-colour.webp new file mode 100644 index 00000000..ca26c559 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t23-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t23-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t23-geometry.webp new file mode 100644 index 00000000..7d66bb6f Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t23-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t24-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t24-colour.webp new file mode 100644 index 00000000..58b4e401 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t24-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t24-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t24-geometry.webp new file mode 100644 index 00000000..fb10bdc4 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t24-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t25-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t25-colour.webp new file mode 100644 index 00000000..eb9d5ede Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t25-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t25-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t25-geometry.webp new file mode 100644 index 00000000..8b43d3a7 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t25-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t26-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t26-colour.webp new file mode 100644 index 00000000..26e79d1f Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t26-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t26-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t26-geometry.webp new file mode 100644 index 00000000..9ccfeec2 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t26-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t27-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t27-colour.webp new file mode 100644 index 00000000..d8f54c65 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t27-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t27-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t27-geometry.webp new file mode 100644 index 00000000..9df85bac Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t27-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t28-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t28-colour.webp new file mode 100644 index 00000000..89bfcc56 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t28-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t28-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t28-geometry.webp new file mode 100644 index 00000000..d498f614 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t28-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t29-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t29-colour.webp new file mode 100644 index 00000000..c7d21c15 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t29-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t29-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t29-geometry.webp new file mode 100644 index 00000000..fcd7f80f Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t29-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t30-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t30-colour.webp new file mode 100644 index 00000000..f3b486db Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t30-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t30-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t30-geometry.webp new file mode 100644 index 00000000..7ac31bea Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t30-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t31-colour.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t31-colour.webp new file mode 100644 index 00000000..6af48260 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t31-colour.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/card-3-t31-geometry.webp b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t31-geometry.webp new file mode 100644 index 00000000..fb0ea964 Binary files /dev/null and b/public/ridge/matterhorn-f4fa1ba3556c/card-3-t31-geometry.webp differ diff --git a/public/ridge/matterhorn-f4fa1ba3556c/manifest.json b/public/ridge/matterhorn-f4fa1ba3556c/manifest.json new file mode 100644 index 00000000..64565e37 --- /dev/null +++ b/public/ridge/matterhorn-f4fa1ba3556c/manifest.json @@ -0,0 +1,1796 @@ +{ + "schema": 3, + "baker_version": 7, + "bake_id": "f4fa1ba3556c", + "place": { + "id": "matterhorn", + "name": "Matterhorn from the Gornergrat", + "lat": 45.983139, + "lon": 7.782466, + "altitude_km": 3.090737150326758, + "eye_m": 3092.337150326758, + "tz": "Europe/Zurich" + }, + "view": { + "look_az_deg": 265.7572707724987, + "plane_h": 600, + "px_per_deg_h": 17.77777777777778, + "px_per_deg_v": 32.88082308679107, + "exaggeration": 1.8495462986319975, + "horizon_row": 385.03507633717794, + "sky_row": 24.0, + "near_row": 396.0, + "ring_w": 6400, + "tile_w": 200, + "tiles": 32, + "apron": 2 + }, + "curvature": { + "r_earth_m": 6371000.0, + "k_ref": 0.13 + }, + "encoding": { + "log_d_min": 6.214608098422191, + "log_d_max": 11.00475592466117, + "normal": "rt8" + }, + "camera": { + "r_max_m": 95.8, + "r_max_forward_m": 198.4 + }, + "cards": [ + { + "near_m": null, + "far_m": 30673.10182459612 + }, + { + "near_m": 30673.10182459612, + "far_m": 46643.05508137366 + }, + { + "near_m": 46643.05508137366, + "far_m": 59265.74213208556 + }, + { + "near_m": 59265.74213208556, + "far_m": null + } + ], + "tiles": [ + [ + { + "top": 382, + "h": 218, + "distance_m": 5200.7626953125, + "colour": { + "file": "card-0-t00-colour.webp", + "bytes": 5116 + }, + "geometry": { + "file": "card-0-t00-geometry.webp", + "bytes": 32912 + } + }, + { + "top": 358, + "h": 242, + "distance_m": 42748.96484375, + "colour": { + "file": "card-1-t00-colour.webp", + "bytes": 3980 + }, + "geometry": { + "file": "card-1-t00-geometry.webp", + "bytes": 20706 + } + }, + { + "top": 370, + "h": 230, + "distance_m": 52637.3125, + "colour": { + "file": "card-2-t00-colour.webp", + "bytes": 3938 + }, + "geometry": { + "file": "card-2-t00-geometry.webp", + "bytes": 14174 + } + }, + { + "top": 370, + "h": 230, + "distance_m": 56318.53125, + "colour": { + "file": "card-3-t00-colour.webp", + "bytes": 1492 + }, + "geometry": { + "file": "card-3-t00-geometry.webp", + "bytes": 4918 + } + } + ], + [ + { + "top": 254, + "h": 346, + "distance_m": 4215.55517578125, + "colour": { + "file": "card-0-t01-colour.webp", + "bytes": 5314 + }, + "geometry": { + "file": "card-0-t01-geometry.webp", + "bytes": 35936 + } + }, + { + "top": 365, + "h": 235, + "distance_m": 39018.9296875, + "colour": { + "file": "card-1-t01-colour.webp", + "bytes": 5848 + }, + "geometry": { + "file": "card-1-t01-geometry.webp", + "bytes": 27468 + } + }, + { + "top": 359, + "h": 241, + "distance_m": 48454.3671875, + "colour": { + "file": "card-2-t01-colour.webp", + "bytes": 4354 + }, + "geometry": { + "file": "card-2-t01-geometry.webp", + "bytes": 19594 + } + }, + { + "top": 359, + "h": 241, + "distance_m": 56371.99609375, + "colour": { + "file": "card-3-t01-colour.webp", + "bytes": 1742 + }, + "geometry": { + "file": "card-3-t01-geometry.webp", + "bytes": 6982 + } + } + ], + [ + { + "top": 192, + "h": 408, + "distance_m": 4912.3134765625, + "colour": { + "file": "card-0-t02-colour.webp", + "bytes": 6306 + }, + "geometry": { + "file": "card-0-t02-geometry.webp", + "bytes": 49514 + } + }, + { + "top": 387, + "h": 213, + "distance_m": 30035.7734375, + "colour": { + "file": "card-1-t02-colour.webp", + "bytes": 1508 + }, + "geometry": { + "file": "card-1-t02-geometry.webp", + "bytes": 4378 + } + }, + { + "top": 386, + "h": 214, + "distance_m": 48779.0078125, + "colour": { + "file": "card-2-t02-colour.webp", + "bytes": 3738 + }, + "geometry": { + "file": "card-2-t02-geometry.webp", + "bytes": 15058 + } + }, + { + "top": 386, + "h": 214, + "distance_m": 58255.13671875, + "colour": { + "file": "card-3-t02-colour.webp", + "bytes": 1652 + }, + "geometry": { + "file": "card-3-t02-geometry.webp", + "bytes": 6844 + } + } + ], + [ + { + "top": 197, + "h": 403, + "distance_m": 5298.56640625, + "colour": { + "file": "card-0-t03-colour.webp", + "bytes": 6244 + }, + "geometry": { + "file": "card-0-t03-geometry.webp", + "bytes": 47566 + } + }, + { + "top": 370, + "h": 230, + "distance_m": 36035.57421875, + "colour": { + "file": "card-1-t03-colour.webp", + "bytes": 2120 + }, + "geometry": { + "file": "card-1-t03-geometry.webp", + "bytes": 7528 + } + }, + { + "top": 387, + "h": 213, + "distance_m": 44827.15625, + "colour": { + "file": "card-2-t03-colour.webp", + "bytes": 2206 + }, + "geometry": { + "file": "card-2-t03-geometry.webp", + "bytes": 8984 + } + }, + { + "top": 394, + "h": 206, + "distance_m": 57030.5625, + "colour": { + "file": "card-3-t03-colour.webp", + "bytes": 1690 + }, + "geometry": { + "file": "card-3-t03-geometry.webp", + "bytes": 6070 + } + } + ], + [ + { + "top": 228, + "h": 372, + "distance_m": 1534.8564453125, + "colour": { + "file": "card-0-t04-colour.webp", + "bytes": 7102 + }, + "geometry": { + "file": "card-0-t04-geometry.webp", + "bytes": 47722 + } + }, + { + "top": 399, + "h": 201, + "distance_m": 37010.08203125, + "colour": { + "file": "card-1-t04-colour.webp", + "bytes": 3318 + }, + "geometry": { + "file": "card-1-t04-geometry.webp", + "bytes": 11958 + } + }, + { + "top": 399, + "h": 201, + "distance_m": 45624.83984375, + "colour": { + "file": "card-2-t04-colour.webp", + "bytes": 3714 + }, + "geometry": { + "file": "card-2-t04-geometry.webp", + "bytes": 19808 + } + }, + { + "top": 404, + "h": 196, + "distance_m": 56994.40234375, + "colour": { + "file": "card-3-t04-colour.webp", + "bytes": 1810 + }, + "geometry": { + "file": "card-3-t04-geometry.webp", + "bytes": 7890 + } + } + ], + [ + { + "top": 175, + "h": 425, + "distance_m": 1364.1209716796875, + "colour": { + "file": "card-0-t05-colour.webp", + "bytes": 5118 + }, + "geometry": { + "file": "card-0-t05-geometry.webp", + "bytes": 39596 + } + }, + { + "top": 414, + "h": 186, + "distance_m": 29493.169921875, + "colour": { + "file": "card-1-t05-colour.webp", + "bytes": 2236 + }, + "geometry": { + "file": "card-1-t05-geometry.webp", + "bytes": 10228 + } + }, + { + "top": 407, + "h": 193, + "distance_m": 50090.2109375, + "colour": { + "file": "card-2-t05-colour.webp", + "bytes": 3600 + }, + "geometry": { + "file": "card-2-t05-geometry.webp", + "bytes": 23392 + } + }, + { + "top": 407, + "h": 193, + "distance_m": 57102.5625, + "colour": { + "file": "card-3-t05-colour.webp", + "bytes": 1606 + }, + "geometry": { + "file": "card-3-t05-geometry.webp", + "bytes": 5904 + } + } + ], + [ + { + "top": 177, + "h": 423, + "distance_m": 1182.6668701171875, + "colour": { + "file": "card-0-t06-colour.webp", + "bytes": 4482 + }, + "geometry": { + "file": "card-0-t06-geometry.webp", + "bytes": 29128 + } + }, + { + "top": 423, + "h": 177, + "distance_m": 30519.244140625, + "colour": { + "file": "card-1-t06-colour.webp", + "bytes": 4036 + }, + "geometry": { + "file": "card-1-t06-geometry.webp", + "bytes": 22168 + } + }, + { + "top": 423, + "h": 177, + "distance_m": 45924.69921875, + "colour": { + "file": "card-2-t06-colour.webp", + "bytes": 2914 + }, + "geometry": { + "file": "card-2-t06-geometry.webp", + "bytes": 19660 + } + }, + { + "top": 424, + "h": 176, + "distance_m": 56655.05859375, + "colour": { + "file": "card-3-t06-colour.webp", + "bytes": 1038 + }, + "geometry": { + "file": "card-3-t06-geometry.webp", + "bytes": 6434 + } + } + ], + [ + { + "top": 198, + "h": 402, + "distance_m": 2050.119140625, + "colour": { + "file": "card-0-t07-colour.webp", + "bytes": 5192 + }, + "geometry": { + "file": "card-0-t07-geometry.webp", + "bytes": 31830 + } + }, + { + "top": 432, + "h": 168, + "distance_m": 34567.80078125, + "colour": { + "file": "card-1-t07-colour.webp", + "bytes": 3088 + }, + "geometry": { + "file": "card-1-t07-geometry.webp", + "bytes": 19350 + } + }, + { + "top": 424, + "h": 176, + "distance_m": 47590.3671875, + "colour": { + "file": "card-2-t07-colour.webp", + "bytes": 2098 + }, + "geometry": { + "file": "card-2-t07-geometry.webp", + "bytes": 15776 + } + }, + { + "top": 424, + "h": 176, + "distance_m": 56721.65625, + "colour": { + "file": "card-3-t07-colour.webp", + "bytes": 1236 + }, + "geometry": { + "file": "card-3-t07-geometry.webp", + "bytes": 7468 + } + } + ], + [ + { + "top": 238, + "h": 362, + "distance_m": 3579.99951171875, + "colour": { + "file": "card-0-t08-colour.webp", + "bytes": 4910 + }, + "geometry": { + "file": "card-0-t08-geometry.webp", + "bytes": 45504 + } + }, + { + "top": 429, + "h": 171, + "distance_m": 30154.337890625, + "colour": { + "file": "card-1-t08-colour.webp", + "bytes": 1882 + }, + "geometry": { + "file": "card-1-t08-geometry.webp", + "bytes": 19770 + } + }, + { + "top": 434, + "h": 166, + "distance_m": 46581.98046875, + "colour": { + "file": "card-2-t08-colour.webp", + "bytes": 1262 + }, + "geometry": { + "file": "card-2-t08-geometry.webp", + "bytes": 5610 + } + }, + { + "top": 459, + "h": 141, + "distance_m": 57186.70703125, + "colour": { + "file": "card-3-t08-colour.webp", + "bytes": 646 + }, + "geometry": { + "file": "card-3-t08-geometry.webp", + "bytes": 2126 + } + } + ], + [ + { + "top": 251, + "h": 349, + "distance_m": 4235.15966796875, + "colour": { + "file": "card-0-t09-colour.webp", + "bytes": 1402 + }, + "geometry": { + "file": "card-0-t09-geometry.webp", + "bytes": 39436 + } + }, + { + "top": 440, + "h": 160, + "distance_m": 33119.98828125, + "colour": { + "file": "card-1-t09-colour.webp", + "bytes": 1482 + }, + "geometry": { + "file": "card-1-t09-geometry.webp", + "bytes": 10982 + } + }, + { + "top": 449, + "h": 151, + "distance_m": 45002.60546875, + "colour": { + "file": "card-2-t09-colour.webp", + "bytes": 1332 + }, + "geometry": { + "file": "card-2-t09-geometry.webp", + "bytes": 7202 + } + }, + { + "top": 460, + "h": 140, + "distance_m": 56251.703125, + "colour": { + "file": "card-3-t09-colour.webp", + "bytes": 578 + }, + "geometry": { + "file": "card-3-t09-geometry.webp", + "bytes": 2594 + } + } + ], + [ + { + "top": 55, + "h": 545, + "distance_m": 4756.9658203125, + "colour": { + "file": "card-0-t10-colour.webp", + "bytes": 7252 + }, + "geometry": { + "file": "card-0-t10-geometry.webp", + "bytes": 67260 + } + }, + { + "top": 461, + "h": 139, + "distance_m": 29934.087890625, + "colour": { + "file": "card-1-t10-colour.webp", + "bytes": 1212 + }, + "geometry": { + "file": "card-1-t10-geometry.webp", + "bytes": 8122 + } + }, + { + "top": 467, + "h": 133, + "distance_m": 45674.9921875, + "colour": { + "file": "card-2-t10-colour.webp", + "bytes": 1068 + }, + "geometry": { + "file": "card-2-t10-geometry.webp", + "bytes": 7526 + } + }, + { + "top": 471, + "h": 129, + "distance_m": 56747.79296875, + "colour": { + "file": "card-3-t10-colour.webp", + "bytes": 514 + }, + "geometry": { + "file": "card-3-t10-geometry.webp", + "bytes": 2212 + } + } + ], + [ + { + "top": 55, + "h": 545, + "distance_m": 4971.21337890625, + "colour": { + "file": "card-0-t11-colour.webp", + "bytes": 8670 + }, + "geometry": { + "file": "card-0-t11-geometry.webp", + "bytes": 68938 + } + }, + { + "top": 441, + "h": 159, + "distance_m": 34451.1953125, + "colour": { + "file": "card-1-t11-colour.webp", + "bytes": 1460 + }, + "geometry": { + "file": "card-1-t11-geometry.webp", + "bytes": 14376 + } + }, + { + "top": 470, + "h": 130, + "distance_m": 51066.16796875, + "colour": { + "file": "card-2-t11-colour.webp", + "bytes": 1110 + }, + "geometry": { + "file": "card-2-t11-geometry.webp", + "bytes": 4576 + } + }, + { + "top": 472, + "h": 128, + "distance_m": 56986.30859375, + "colour": { + "file": "card-3-t11-colour.webp", + "bytes": 454 + }, + "geometry": { + "file": "card-3-t11-geometry.webp", + "bytes": 2358 + } + } + ], + [ + { + "top": 107, + "h": 493, + "distance_m": 4934.541015625, + "colour": { + "file": "card-0-t12-colour.webp", + "bytes": 6688 + }, + "geometry": { + "file": "card-0-t12-geometry.webp", + "bytes": 64866 + } + }, + { + "top": 448, + "h": 152, + "distance_m": 31824.158203125, + "colour": { + "file": "card-1-t12-colour.webp", + "bytes": 1444 + }, + "geometry": { + "file": "card-1-t12-geometry.webp", + "bytes": 16024 + } + }, + { + "top": 464, + "h": 136, + "distance_m": 45762.671875, + "colour": { + "file": "card-2-t12-colour.webp", + "bytes": 676 + }, + "geometry": { + "file": "card-2-t12-geometry.webp", + "bytes": 2428 + } + }, + { + "top": 481, + "h": 119, + "distance_m": 57345.6328125, + "colour": { + "file": "card-3-t12-colour.webp", + "bytes": 252 + }, + "geometry": { + "file": "card-3-t12-geometry.webp", + "bytes": 1694 + } + } + ], + [ + { + "top": 31, + "h": 569, + "distance_m": 5699.51953125, + "colour": { + "file": "card-0-t13-colour.webp", + "bytes": 3424 + }, + "geometry": { + "file": "card-0-t13-geometry.webp", + "bytes": 64924 + } + }, + { + "top": 416, + "h": 184, + "distance_m": 30396.14453125, + "colour": { + "file": "card-1-t13-colour.webp", + "bytes": 1818 + }, + "geometry": { + "file": "card-1-t13-geometry.webp", + "bytes": 11370 + } + }, + { + "top": 466, + "h": 134, + "distance_m": 47246.19140625, + "colour": { + "file": "card-2-t13-colour.webp", + "bytes": 720 + }, + "geometry": { + "file": "card-2-t13-geometry.webp", + "bytes": 2078 + } + }, + { + "top": 481, + "h": 119, + "distance_m": 57345.6328125, + "colour": { + "file": "card-3-t13-colour.webp", + "bytes": 242 + }, + "geometry": { + "file": "card-3-t13-geometry.webp", + "bytes": 1692 + } + } + ], + [ + { + "top": 76, + "h": 524, + "distance_m": 4679.2646484375, + "colour": { + "file": "card-0-t14-colour.webp", + "bytes": 5998 + }, + "geometry": { + "file": "card-0-t14-geometry.webp", + "bytes": 60814 + } + }, + { + "top": 416, + "h": 184, + "distance_m": 33286.3515625, + "colour": { + "file": "card-1-t14-colour.webp", + "bytes": 1790 + }, + "geometry": { + "file": "card-1-t14-geometry.webp", + "bytes": 9784 + } + }, + { + "top": 424, + "h": 176, + "distance_m": 44325.48828125, + "colour": { + "file": "card-2-t14-colour.webp", + "bytes": 934 + }, + "geometry": { + "file": "card-2-t14-geometry.webp", + "bytes": 2340 + } + }, + { + "top": 472, + "h": 128, + "distance_m": 57117.16015625, + "colour": { + "file": "card-3-t14-colour.webp", + "bytes": 390 + }, + "geometry": { + "file": "card-3-t14-geometry.webp", + "bytes": 2114 + } + } + ], + [ + { + "top": 93, + "h": 507, + "distance_m": 3718.8134765625, + "colour": { + "file": "card-0-t15-colour.webp", + "bytes": 6092 + }, + "geometry": { + "file": "card-0-t15-geometry.webp", + "bytes": 54590 + } + }, + { + "top": 393, + "h": 207, + "distance_m": 29459.6875, + "colour": { + "file": "card-1-t15-colour.webp", + "bytes": 2484 + }, + "geometry": { + "file": "card-1-t15-geometry.webp", + "bytes": 11778 + } + }, + { + "top": 423, + "h": 177, + "distance_m": 48277.2421875, + "colour": { + "file": "card-2-t15-colour.webp", + "bytes": 1188 + }, + "geometry": { + "file": "card-2-t15-geometry.webp", + "bytes": 6648 + } + }, + { + "top": 469, + "h": 131, + "distance_m": 57345.6328125, + "colour": { + "file": "card-3-t15-colour.webp", + "bytes": 422 + }, + "geometry": { + "file": "card-3-t15-geometry.webp", + "bytes": 1948 + } + } + ], + [ + { + "top": 42, + "h": 558, + "distance_m": 4111.91357421875, + "colour": { + "file": "card-0-t16-colour.webp", + "bytes": 5116 + }, + "geometry": { + "file": "card-0-t16-geometry.webp", + "bytes": 50356 + } + }, + { + "top": 403, + "h": 197, + "distance_m": 34945.5, + "colour": { + "file": "card-1-t16-colour.webp", + "bytes": 5388 + }, + "geometry": { + "file": "card-1-t16-geometry.webp", + "bytes": 22758 + } + }, + { + "top": 412, + "h": 188, + "distance_m": 45557.578125, + "colour": { + "file": "card-2-t16-colour.webp", + "bytes": 2200 + }, + "geometry": { + "file": "card-2-t16-geometry.webp", + "bytes": 17398 + } + }, + { + "top": 416, + "h": 184, + "distance_m": 55988.37890625, + "colour": { + "file": "card-3-t16-colour.webp", + "bytes": 902 + }, + "geometry": { + "file": "card-3-t16-geometry.webp", + "bytes": 3484 + } + } + ], + [ + { + "top": 24, + "h": 576, + "distance_m": 4138.59521484375, + "colour": { + "file": "card-0-t17-colour.webp", + "bytes": 4186 + }, + "geometry": { + "file": "card-0-t17-geometry.webp", + "bytes": 53810 + } + }, + { + "top": 398, + "h": 202, + "distance_m": 36938.1171875, + "colour": { + "file": "card-1-t17-colour.webp", + "bytes": 6772 + }, + "geometry": { + "file": "card-1-t17-geometry.webp", + "bytes": 36414 + } + }, + { + "top": 398, + "h": 202, + "distance_m": 45468.5546875, + "colour": { + "file": "card-2-t17-colour.webp", + "bytes": 2606 + }, + "geometry": { + "file": "card-2-t17-geometry.webp", + "bytes": 13168 + } + }, + { + "top": 415, + "h": 185, + "distance_m": 55893.73828125, + "colour": { + "file": "card-3-t17-colour.webp", + "bytes": 1082 + }, + "geometry": { + "file": "card-3-t17-geometry.webp", + "bytes": 3378 + } + } + ], + [ + { + "top": 25, + "h": 575, + "distance_m": 4345.9052734375, + "colour": { + "file": "card-0-t18-colour.webp", + "bytes": 4400 + }, + "geometry": { + "file": "card-0-t18-geometry.webp", + "bytes": 54898 + } + }, + { + "top": 376, + "h": 224, + "distance_m": 34020.55078125, + "colour": { + "file": "card-1-t18-colour.webp", + "bytes": 6162 + }, + "geometry": { + "file": "card-1-t18-geometry.webp", + "bytes": 38018 + } + }, + { + "top": 376, + "h": 224, + "distance_m": 46033.62109375, + "colour": { + "file": "card-2-t18-colour.webp", + "bytes": 2404 + }, + "geometry": { + "file": "card-2-t18-geometry.webp", + "bytes": 8386 + } + }, + { + "top": 378, + "h": 222, + "distance_m": 58590.1015625, + "colour": { + "file": "card-3-t18-colour.webp", + "bytes": 2098 + }, + "geometry": { + "file": "card-3-t18-geometry.webp", + "bytes": 7536 + } + } + ], + [ + { + "top": 133, + "h": 467, + "distance_m": 4712.76806640625, + "colour": { + "file": "card-0-t19-colour.webp", + "bytes": 5342 + }, + "geometry": { + "file": "card-0-t19-geometry.webp", + "bytes": 51372 + } + }, + { + "top": 375, + "h": 225, + "distance_m": 41753.94921875, + "colour": { + "file": "card-1-t19-colour.webp", + "bytes": 6084 + }, + "geometry": { + "file": "card-1-t19-geometry.webp", + "bytes": 26460 + } + }, + { + "top": 369, + "h": 231, + "distance_m": 45021.44921875, + "colour": { + "file": "card-2-t19-colour.webp", + "bytes": 3274 + }, + "geometry": { + "file": "card-2-t19-geometry.webp", + "bytes": 10926 + } + }, + { + "top": 369, + "h": 231, + "distance_m": 57015.609375, + "colour": { + "file": "card-3-t19-colour.webp", + "bytes": 2592 + }, + "geometry": { + "file": "card-3-t19-geometry.webp", + "bytes": 9752 + } + } + ], + [ + { + "top": 269, + "h": 331, + "distance_m": 4853.74560546875, + "colour": { + "file": "card-0-t20-colour.webp", + "bytes": 4084 + }, + "geometry": { + "file": "card-0-t20-geometry.webp", + "bytes": 40014 + } + }, + { + "top": 384, + "h": 216, + "distance_m": 42653.47265625, + "colour": { + "file": "card-1-t20-colour.webp", + "bytes": 2514 + }, + "geometry": { + "file": "card-1-t20-geometry.webp", + "bytes": 7660 + } + }, + { + "top": 386, + "h": 214, + "distance_m": 50108.26953125, + "colour": { + "file": "card-2-t20-colour.webp", + "bytes": 4602 + }, + "geometry": { + "file": "card-2-t20-geometry.webp", + "bytes": 20942 + } + }, + { + "top": 386, + "h": 214, + "distance_m": 56993.9140625, + "colour": { + "file": "card-3-t20-colour.webp", + "bytes": 1858 + }, + "geometry": { + "file": "card-3-t20-geometry.webp", + "bytes": 11374 + } + } + ], + [ + { + "top": 288, + "h": 312, + "distance_m": 4818.70654296875, + "colour": { + "file": "card-0-t21-colour.webp", + "bytes": 4582 + }, + "geometry": { + "file": "card-0-t21-geometry.webp", + "bytes": 40282 + } + }, + { + "top": 383, + "h": 217, + "distance_m": 29521.30859375, + "colour": { + "file": "card-1-t21-colour.webp", + "bytes": 2596 + }, + "geometry": { + "file": "card-1-t21-geometry.webp", + "bytes": 11918 + } + }, + { + "top": 394, + "h": 206, + "distance_m": 46590.4609375, + "colour": { + "file": "card-2-t21-colour.webp", + "bytes": 2394 + }, + "geometry": { + "file": "card-2-t21-geometry.webp", + "bytes": 16616 + } + }, + { + "top": 404, + "h": 196, + "distance_m": 56939.96484375, + "colour": { + "file": "card-3-t21-colour.webp", + "bytes": 1042 + }, + "geometry": { + "file": "card-3-t21-geometry.webp", + "bytes": 3196 + } + } + ], + [ + { + "top": 290, + "h": 310, + "distance_m": 4831.7939453125, + "colour": { + "file": "card-0-t22-colour.webp", + "bytes": 4572 + }, + "geometry": { + "file": "card-0-t22-geometry.webp", + "bytes": 44246 + } + }, + { + "top": 363, + "h": 237, + "distance_m": 33445.0078125, + "colour": { + "file": "card-1-t22-colour.webp", + "bytes": 2468 + }, + "geometry": { + "file": "card-1-t22-geometry.webp", + "bytes": 10830 + } + }, + { + "top": 388, + "h": 212, + "distance_m": 55223.69921875, + "colour": { + "file": "card-2-t22-colour.webp", + "bytes": 1818 + }, + "geometry": { + "file": "card-2-t22-geometry.webp", + "bytes": 4430 + } + }, + { + "top": 388, + "h": 212, + "distance_m": 55958.26953125, + "colour": { + "file": "card-3-t22-colour.webp", + "bytes": 1248 + }, + "geometry": { + "file": "card-3-t22-geometry.webp", + "bytes": 4024 + } + } + ], + [ + { + "top": 148, + "h": 452, + "distance_m": 7991.69677734375, + "colour": { + "file": "card-0-t23-colour.webp", + "bytes": 5978 + }, + "geometry": { + "file": "card-0-t23-geometry.webp", + "bytes": 54266 + } + }, + { + "top": 330, + "h": 270, + "distance_m": 35701.03515625, + "colour": { + "file": "card-1-t23-colour.webp", + "bytes": 2580 + }, + "geometry": { + "file": "card-1-t23-geometry.webp", + "bytes": 12230 + } + }, + { + "top": 369, + "h": 231, + "distance_m": 54297.42578125, + "colour": { + "file": "card-2-t23-colour.webp", + "bytes": 5658 + }, + "geometry": { + "file": "card-2-t23-geometry.webp", + "bytes": 15656 + } + }, + { + "top": 369, + "h": 231, + "distance_m": 56929.9765625, + "colour": { + "file": "card-3-t23-colour.webp", + "bytes": 2360 + }, + "geometry": { + "file": "card-3-t23-geometry.webp", + "bytes": 9738 + } + } + ], + [ + { + "top": 287, + "h": 313, + "distance_m": 7433.8583984375, + "colour": { + "file": "card-0-t24-colour.webp", + "bytes": 7246 + }, + "geometry": { + "file": "card-0-t24-geometry.webp", + "bytes": 49400 + } + }, + { + "top": 343, + "h": 257, + "distance_m": 30422.564453125, + "colour": { + "file": "card-1-t24-colour.webp", + "bytes": 1708 + }, + "geometry": { + "file": "card-1-t24-geometry.webp", + "bytes": 8764 + } + }, + { + "top": 382, + "h": 218, + "distance_m": 46458.15625, + "colour": { + "file": "card-2-t24-colour.webp", + "bytes": 2910 + }, + "geometry": { + "file": "card-2-t24-geometry.webp", + "bytes": 11038 + } + }, + { + "top": 382, + "h": 218, + "distance_m": 56836.88671875, + "colour": { + "file": "card-3-t24-colour.webp", + "bytes": 1666 + }, + "geometry": { + "file": "card-3-t24-geometry.webp", + "bytes": 7624 + } + } + ], + [ + { + "top": 238, + "h": 362, + "distance_m": 10644.763671875, + "colour": { + "file": "card-0-t25-colour.webp", + "bytes": 6366 + }, + "geometry": { + "file": "card-0-t25-geometry.webp", + "bytes": 53384 + } + }, + { + "top": 365, + "h": 235, + "distance_m": 32008.306640625, + "colour": { + "file": "card-1-t25-colour.webp", + "bytes": 1230 + }, + "geometry": { + "file": "card-1-t25-geometry.webp", + "bytes": 4182 + } + }, + { + "top": 403, + "h": 197, + "distance_m": 47011.2578125, + "colour": { + "file": "card-2-t25-colour.webp", + "bytes": 1948 + }, + "geometry": { + "file": "card-2-t25-geometry.webp", + "bytes": 7998 + } + }, + { + "top": 403, + "h": 197, + "distance_m": 56836.078125, + "colour": { + "file": "card-3-t25-colour.webp", + "bytes": 1292 + }, + "geometry": { + "file": "card-3-t25-geometry.webp", + "bytes": 8980 + } + } + ], + [ + { + "top": 229, + "h": 371, + "distance_m": 8270.6533203125, + "colour": { + "file": "card-0-t26-colour.webp", + "bytes": 6442 + }, + "geometry": { + "file": "card-0-t26-geometry.webp", + "bytes": 53612 + } + }, + { + "top": 386, + "h": 214, + "distance_m": 29769.423828125, + "colour": { + "file": "card-1-t26-colour.webp", + "bytes": 2580 + }, + "geometry": { + "file": "card-1-t26-geometry.webp", + "bytes": 13894 + } + }, + { + "top": 398, + "h": 202, + "distance_m": 53755.09375, + "colour": { + "file": "card-2-t26-colour.webp", + "bytes": 4126 + }, + "geometry": { + "file": "card-2-t26-geometry.webp", + "bytes": 16184 + } + }, + { + "top": 398, + "h": 202, + "distance_m": 56437.1875, + "colour": { + "file": "card-3-t26-colour.webp", + "bytes": 2052 + }, + "geometry": { + "file": "card-3-t26-geometry.webp", + "bytes": 7216 + } + } + ], + [ + { + "top": 242, + "h": 358, + "distance_m": 7733.07861328125, + "colour": { + "file": "card-0-t27-colour.webp", + "bytes": 7702 + }, + "geometry": { + "file": "card-0-t27-geometry.webp", + "bytes": 54418 + } + }, + { + "top": 391, + "h": 209, + "distance_m": 31635.669921875, + "colour": { + "file": "card-1-t27-colour.webp", + "bytes": 1170 + }, + "geometry": { + "file": "card-1-t27-geometry.webp", + "bytes": 5642 + } + }, + { + "top": 390, + "h": 210, + "distance_m": 49537.48046875, + "colour": { + "file": "card-2-t27-colour.webp", + "bytes": 4302 + }, + "geometry": { + "file": "card-2-t27-geometry.webp", + "bytes": 26440 + } + }, + { + "top": 390, + "h": 210, + "distance_m": 56523.26171875, + "colour": { + "file": "card-3-t27-colour.webp", + "bytes": 1538 + }, + "geometry": { + "file": "card-3-t27-geometry.webp", + "bytes": 7538 + } + } + ], + [ + { + "top": 231, + "h": 369, + "distance_m": 8952.802734375, + "colour": { + "file": "card-0-t28-colour.webp", + "bytes": 8324 + }, + "geometry": { + "file": "card-0-t28-geometry.webp", + "bytes": 58204 + } + }, + { + "top": 389, + "h": 211, + "distance_m": 29559.9609375, + "colour": { + "file": "card-1-t28-colour.webp", + "bytes": 2618 + }, + "geometry": { + "file": "card-1-t28-geometry.webp", + "bytes": 10096 + } + }, + { + "top": 388, + "h": 212, + "distance_m": 47157.2421875, + "colour": { + "file": "card-2-t28-colour.webp", + "bytes": 3038 + }, + "geometry": { + "file": "card-2-t28-geometry.webp", + "bytes": 22630 + } + }, + { + "top": 404, + "h": 196, + "distance_m": 55958.64453125, + "colour": { + "file": "card-3-t28-colour.webp", + "bytes": 1204 + }, + "geometry": { + "file": "card-3-t28-geometry.webp", + "bytes": 2670 + } + } + ], + [ + { + "top": 243, + "h": 357, + "distance_m": 7626.91552734375, + "colour": { + "file": "card-0-t29-colour.webp", + "bytes": 6618 + }, + "geometry": { + "file": "card-0-t29-geometry.webp", + "bytes": 51022 + } + }, + { + "top": 391, + "h": 209, + "distance_m": 43394.55078125, + "colour": { + "file": "card-1-t29-colour.webp", + "bytes": 5902 + }, + "geometry": { + "file": "card-1-t29-geometry.webp", + "bytes": 20418 + } + }, + { + "top": 387, + "h": 213, + "distance_m": 45741.1640625, + "colour": { + "file": "card-2-t29-colour.webp", + "bytes": 2548 + }, + "geometry": { + "file": "card-2-t29-geometry.webp", + "bytes": 16600 + } + }, + { + "top": 415, + "h": 185, + "distance_m": 56662.9375, + "colour": { + "file": "card-3-t29-colour.webp", + "bytes": 978 + }, + "geometry": { + "file": "card-3-t29-geometry.webp", + "bytes": 4000 + } + } + ], + [ + { + "top": 209, + "h": 391, + "distance_m": 8535.6982421875, + "colour": { + "file": "card-0-t30-colour.webp", + "bytes": 6504 + }, + "geometry": { + "file": "card-0-t30-geometry.webp", + "bytes": 54608 + } + }, + { + "top": 379, + "h": 221, + "distance_m": 30519.244140625, + "colour": { + "file": "card-1-t30-colour.webp", + "bytes": 3252 + }, + "geometry": { + "file": "card-1-t30-geometry.webp", + "bytes": 10042 + } + }, + { + "top": 379, + "h": 221, + "distance_m": 46410.1953125, + "colour": { + "file": "card-2-t30-colour.webp", + "bytes": 2922 + }, + "geometry": { + "file": "card-2-t30-geometry.webp", + "bytes": 14372 + } + }, + { + "top": 397, + "h": 203, + "distance_m": 56393.33984375, + "colour": { + "file": "card-3-t30-colour.webp", + "bytes": 1230 + }, + "geometry": { + "file": "card-3-t30-geometry.webp", + "bytes": 4024 + } + } + ], + [ + { + "top": 303, + "h": 297, + "distance_m": 14576.4990234375, + "colour": { + "file": "card-0-t31-colour.webp", + "bytes": 5654 + }, + "geometry": { + "file": "card-0-t31-geometry.webp", + "bytes": 48236 + } + }, + { + "top": 370, + "h": 230, + "distance_m": 41007.98046875, + "colour": { + "file": "card-1-t31-colour.webp", + "bytes": 4592 + }, + "geometry": { + "file": "card-1-t31-geometry.webp", + "bytes": 13188 + } + }, + { + "top": 370, + "h": 230, + "distance_m": 48204.4140625, + "colour": { + "file": "card-2-t31-colour.webp", + "bytes": 3650 + }, + "geometry": { + "file": "card-2-t31-geometry.webp", + "bytes": 15018 + } + }, + { + "top": 374, + "h": 226, + "distance_m": 56437.1875, + "colour": { + "file": "card-3-t31-colour.webp", + "bytes": 1212 + }, + "geometry": { + "file": "card-3-t31-geometry.webp", + "bytes": 3638 + } + } + ] + ], + "bytes": 3056362, + "attribution": { + "credit_line": "Contains modified Copernicus data: DEM \u00a9 DLR e.V. 2010-2014 and \u00a9 Airbus Defence and Space GmbH 2014-2018 provided under COPERNICUS by the European Union and ESA; all rights reserved.", + "licence": "Copernicus DEM licence: free, full and open access, with the credit line shown", + "dem_source": "Copernicus DEM GLO-30 (30 m)", + "url": "https://spacedata.copernicus.eu/collections/copernicus-digital-elevation-model" + } +} diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t00-colour.webp b/public/ridge/vienna-f50ec31ee950/card-0-t00-colour.webp new file mode 100644 index 00000000..686362d9 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t00-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t00-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-0-t00-geometry.webp new file mode 100644 index 00000000..404e34f3 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t00-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t01-colour.webp b/public/ridge/vienna-f50ec31ee950/card-0-t01-colour.webp new file mode 100644 index 00000000..8b23e1cb Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t01-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t01-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-0-t01-geometry.webp new file mode 100644 index 00000000..df1f1e86 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t01-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t02-colour.webp b/public/ridge/vienna-f50ec31ee950/card-0-t02-colour.webp new file mode 100644 index 00000000..ee2f52bb Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t02-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t02-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-0-t02-geometry.webp new file mode 100644 index 00000000..a119adf7 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t02-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t03-colour.webp b/public/ridge/vienna-f50ec31ee950/card-0-t03-colour.webp new file mode 100644 index 00000000..8f032bc9 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t03-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t03-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-0-t03-geometry.webp new file mode 100644 index 00000000..a3d9c65a Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t03-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t04-colour.webp b/public/ridge/vienna-f50ec31ee950/card-0-t04-colour.webp new file mode 100644 index 00000000..e4157192 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t04-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t04-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-0-t04-geometry.webp new file mode 100644 index 00000000..f787120e Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t04-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t05-colour.webp b/public/ridge/vienna-f50ec31ee950/card-0-t05-colour.webp new file mode 100644 index 00000000..13d4b141 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t05-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t05-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-0-t05-geometry.webp new file mode 100644 index 00000000..a26acc06 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t05-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t06-colour.webp b/public/ridge/vienna-f50ec31ee950/card-0-t06-colour.webp new file mode 100644 index 00000000..a3d23180 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t06-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t06-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-0-t06-geometry.webp new file mode 100644 index 00000000..00abe410 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t06-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t07-colour.webp b/public/ridge/vienna-f50ec31ee950/card-0-t07-colour.webp new file mode 100644 index 00000000..67fd7605 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t07-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t07-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-0-t07-geometry.webp new file mode 100644 index 00000000..998d80ca Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t07-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t08-colour.webp b/public/ridge/vienna-f50ec31ee950/card-0-t08-colour.webp new file mode 100644 index 00000000..d47c3d71 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t08-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t08-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-0-t08-geometry.webp new file mode 100644 index 00000000..1c2e742c Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t08-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t09-colour.webp b/public/ridge/vienna-f50ec31ee950/card-0-t09-colour.webp new file mode 100644 index 00000000..43545dad Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t09-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t09-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-0-t09-geometry.webp new file mode 100644 index 00000000..7c06ba9b Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t09-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t10-colour.webp b/public/ridge/vienna-f50ec31ee950/card-0-t10-colour.webp new file mode 100644 index 00000000..71db26f9 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t10-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t10-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-0-t10-geometry.webp new file mode 100644 index 00000000..64b8f54e Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t10-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t11-colour.webp b/public/ridge/vienna-f50ec31ee950/card-0-t11-colour.webp new file mode 100644 index 00000000..217387dc Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t11-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t11-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-0-t11-geometry.webp new file mode 100644 index 00000000..f2127ce4 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t11-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t12-colour.webp b/public/ridge/vienna-f50ec31ee950/card-0-t12-colour.webp new file mode 100644 index 00000000..908e626b Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t12-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t12-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-0-t12-geometry.webp new file mode 100644 index 00000000..1ccc9f79 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t12-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t13-colour.webp b/public/ridge/vienna-f50ec31ee950/card-0-t13-colour.webp new file mode 100644 index 00000000..a7406271 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t13-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t13-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-0-t13-geometry.webp new file mode 100644 index 00000000..36933b0d Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t13-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t14-colour.webp b/public/ridge/vienna-f50ec31ee950/card-0-t14-colour.webp new file mode 100644 index 00000000..ee3823c5 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t14-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t14-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-0-t14-geometry.webp new file mode 100644 index 00000000..064ee277 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t14-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t15-colour.webp b/public/ridge/vienna-f50ec31ee950/card-0-t15-colour.webp new file mode 100644 index 00000000..29409430 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t15-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t15-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-0-t15-geometry.webp new file mode 100644 index 00000000..75ae86c3 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t15-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t16-colour.webp b/public/ridge/vienna-f50ec31ee950/card-0-t16-colour.webp new file mode 100644 index 00000000..a50024d4 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t16-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t16-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-0-t16-geometry.webp new file mode 100644 index 00000000..c0286780 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t16-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t17-colour.webp b/public/ridge/vienna-f50ec31ee950/card-0-t17-colour.webp new file mode 100644 index 00000000..df1d26bc Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t17-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t17-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-0-t17-geometry.webp new file mode 100644 index 00000000..ad94826f Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t17-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t18-colour.webp b/public/ridge/vienna-f50ec31ee950/card-0-t18-colour.webp new file mode 100644 index 00000000..51b89544 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t18-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t18-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-0-t18-geometry.webp new file mode 100644 index 00000000..717fb6f8 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t18-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t19-colour.webp b/public/ridge/vienna-f50ec31ee950/card-0-t19-colour.webp new file mode 100644 index 00000000..dbdac364 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t19-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t19-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-0-t19-geometry.webp new file mode 100644 index 00000000..ec133982 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t19-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t20-colour.webp b/public/ridge/vienna-f50ec31ee950/card-0-t20-colour.webp new file mode 100644 index 00000000..b1eccb3c Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t20-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t20-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-0-t20-geometry.webp new file mode 100644 index 00000000..64692465 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t20-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t21-colour.webp b/public/ridge/vienna-f50ec31ee950/card-0-t21-colour.webp new file mode 100644 index 00000000..8eeb4af1 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t21-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t21-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-0-t21-geometry.webp new file mode 100644 index 00000000..e01306ad Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t21-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t22-colour.webp b/public/ridge/vienna-f50ec31ee950/card-0-t22-colour.webp new file mode 100644 index 00000000..070d8d99 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t22-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t22-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-0-t22-geometry.webp new file mode 100644 index 00000000..42c7ba9f Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t22-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t23-colour.webp b/public/ridge/vienna-f50ec31ee950/card-0-t23-colour.webp new file mode 100644 index 00000000..26820fc4 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t23-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t23-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-0-t23-geometry.webp new file mode 100644 index 00000000..d578769b Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t23-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t24-colour.webp b/public/ridge/vienna-f50ec31ee950/card-0-t24-colour.webp new file mode 100644 index 00000000..944d2d7f Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t24-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t24-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-0-t24-geometry.webp new file mode 100644 index 00000000..a18af569 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t24-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t25-colour.webp b/public/ridge/vienna-f50ec31ee950/card-0-t25-colour.webp new file mode 100644 index 00000000..f902bea7 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t25-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t25-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-0-t25-geometry.webp new file mode 100644 index 00000000..b9e726d1 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t25-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t26-colour.webp b/public/ridge/vienna-f50ec31ee950/card-0-t26-colour.webp new file mode 100644 index 00000000..de1883f1 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t26-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t26-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-0-t26-geometry.webp new file mode 100644 index 00000000..c4f2c33d Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t26-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t27-colour.webp b/public/ridge/vienna-f50ec31ee950/card-0-t27-colour.webp new file mode 100644 index 00000000..8e6f04e5 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t27-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t27-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-0-t27-geometry.webp new file mode 100644 index 00000000..26dc3c1c Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t27-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t28-colour.webp b/public/ridge/vienna-f50ec31ee950/card-0-t28-colour.webp new file mode 100644 index 00000000..682b4975 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t28-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t28-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-0-t28-geometry.webp new file mode 100644 index 00000000..1eb9681a Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t28-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t29-colour.webp b/public/ridge/vienna-f50ec31ee950/card-0-t29-colour.webp new file mode 100644 index 00000000..ebbfad82 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t29-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t29-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-0-t29-geometry.webp new file mode 100644 index 00000000..cb9f1d35 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t29-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t30-colour.webp b/public/ridge/vienna-f50ec31ee950/card-0-t30-colour.webp new file mode 100644 index 00000000..6e93f4a0 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t30-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t30-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-0-t30-geometry.webp new file mode 100644 index 00000000..03fba725 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t30-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t31-colour.webp b/public/ridge/vienna-f50ec31ee950/card-0-t31-colour.webp new file mode 100644 index 00000000..0bc262e2 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t31-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-0-t31-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-0-t31-geometry.webp new file mode 100644 index 00000000..97214f10 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-0-t31-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t00-colour.webp b/public/ridge/vienna-f50ec31ee950/card-1-t00-colour.webp new file mode 100644 index 00000000..c5af4bb6 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t00-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t00-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-1-t00-geometry.webp new file mode 100644 index 00000000..58cd96a5 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t00-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t01-colour.webp b/public/ridge/vienna-f50ec31ee950/card-1-t01-colour.webp new file mode 100644 index 00000000..a6439983 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t01-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t01-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-1-t01-geometry.webp new file mode 100644 index 00000000..aad4b786 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t01-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t02-colour.webp b/public/ridge/vienna-f50ec31ee950/card-1-t02-colour.webp new file mode 100644 index 00000000..6ea1f7af Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t02-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t02-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-1-t02-geometry.webp new file mode 100644 index 00000000..0c103115 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t02-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t03-colour.webp b/public/ridge/vienna-f50ec31ee950/card-1-t03-colour.webp new file mode 100644 index 00000000..1a779093 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t03-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t03-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-1-t03-geometry.webp new file mode 100644 index 00000000..28a2644b Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t03-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t04-colour.webp b/public/ridge/vienna-f50ec31ee950/card-1-t04-colour.webp new file mode 100644 index 00000000..950fc2a6 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t04-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t04-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-1-t04-geometry.webp new file mode 100644 index 00000000..708c2c10 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t04-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t05-colour.webp b/public/ridge/vienna-f50ec31ee950/card-1-t05-colour.webp new file mode 100644 index 00000000..46107bf7 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t05-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t05-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-1-t05-geometry.webp new file mode 100644 index 00000000..d249f8de Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t05-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t06-colour.webp b/public/ridge/vienna-f50ec31ee950/card-1-t06-colour.webp new file mode 100644 index 00000000..2a32bca9 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t06-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t06-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-1-t06-geometry.webp new file mode 100644 index 00000000..f3250ed8 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t06-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t07-colour.webp b/public/ridge/vienna-f50ec31ee950/card-1-t07-colour.webp new file mode 100644 index 00000000..41081904 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t07-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t07-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-1-t07-geometry.webp new file mode 100644 index 00000000..d5e46567 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t07-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t08-colour.webp b/public/ridge/vienna-f50ec31ee950/card-1-t08-colour.webp new file mode 100644 index 00000000..97db459b Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t08-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t08-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-1-t08-geometry.webp new file mode 100644 index 00000000..554e502e Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t08-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t09-colour.webp b/public/ridge/vienna-f50ec31ee950/card-1-t09-colour.webp new file mode 100644 index 00000000..c30c2166 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t09-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t09-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-1-t09-geometry.webp new file mode 100644 index 00000000..fb7f668d Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t09-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t10-colour.webp b/public/ridge/vienna-f50ec31ee950/card-1-t10-colour.webp new file mode 100644 index 00000000..981fe509 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t10-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t10-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-1-t10-geometry.webp new file mode 100644 index 00000000..27b1fb7a Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t10-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t11-colour.webp b/public/ridge/vienna-f50ec31ee950/card-1-t11-colour.webp new file mode 100644 index 00000000..763fed8f Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t11-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t11-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-1-t11-geometry.webp new file mode 100644 index 00000000..d64787ea Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t11-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t12-colour.webp b/public/ridge/vienna-f50ec31ee950/card-1-t12-colour.webp new file mode 100644 index 00000000..55103a11 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t12-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t12-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-1-t12-geometry.webp new file mode 100644 index 00000000..7e71327f Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t12-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t13-colour.webp b/public/ridge/vienna-f50ec31ee950/card-1-t13-colour.webp new file mode 100644 index 00000000..84863b23 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t13-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t13-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-1-t13-geometry.webp new file mode 100644 index 00000000..0cf1bfa6 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t13-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t14-colour.webp b/public/ridge/vienna-f50ec31ee950/card-1-t14-colour.webp new file mode 100644 index 00000000..26a04948 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t14-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t14-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-1-t14-geometry.webp new file mode 100644 index 00000000..f513b6de Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t14-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t15-colour.webp b/public/ridge/vienna-f50ec31ee950/card-1-t15-colour.webp new file mode 100644 index 00000000..5c449c09 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t15-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t15-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-1-t15-geometry.webp new file mode 100644 index 00000000..c4fa92b3 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t15-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t16-colour.webp b/public/ridge/vienna-f50ec31ee950/card-1-t16-colour.webp new file mode 100644 index 00000000..2b2a61ce Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t16-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t16-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-1-t16-geometry.webp new file mode 100644 index 00000000..42d24b90 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t16-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t17-colour.webp b/public/ridge/vienna-f50ec31ee950/card-1-t17-colour.webp new file mode 100644 index 00000000..b6522d96 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t17-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t17-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-1-t17-geometry.webp new file mode 100644 index 00000000..d50da47f Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t17-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t18-colour.webp b/public/ridge/vienna-f50ec31ee950/card-1-t18-colour.webp new file mode 100644 index 00000000..45e7edb8 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t18-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t18-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-1-t18-geometry.webp new file mode 100644 index 00000000..af61ad07 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t18-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t19-colour.webp b/public/ridge/vienna-f50ec31ee950/card-1-t19-colour.webp new file mode 100644 index 00000000..df60d40a Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t19-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t19-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-1-t19-geometry.webp new file mode 100644 index 00000000..66127020 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t19-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t20-colour.webp b/public/ridge/vienna-f50ec31ee950/card-1-t20-colour.webp new file mode 100644 index 00000000..b6659fdd Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t20-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t20-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-1-t20-geometry.webp new file mode 100644 index 00000000..0bca3b52 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t20-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t21-colour.webp b/public/ridge/vienna-f50ec31ee950/card-1-t21-colour.webp new file mode 100644 index 00000000..987eaac3 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t21-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t21-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-1-t21-geometry.webp new file mode 100644 index 00000000..9d623baf Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t21-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t22-colour.webp b/public/ridge/vienna-f50ec31ee950/card-1-t22-colour.webp new file mode 100644 index 00000000..9d947e7b Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t22-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t22-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-1-t22-geometry.webp new file mode 100644 index 00000000..84f0813e Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t22-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t23-colour.webp b/public/ridge/vienna-f50ec31ee950/card-1-t23-colour.webp new file mode 100644 index 00000000..6a0fb7ab Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t23-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t23-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-1-t23-geometry.webp new file mode 100644 index 00000000..c05fd3c7 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t23-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t24-colour.webp b/public/ridge/vienna-f50ec31ee950/card-1-t24-colour.webp new file mode 100644 index 00000000..2aae2a91 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t24-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t24-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-1-t24-geometry.webp new file mode 100644 index 00000000..02be7816 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t24-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t25-colour.webp b/public/ridge/vienna-f50ec31ee950/card-1-t25-colour.webp new file mode 100644 index 00000000..d88a2cf5 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t25-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t25-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-1-t25-geometry.webp new file mode 100644 index 00000000..5a840047 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t25-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t26-colour.webp b/public/ridge/vienna-f50ec31ee950/card-1-t26-colour.webp new file mode 100644 index 00000000..ca02aa50 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t26-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t26-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-1-t26-geometry.webp new file mode 100644 index 00000000..d1274f06 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t26-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t27-colour.webp b/public/ridge/vienna-f50ec31ee950/card-1-t27-colour.webp new file mode 100644 index 00000000..368ed321 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t27-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t27-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-1-t27-geometry.webp new file mode 100644 index 00000000..acfcf68e Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t27-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t28-colour.webp b/public/ridge/vienna-f50ec31ee950/card-1-t28-colour.webp new file mode 100644 index 00000000..99278ff3 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t28-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t28-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-1-t28-geometry.webp new file mode 100644 index 00000000..97c25e93 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t28-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t29-colour.webp b/public/ridge/vienna-f50ec31ee950/card-1-t29-colour.webp new file mode 100644 index 00000000..6896f47c Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t29-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t29-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-1-t29-geometry.webp new file mode 100644 index 00000000..b86f0e94 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t29-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t30-colour.webp b/public/ridge/vienna-f50ec31ee950/card-1-t30-colour.webp new file mode 100644 index 00000000..7053645b Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t30-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t30-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-1-t30-geometry.webp new file mode 100644 index 00000000..29f233d2 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t30-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t31-colour.webp b/public/ridge/vienna-f50ec31ee950/card-1-t31-colour.webp new file mode 100644 index 00000000..a67cd724 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t31-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-1-t31-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-1-t31-geometry.webp new file mode 100644 index 00000000..b1365240 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-1-t31-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t00-colour.webp b/public/ridge/vienna-f50ec31ee950/card-2-t00-colour.webp new file mode 100644 index 00000000..8bfde290 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t00-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t00-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-2-t00-geometry.webp new file mode 100644 index 00000000..ae5550f5 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t00-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t01-colour.webp b/public/ridge/vienna-f50ec31ee950/card-2-t01-colour.webp new file mode 100644 index 00000000..8039a109 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t01-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t01-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-2-t01-geometry.webp new file mode 100644 index 00000000..6b086a39 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t01-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t02-colour.webp b/public/ridge/vienna-f50ec31ee950/card-2-t02-colour.webp new file mode 100644 index 00000000..1317a36d Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t02-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t02-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-2-t02-geometry.webp new file mode 100644 index 00000000..1ba99ab8 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t02-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t03-colour.webp b/public/ridge/vienna-f50ec31ee950/card-2-t03-colour.webp new file mode 100644 index 00000000..e1be6372 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t03-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t03-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-2-t03-geometry.webp new file mode 100644 index 00000000..6cb9b9c5 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t03-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t04-colour.webp b/public/ridge/vienna-f50ec31ee950/card-2-t04-colour.webp new file mode 100644 index 00000000..45d9819b Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t04-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t04-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-2-t04-geometry.webp new file mode 100644 index 00000000..6a0204d6 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t04-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t05-colour.webp b/public/ridge/vienna-f50ec31ee950/card-2-t05-colour.webp new file mode 100644 index 00000000..a3e8391e Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t05-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t05-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-2-t05-geometry.webp new file mode 100644 index 00000000..58b0f626 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t05-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t06-colour.webp b/public/ridge/vienna-f50ec31ee950/card-2-t06-colour.webp new file mode 100644 index 00000000..40674442 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t06-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t06-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-2-t06-geometry.webp new file mode 100644 index 00000000..8b9fdb41 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t06-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t07-colour.webp b/public/ridge/vienna-f50ec31ee950/card-2-t07-colour.webp new file mode 100644 index 00000000..ec5da0e4 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t07-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t07-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-2-t07-geometry.webp new file mode 100644 index 00000000..4cb83331 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t07-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t08-colour.webp b/public/ridge/vienna-f50ec31ee950/card-2-t08-colour.webp new file mode 100644 index 00000000..b7c9cccf Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t08-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t08-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-2-t08-geometry.webp new file mode 100644 index 00000000..5ae5e3ae Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t08-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t09-colour.webp b/public/ridge/vienna-f50ec31ee950/card-2-t09-colour.webp new file mode 100644 index 00000000..b9fa4d48 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t09-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t09-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-2-t09-geometry.webp new file mode 100644 index 00000000..cc630325 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t09-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t10-colour.webp b/public/ridge/vienna-f50ec31ee950/card-2-t10-colour.webp new file mode 100644 index 00000000..b63b2a9b Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t10-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t10-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-2-t10-geometry.webp new file mode 100644 index 00000000..c634800f Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t10-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t11-colour.webp b/public/ridge/vienna-f50ec31ee950/card-2-t11-colour.webp new file mode 100644 index 00000000..f0c1b27e Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t11-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t11-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-2-t11-geometry.webp new file mode 100644 index 00000000..8d79bb99 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t11-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t12-colour.webp b/public/ridge/vienna-f50ec31ee950/card-2-t12-colour.webp new file mode 100644 index 00000000..42cf3107 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t12-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t12-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-2-t12-geometry.webp new file mode 100644 index 00000000..f2dafbd9 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t12-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t13-colour.webp b/public/ridge/vienna-f50ec31ee950/card-2-t13-colour.webp new file mode 100644 index 00000000..07dd9300 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t13-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t13-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-2-t13-geometry.webp new file mode 100644 index 00000000..e20a9170 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t13-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t14-colour.webp b/public/ridge/vienna-f50ec31ee950/card-2-t14-colour.webp new file mode 100644 index 00000000..623e6edb Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t14-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t14-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-2-t14-geometry.webp new file mode 100644 index 00000000..02b1258f Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t14-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t15-colour.webp b/public/ridge/vienna-f50ec31ee950/card-2-t15-colour.webp new file mode 100644 index 00000000..079fd725 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t15-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t15-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-2-t15-geometry.webp new file mode 100644 index 00000000..cea2b8e4 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t15-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t16-colour.webp b/public/ridge/vienna-f50ec31ee950/card-2-t16-colour.webp new file mode 100644 index 00000000..67f196c1 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t16-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t16-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-2-t16-geometry.webp new file mode 100644 index 00000000..3702ec15 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t16-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t17-colour.webp b/public/ridge/vienna-f50ec31ee950/card-2-t17-colour.webp new file mode 100644 index 00000000..b2c864e2 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t17-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t17-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-2-t17-geometry.webp new file mode 100644 index 00000000..133bb147 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t17-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t18-colour.webp b/public/ridge/vienna-f50ec31ee950/card-2-t18-colour.webp new file mode 100644 index 00000000..a0d4d8fa Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t18-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t18-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-2-t18-geometry.webp new file mode 100644 index 00000000..34949f41 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t18-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t19-colour.webp b/public/ridge/vienna-f50ec31ee950/card-2-t19-colour.webp new file mode 100644 index 00000000..7a44160b Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t19-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t19-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-2-t19-geometry.webp new file mode 100644 index 00000000..bffe85bd Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t19-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t20-colour.webp b/public/ridge/vienna-f50ec31ee950/card-2-t20-colour.webp new file mode 100644 index 00000000..760155fd Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t20-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t20-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-2-t20-geometry.webp new file mode 100644 index 00000000..c24bf013 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t20-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t21-colour.webp b/public/ridge/vienna-f50ec31ee950/card-2-t21-colour.webp new file mode 100644 index 00000000..b38a28e1 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t21-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t21-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-2-t21-geometry.webp new file mode 100644 index 00000000..60482a18 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t21-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t22-colour.webp b/public/ridge/vienna-f50ec31ee950/card-2-t22-colour.webp new file mode 100644 index 00000000..b0dc679f Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t22-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t22-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-2-t22-geometry.webp new file mode 100644 index 00000000..35103f4a Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t22-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t23-colour.webp b/public/ridge/vienna-f50ec31ee950/card-2-t23-colour.webp new file mode 100644 index 00000000..30cd1c5b Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t23-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t23-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-2-t23-geometry.webp new file mode 100644 index 00000000..d9c75f82 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t23-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t24-colour.webp b/public/ridge/vienna-f50ec31ee950/card-2-t24-colour.webp new file mode 100644 index 00000000..5233fb24 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t24-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t24-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-2-t24-geometry.webp new file mode 100644 index 00000000..48a2aa42 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t24-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t25-colour.webp b/public/ridge/vienna-f50ec31ee950/card-2-t25-colour.webp new file mode 100644 index 00000000..fc092679 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t25-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t25-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-2-t25-geometry.webp new file mode 100644 index 00000000..4c5e7fc8 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t25-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t26-colour.webp b/public/ridge/vienna-f50ec31ee950/card-2-t26-colour.webp new file mode 100644 index 00000000..aa277098 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t26-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t26-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-2-t26-geometry.webp new file mode 100644 index 00000000..06258cf4 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t26-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t27-colour.webp b/public/ridge/vienna-f50ec31ee950/card-2-t27-colour.webp new file mode 100644 index 00000000..34d07fee Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t27-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t27-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-2-t27-geometry.webp new file mode 100644 index 00000000..f23c776f Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t27-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t28-colour.webp b/public/ridge/vienna-f50ec31ee950/card-2-t28-colour.webp new file mode 100644 index 00000000..f3dbe838 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t28-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t28-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-2-t28-geometry.webp new file mode 100644 index 00000000..c3157c79 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t28-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t29-colour.webp b/public/ridge/vienna-f50ec31ee950/card-2-t29-colour.webp new file mode 100644 index 00000000..6319a327 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t29-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t29-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-2-t29-geometry.webp new file mode 100644 index 00000000..c02f2b73 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t29-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t30-colour.webp b/public/ridge/vienna-f50ec31ee950/card-2-t30-colour.webp new file mode 100644 index 00000000..4a604811 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t30-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t30-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-2-t30-geometry.webp new file mode 100644 index 00000000..f0f62f6f Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t30-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t31-colour.webp b/public/ridge/vienna-f50ec31ee950/card-2-t31-colour.webp new file mode 100644 index 00000000..ac008a73 Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t31-colour.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/card-2-t31-geometry.webp b/public/ridge/vienna-f50ec31ee950/card-2-t31-geometry.webp new file mode 100644 index 00000000..b60767fd Binary files /dev/null and b/public/ridge/vienna-f50ec31ee950/card-2-t31-geometry.webp differ diff --git a/public/ridge/vienna-f50ec31ee950/manifest.json b/public/ridge/vienna-f50ec31ee950/manifest.json new file mode 100644 index 00000000..caca5704 --- /dev/null +++ b/public/ridge/vienna-f50ec31ee950/manifest.json @@ -0,0 +1,1376 @@ +{ + "schema": 3, + "baker_version": 7, + "bake_id": "f50ec31ee950", + "place": { + "id": "vienna", + "name": "Vienna, looking SW to Rax/Schneeberg", + "lat": 48.1929826, + "lon": 16.3534237, + "altitude_km": 0.18330000000000002, + "eye_m": 213.3, + "tz": "Europe/Vienna" + }, + "view": { + "look_az_deg": 214.0, + "plane_h": 600, + "px_per_deg_h": 17.77777777777778, + "px_per_deg_v": 171.73831979090915, + "exaggeration": 9.660280488238639, + "horizon_row": 357.01990847502145, + "sky_row": 24.0, + "near_row": 396.0, + "ring_w": 6400, + "tile_w": 200, + "tiles": 32, + "apron": 2 + }, + "curvature": { + "r_earth_m": 6371000.0, + "k_ref": 0.13 + }, + "encoding": { + "log_d_min": 6.214608098422191, + "log_d_max": 11.462786662662916, + "normal": "rt8" + }, + "camera": { + "r_max_m": 95.8, + "r_max_forward_m": 198.4 + }, + "cards": [ + { + "near_m": null, + "far_m": 4013.740853069043 + }, + { + "near_m": 4013.740853069043, + "far_m": 41206.78494161152 + }, + { + "near_m": 41206.78494161152, + "far_m": null + } + ], + "tiles": [ + [ + { + "top": 337, + "h": 263, + "distance_m": 612.7647094726562, + "colour": { + "file": "card-0-t00-colour.webp", + "bytes": 850 + }, + "geometry": { + "file": "card-0-t00-geometry.webp", + "bytes": 7502 + } + }, + { + "top": 254, + "h": 346, + "distance_m": 7923.6240234375, + "colour": { + "file": "card-1-t00-colour.webp", + "bytes": 1328 + }, + "geometry": { + "file": "card-1-t00-geometry.webp", + "bytes": 21430 + } + }, + { + "top": 326, + "h": 274, + "distance_m": 41265.13671875, + "colour": { + "file": "card-2-t00-colour.webp", + "bytes": 894 + }, + "geometry": { + "file": "card-2-t00-geometry.webp", + "bytes": 8502 + } + } + ], + [ + { + "top": 397, + "h": 203, + "distance_m": 681.6199951171875, + "colour": { + "file": "card-0-t01-colour.webp", + "bytes": 702 + }, + "geometry": { + "file": "card-0-t01-geometry.webp", + "bytes": 5444 + } + }, + { + "top": 294, + "h": 306, + "distance_m": 12328.642578125, + "colour": { + "file": "card-1-t01-colour.webp", + "bytes": 1202 + }, + "geometry": { + "file": "card-1-t01-geometry.webp", + "bytes": 19568 + } + }, + { + "top": 359, + "h": 241, + "distance_m": 41087.56640625, + "colour": { + "file": "card-2-t01-colour.webp", + "bytes": 652 + }, + "geometry": { + "file": "card-2-t01-geometry.webp", + "bytes": 3190 + } + } + ], + [ + { + "top": 437, + "h": 163, + "distance_m": 802.34912109375, + "colour": { + "file": "card-0-t02-colour.webp", + "bytes": 634 + }, + "geometry": { + "file": "card-0-t02-geometry.webp", + "bytes": 7220 + } + }, + { + "top": 353, + "h": 247, + "distance_m": 9379.99609375, + "colour": { + "file": "card-1-t02-colour.webp", + "bytes": 956 + }, + "geometry": { + "file": "card-1-t02-geometry.webp", + "bytes": 16212 + } + }, + { + "top": 362, + "h": 238, + "distance_m": 38873.109375, + "colour": { + "file": "card-2-t02-colour.webp", + "bytes": 506 + }, + "geometry": { + "file": "card-2-t02-geometry.webp", + "bytes": 2514 + } + } + ], + [ + { + "top": 439, + "h": 161, + "distance_m": 1497.642333984375, + "colour": { + "file": "card-0-t03-colour.webp", + "bytes": 600 + }, + "geometry": { + "file": "card-0-t03-geometry.webp", + "bytes": 9330 + } + }, + { + "top": 357, + "h": 243, + "distance_m": 9379.99609375, + "colour": { + "file": "card-1-t03-colour.webp", + "bytes": 986 + }, + "geometry": { + "file": "card-1-t03-geometry.webp", + "bytes": 15134 + } + }, + { + "top": 371, + "h": 229, + "distance_m": 39822.90234375, + "colour": { + "file": "card-2-t03-colour.webp", + "bytes": 482 + }, + "geometry": { + "file": "card-2-t03-geometry.webp", + "bytes": 1748 + } + } + ], + [ + { + "top": 455, + "h": 145, + "distance_m": 1587.480712890625, + "colour": { + "file": "card-0-t04-colour.webp", + "bytes": 678 + }, + "geometry": { + "file": "card-0-t04-geometry.webp", + "bytes": 7418 + } + }, + { + "top": 363, + "h": 237, + "distance_m": 7940.0009765625, + "colour": { + "file": "card-1-t04-colour.webp", + "bytes": 1008 + }, + "geometry": { + "file": "card-1-t04-geometry.webp", + "bytes": 15664 + } + }, + { + "top": 380, + "h": 220, + "distance_m": 42715.42578125, + "colour": { + "file": "card-2-t04-colour.webp", + "bytes": 510 + }, + "geometry": { + "file": "card-2-t04-geometry.webp", + "bytes": 516 + } + } + ], + [ + { + "top": 461, + "h": 139, + "distance_m": 1739.9998779296875, + "colour": { + "file": "card-0-t05-colour.webp", + "bytes": 552 + }, + "geometry": { + "file": "card-0-t05-geometry.webp", + "bytes": 9882 + } + }, + { + "top": 390, + "h": 210, + "distance_m": 7191.796875, + "colour": { + "file": "card-1-t05-colour.webp", + "bytes": 498 + }, + "geometry": { + "file": "card-1-t05-geometry.webp", + "bytes": 9640 + } + }, + { + "top": 342, + "h": 258, + "distance_m": 73387.6015625, + "colour": { + "file": "card-2-t05-colour.webp", + "bytes": 994 + }, + "geometry": { + "file": "card-2-t05-geometry.webp", + "bytes": 6354 + } + } + ], + [ + { + "top": 461, + "h": 139, + "distance_m": 1397.39599609375, + "colour": { + "file": "card-0-t06-colour.webp", + "bytes": 384 + }, + "geometry": { + "file": "card-0-t06-geometry.webp", + "bytes": 7150 + } + }, + { + "top": 393, + "h": 207, + "distance_m": 6499.99853515625, + "colour": { + "file": "card-1-t06-colour.webp", + "bytes": 514 + }, + "geometry": { + "file": "card-1-t06-geometry.webp", + "bytes": 10622 + } + }, + { + "top": 323, + "h": 277, + "distance_m": 60884.40234375, + "colour": { + "file": "card-2-t06-colour.webp", + "bytes": 1652 + }, + "geometry": { + "file": "card-2-t06-geometry.webp", + "bytes": 18624 + } + } + ], + [ + { + "top": 440, + "h": 160, + "distance_m": 1639.5902099609375, + "colour": { + "file": "card-0-t07-colour.webp", + "bytes": 584 + }, + "geometry": { + "file": "card-0-t07-geometry.webp", + "bytes": 9288 + } + }, + { + "top": 393, + "h": 207, + "distance_m": 7020.00244140625, + "colour": { + "file": "card-1-t07-colour.webp", + "bytes": 604 + }, + "geometry": { + "file": "card-1-t07-geometry.webp", + "bytes": 8706 + } + }, + { + "top": 332, + "h": 268, + "distance_m": 53030.578125, + "colour": { + "file": "card-2-t07-colour.webp", + "bytes": 1356 + }, + "geometry": { + "file": "card-2-t07-geometry.webp", + "bytes": 14322 + } + } + ], + [ + { + "top": 404, + "h": 196, + "distance_m": 1494.0631103515625, + "colour": { + "file": "card-0-t08-colour.webp", + "bytes": 728 + }, + "geometry": { + "file": "card-0-t08-geometry.webp", + "bytes": 9320 + } + }, + { + "top": 393, + "h": 207, + "distance_m": 7499.99755859375, + "colour": { + "file": "card-1-t08-colour.webp", + "bytes": 700 + }, + "geometry": { + "file": "card-1-t08-geometry.webp", + "bytes": 10602 + } + }, + { + "top": 329, + "h": 271, + "distance_m": 44656.86328125, + "colour": { + "file": "card-2-t08-colour.webp", + "bytes": 1258 + }, + "geometry": { + "file": "card-2-t08-geometry.webp", + "bytes": 9538 + } + } + ], + [ + { + "top": 396, + "h": 204, + "distance_m": 1222.066650390625, + "colour": { + "file": "card-0-t09-colour.webp", + "bytes": 558 + }, + "geometry": { + "file": "card-0-t09-geometry.webp", + "bytes": 8568 + } + }, + { + "top": 360, + "h": 240, + "distance_m": 9976.568359375, + "colour": { + "file": "card-1-t09-colour.webp", + "bytes": 876 + }, + "geometry": { + "file": "card-1-t09-geometry.webp", + "bytes": 12968 + } + }, + { + "top": 370, + "h": 230, + "distance_m": 44772.3828125, + "colour": { + "file": "card-2-t09-colour.webp", + "bytes": 626 + }, + "geometry": { + "file": "card-2-t09-geometry.webp", + "bytes": 2232 + } + } + ], + [ + { + "top": 380, + "h": 220, + "distance_m": 1104.7967529296875, + "colour": { + "file": "card-0-t10-colour.webp", + "bytes": 576 + }, + "geometry": { + "file": "card-0-t10-geometry.webp", + "bytes": 6836 + } + }, + { + "top": 355, + "h": 245, + "distance_m": 14817.3876953125, + "colour": { + "file": "card-1-t10-colour.webp", + "bytes": 938 + }, + "geometry": { + "file": "card-1-t10-geometry.webp", + "bytes": 12918 + } + }, + { + "top": 370, + "h": 230, + "distance_m": 38822.984375, + "colour": { + "file": "card-2-t10-colour.webp", + "bytes": 474 + }, + "geometry": { + "file": "card-2-t10-geometry.webp", + "bytes": 2060 + } + } + ], + [ + { + "top": 285, + "h": 315, + "distance_m": 1123.831787109375, + "colour": { + "file": "card-0-t11-colour.webp", + "bytes": 1002 + }, + "geometry": { + "file": "card-0-t11-geometry.webp", + "bytes": 10782 + } + }, + { + "top": 312, + "h": 288, + "distance_m": 16307.2421875, + "colour": { + "file": "card-1-t11-colour.webp", + "bytes": 544 + }, + "geometry": { + "file": "card-1-t11-geometry.webp", + "bytes": 2216 + } + }, + { + "top": 358, + "h": 242, + "distance_m": 37985.00390625, + "colour": { + "file": "card-2-t11-colour.webp", + "bytes": 630 + }, + "geometry": { + "file": "card-2-t11-geometry.webp", + "bytes": 1840 + } + } + ], + [ + { + "top": 272, + "h": 328, + "distance_m": 1142.0506591796875, + "colour": { + "file": "card-0-t12-colour.webp", + "bytes": 758 + }, + "geometry": { + "file": "card-0-t12-geometry.webp", + "bytes": 13578 + } + }, + { + "top": 281, + "h": 319, + "distance_m": 5059.99853515625, + "colour": { + "file": "card-1-t12-colour.webp", + "bytes": 520 + }, + "geometry": { + "file": "card-1-t12-geometry.webp", + "bytes": 176 + } + }, + { + "top": 350, + "h": 250, + "distance_m": 37450.98828125, + "colour": { + "file": "card-2-t12-colour.webp", + "bytes": 646 + }, + "geometry": { + "file": "card-2-t12-geometry.webp", + "bytes": 612 + } + } + ], + [ + { + "top": 265, + "h": 335, + "distance_m": 1120.1195068359375, + "colour": { + "file": "card-0-t13-colour.webp", + "bytes": 582 + }, + "geometry": { + "file": "card-0-t13-geometry.webp", + "bytes": 11368 + } + }, + { + "top": 309, + "h": 291, + "distance_m": 35995.66015625, + "colour": { + "file": "card-1-t13-colour.webp", + "bytes": 952 + }, + "geometry": { + "file": "card-1-t13-geometry.webp", + "bytes": 5842 + } + }, + { + "top": 332, + "h": 268, + "distance_m": 37581.2578125, + "colour": { + "file": "card-2-t13-colour.webp", + "bytes": 634 + }, + "geometry": { + "file": "card-2-t13-geometry.webp", + "bytes": 1514 + } + } + ], + [ + { + "top": 247, + "h": 353, + "distance_m": 1184.9326171875, + "colour": { + "file": "card-0-t14-colour.webp", + "bytes": 608 + }, + "geometry": { + "file": "card-0-t14-geometry.webp", + "bytes": 10944 + } + }, + { + "top": 312, + "h": 288, + "distance_m": 33968.61328125, + "colour": { + "file": "card-1-t14-colour.webp", + "bytes": 1280 + }, + "geometry": { + "file": "card-1-t14-geometry.webp", + "bytes": 15154 + } + }, + { + "top": 318, + "h": 282, + "distance_m": 37484.328125, + "colour": { + "file": "card-2-t14-colour.webp", + "bytes": 678 + }, + "geometry": { + "file": "card-2-t14-geometry.webp", + "bytes": 1148 + } + } + ], + [ + { + "top": 244, + "h": 356, + "distance_m": 1333.3995361328125, + "colour": { + "file": "card-0-t15-colour.webp", + "bytes": 684 + }, + "geometry": { + "file": "card-0-t15-geometry.webp", + "bytes": 10824 + } + }, + { + "top": 346, + "h": 254, + "distance_m": 7460.00048828125, + "colour": { + "file": "card-1-t15-colour.webp", + "bytes": 602 + }, + "geometry": { + "file": "card-1-t15-geometry.webp", + "bytes": 6172 + } + }, + { + "top": 315, + "h": 285, + "distance_m": 56122.19140625, + "colour": { + "file": "card-2-t15-colour.webp", + "bytes": 1052 + }, + "geometry": { + "file": "card-2-t15-geometry.webp", + "bytes": 10512 + } + } + ], + [ + { + "top": 248, + "h": 352, + "distance_m": 1396.94775390625, + "colour": { + "file": "card-0-t16-colour.webp", + "bytes": 810 + }, + "geometry": { + "file": "card-0-t16-geometry.webp", + "bytes": 11362 + } + }, + { + "top": 364, + "h": 236, + "distance_m": 6820.00048828125, + "colour": { + "file": "card-1-t16-colour.webp", + "bytes": 436 + }, + "geometry": { + "file": "card-1-t16-geometry.webp", + "bytes": 4668 + } + }, + { + "top": 303, + "h": 297, + "distance_m": 53429.6796875, + "colour": { + "file": "card-2-t16-colour.webp", + "bytes": 1488 + }, + "geometry": { + "file": "card-2-t16-geometry.webp", + "bytes": 18396 + } + } + ], + [ + { + "top": 286, + "h": 314, + "distance_m": 1396.3682861328125, + "colour": { + "file": "card-0-t17-colour.webp", + "bytes": 684 + }, + "geometry": { + "file": "card-0-t17-geometry.webp", + "bytes": 10000 + } + }, + { + "top": 240, + "h": 360, + "distance_m": 14172.7490234375, + "colour": { + "file": "card-1-t17-colour.webp", + "bytes": 1104 + }, + "geometry": { + "file": "card-1-t17-geometry.webp", + "bytes": 10308 + } + }, + { + "top": 235, + "h": 365, + "distance_m": 65859.734375, + "colour": { + "file": "card-2-t17-colour.webp", + "bytes": 1674 + }, + "geometry": { + "file": "card-2-t17-geometry.webp", + "bytes": 16832 + } + } + ], + [ + { + "top": 314, + "h": 286, + "distance_m": 1440.37646484375, + "colour": { + "file": "card-0-t18-colour.webp", + "bytes": 552 + }, + "geometry": { + "file": "card-0-t18-geometry.webp", + "bytes": 11138 + } + }, + { + "top": 122, + "h": 478, + "distance_m": 14387.8525390625, + "colour": { + "file": "card-1-t18-colour.webp", + "bytes": 1796 + }, + "geometry": { + "file": "card-1-t18-geometry.webp", + "bytes": 30488 + } + }, + { + "top": 211, + "h": 389, + "distance_m": 44942.2578125, + "colour": { + "file": "card-2-t18-colour.webp", + "bytes": 1396 + }, + "geometry": { + "file": "card-2-t18-geometry.webp", + "bytes": 17582 + } + } + ], + [ + { + "top": 317, + "h": 283, + "distance_m": 1704.598388671875, + "colour": { + "file": "card-0-t19-colour.webp", + "bytes": 704 + }, + "geometry": { + "file": "card-0-t19-geometry.webp", + "bytes": 12068 + } + }, + { + "top": 144, + "h": 456, + "distance_m": 11607.04296875, + "colour": { + "file": "card-1-t19-colour.webp", + "bytes": 1898 + }, + "geometry": { + "file": "card-1-t19-geometry.webp", + "bytes": 27774 + } + }, + { + "top": 111, + "h": 489, + "distance_m": 53726.9609375, + "colour": { + "file": "card-2-t19-colour.webp", + "bytes": 2010 + }, + "geometry": { + "file": "card-2-t19-geometry.webp", + "bytes": 24316 + } + } + ], + [ + { + "top": 297, + "h": 303, + "distance_m": 2042.0157470703125, + "colour": { + "file": "card-0-t20-colour.webp", + "bytes": 724 + }, + "geometry": { + "file": "card-0-t20-geometry.webp", + "bytes": 11566 + } + }, + { + "top": 95, + "h": 505, + "distance_m": 10982.046875, + "colour": { + "file": "card-1-t20-colour.webp", + "bytes": 1794 + }, + "geometry": { + "file": "card-1-t20-geometry.webp", + "bytes": 28234 + } + }, + { + "top": 171, + "h": 429, + "distance_m": 40730.703125, + "colour": { + "file": "card-2-t20-colour.webp", + "bytes": 1772 + }, + "geometry": { + "file": "card-2-t20-geometry.webp", + "bytes": 17478 + } + } + ], + [ + { + "top": 269, + "h": 331, + "distance_m": 2420.00048828125, + "colour": { + "file": "card-0-t21-colour.webp", + "bytes": 998 + }, + "geometry": { + "file": "card-0-t21-geometry.webp", + "bytes": 18072 + } + }, + { + "top": 174, + "h": 426, + "distance_m": 8230.6103515625, + "colour": { + "file": "card-1-t21-colour.webp", + "bytes": 1386 + }, + "geometry": { + "file": "card-1-t21-geometry.webp", + "bytes": 15038 + } + }, + { + "top": 199, + "h": 401, + "distance_m": 41044.6015625, + "colour": { + "file": "card-2-t21-colour.webp", + "bytes": 1644 + }, + "geometry": { + "file": "card-2-t21-geometry.webp", + "bytes": 16786 + } + } + ], + [ + { + "top": 279, + "h": 321, + "distance_m": 1978.4818115234375, + "colour": { + "file": "card-0-t22-colour.webp", + "bytes": 1478 + }, + "geometry": { + "file": "card-0-t22-geometry.webp", + "bytes": 19720 + } + }, + { + "top": 80, + "h": 520, + "distance_m": 7335.22265625, + "colour": { + "file": "card-1-t22-colour.webp", + "bytes": 1866 + }, + "geometry": { + "file": "card-1-t22-geometry.webp", + "bytes": 21744 + } + }, + { + "top": 232, + "h": 368, + "distance_m": 40101.375, + "colour": { + "file": "card-2-t22-colour.webp", + "bytes": 1206 + }, + "geometry": { + "file": "card-2-t22-geometry.webp", + "bytes": 6988 + } + } + ], + [ + { + "top": 351, + "h": 249, + "distance_m": 925.3698120117188, + "colour": { + "file": "card-0-t23-colour.webp", + "bytes": 946 + }, + "geometry": { + "file": "card-0-t23-geometry.webp", + "bytes": 10266 + } + }, + { + "top": 79, + "h": 521, + "distance_m": 7168.36474609375, + "colour": { + "file": "card-1-t23-colour.webp", + "bytes": 1384 + }, + "geometry": { + "file": "card-1-t23-geometry.webp", + "bytes": 20954 + } + }, + { + "top": 289, + "h": 311, + "distance_m": 41300.6875, + "colour": { + "file": "card-2-t23-colour.webp", + "bytes": 934 + }, + "geometry": { + "file": "card-2-t23-geometry.webp", + "bytes": 4296 + } + } + ], + [ + { + "top": 244, + "h": 356, + "distance_m": 1025.4903564453125, + "colour": { + "file": "card-0-t24-colour.webp", + "bytes": 1106 + }, + "geometry": { + "file": "card-0-t24-geometry.webp", + "bytes": 11518 + } + }, + { + "top": 159, + "h": 441, + "distance_m": 11321.796875, + "colour": { + "file": "card-1-t24-colour.webp", + "bytes": 1558 + }, + "geometry": { + "file": "card-1-t24-geometry.webp", + "bytes": 18134 + } + }, + { + "top": 319, + "h": 281, + "distance_m": 57565.35546875, + "colour": { + "file": "card-2-t24-colour.webp", + "bytes": 954 + }, + "geometry": { + "file": "card-2-t24-geometry.webp", + "bytes": 6602 + } + } + ], + [ + { + "top": 229, + "h": 371, + "distance_m": 1073.8558349609375, + "colour": { + "file": "card-0-t25-colour.webp", + "bytes": 808 + }, + "geometry": { + "file": "card-0-t25-geometry.webp", + "bytes": 12526 + } + }, + { + "top": 72, + "h": 528, + "distance_m": 5733.2158203125, + "colour": { + "file": "card-1-t25-colour.webp", + "bytes": 1614 + }, + "geometry": { + "file": "card-1-t25-geometry.webp", + "bytes": 15386 + } + }, + { + "top": 313, + "h": 287, + "distance_m": 59443.39453125, + "colour": { + "file": "card-2-t25-colour.webp", + "bytes": 1490 + }, + "geometry": { + "file": "card-2-t25-geometry.webp", + "bytes": 16294 + } + } + ], + [ + { + "top": 250, + "h": 350, + "distance_m": 766.68505859375, + "colour": { + "file": "card-0-t26-colour.webp", + "bytes": 676 + }, + "geometry": { + "file": "card-0-t26-geometry.webp", + "bytes": 10752 + } + }, + { + "top": 28, + "h": 572, + "distance_m": 5613.7412109375, + "colour": { + "file": "card-1-t26-colour.webp", + "bytes": 1432 + }, + "geometry": { + "file": "card-1-t26-geometry.webp", + "bytes": 20908 + } + }, + { + "top": 338, + "h": 262, + "distance_m": 65859.734375, + "colour": { + "file": "card-2-t26-colour.webp", + "bytes": 1384 + }, + "geometry": { + "file": "card-2-t26-geometry.webp", + "bytes": 14708 + } + } + ], + [ + { + "top": 278, + "h": 322, + "distance_m": 715.7683715820312, + "colour": { + "file": "card-0-t27-colour.webp", + "bytes": 708 + }, + "geometry": { + "file": "card-0-t27-geometry.webp", + "bytes": 8710 + } + }, + { + "top": 24, + "h": 576, + "distance_m": 6389.61474609375, + "colour": { + "file": "card-1-t27-colour.webp", + "bytes": 1470 + }, + "geometry": { + "file": "card-1-t27-geometry.webp", + "bytes": 23794 + } + }, + { + "top": 344, + "h": 256, + "distance_m": 50670.5078125, + "colour": { + "file": "card-2-t27-colour.webp", + "bytes": 1080 + }, + "geometry": { + "file": "card-2-t27-geometry.webp", + "bytes": 11834 + } + } + ], + [ + { + "top": 309, + "h": 291, + "distance_m": 851.5679321289062, + "colour": { + "file": "card-0-t28-colour.webp", + "bytes": 560 + }, + "geometry": { + "file": "card-0-t28-geometry.webp", + "bytes": 6160 + } + }, + { + "top": 94, + "h": 506, + "distance_m": 5985.80078125, + "colour": { + "file": "card-1-t28-colour.webp", + "bytes": 1472 + }, + "geometry": { + "file": "card-1-t28-geometry.webp", + "bytes": 23606 + } + }, + { + "top": 338, + "h": 262, + "distance_m": 41220.84765625, + "colour": { + "file": "card-2-t28-colour.webp", + "bytes": 782 + }, + "geometry": { + "file": "card-2-t28-geometry.webp", + "bytes": 5094 + } + } + ], + [ + { + "top": 327, + "h": 273, + "distance_m": 591.9729614257812, + "colour": { + "file": "card-0-t29-colour.webp", + "bytes": 600 + }, + "geometry": { + "file": "card-0-t29-geometry.webp", + "bytes": 5650 + } + }, + { + "top": 53, + "h": 547, + "distance_m": 7741.88134765625, + "colour": { + "file": "card-1-t29-colour.webp", + "bytes": 1768 + }, + "geometry": { + "file": "card-1-t29-geometry.webp", + "bytes": 26930 + } + }, + { + "top": 334, + "h": 266, + "distance_m": 39778.60546875, + "colour": { + "file": "card-2-t29-colour.webp", + "bytes": 802 + }, + "geometry": { + "file": "card-2-t29-geometry.webp", + "bytes": 4504 + } + } + ], + [ + { + "top": 324, + "h": 276, + "distance_m": 592.1824951171875, + "colour": { + "file": "card-0-t30-colour.webp", + "bytes": 488 + }, + "geometry": { + "file": "card-0-t30-geometry.webp", + "bytes": 5312 + } + }, + { + "top": 58, + "h": 542, + "distance_m": 7652.43017578125, + "colour": { + "file": "card-1-t30-colour.webp", + "bytes": 1816 + }, + "geometry": { + "file": "card-1-t30-geometry.webp", + "bytes": 28380 + } + }, + { + "top": 344, + "h": 256, + "distance_m": 39515.10546875, + "colour": { + "file": "card-2-t30-colour.webp", + "bytes": 756 + }, + "geometry": { + "file": "card-2-t30-geometry.webp", + "bytes": 4638 + } + } + ], + [ + { + "top": 330, + "h": 270, + "distance_m": 597.7586059570312, + "colour": { + "file": "card-0-t31-colour.webp", + "bytes": 506 + }, + "geometry": { + "file": "card-0-t31-geometry.webp", + "bytes": 5788 + } + }, + { + "top": 85, + "h": 515, + "distance_m": 7773.806640625, + "colour": { + "file": "card-1-t31-colour.webp", + "bytes": 1642 + }, + "geometry": { + "file": "card-1-t31-geometry.webp", + "bytes": 25034 + } + }, + { + "top": 326, + "h": 274, + "distance_m": 39216.27734375, + "colour": { + "file": "card-2-t31-colour.webp", + "bytes": 760 + }, + "geometry": { + "file": "card-2-t31-geometry.webp", + "bytes": 4148 + } + } + ] + ], + "bytes": 1210136, + "attribution": { + "credit_line": "Contains modified Copernicus data: DEM \u00a9 DLR e.V. 2010-2014 and \u00a9 Airbus Defence and Space GmbH 2014-2018 provided under COPERNICUS by the European Union and ESA; all rights reserved.", + "licence": "Copernicus DEM licence: free, full and open access, with the credit line shown", + "dem_source": "Copernicus DEM GLO-30 (30 m)", + "url": "https://spacedata.copernicus.eu/collections/copernicus-digital-elevation-model" + } +} diff --git a/scripts/bake-horizon.py b/scripts/bake-horizon.py deleted file mode 100644 index 372e70e8..00000000 --- a/scripts/bake-horizon.py +++ /dev/null @@ -1,123 +0,0 @@ -#!/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 [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() diff --git a/scripts/ridge-bake/.gitignore b/scripts/ridge-bake/.gitignore new file mode 100644 index 00000000..c18dd8d8 --- /dev/null +++ b/scripts/ridge-bake/.gitignore @@ -0,0 +1 @@ +__pycache__/ diff --git a/scripts/ridge-bake/README.md b/scripts/ridge-bake/README.md new file mode 100644 index 00000000..97b02a77 --- /dev/null +++ b/scripts/ridge-bake/README.md @@ -0,0 +1,62 @@ +# ridge-bake + +Offline baker for the ridge backdrop: it turns a Copernicus DEM into K+1 G-buffer cards per place, split by K authored seams and cut into 32 azimuth tiles round the whole 360 degree ring, plus a `manifest.json` (schema 3) and an `index.json` that the runtime reads. Each card tile is a colour WebP (albedo and coverage) and a geometry WebP (normal and log-distance). The baker is not shipped; `public/ridge/` holds its output. The client owns lighting, haze and ink: no sun, haze or shadow is baked. + +## Run + +```sh +python3 -I scripts/ridge-bake/export.py --tiles DIR --out public/ridge/ [--work DIR] [--sheet contact.png] +``` + +Needs Python 3 with `numpy`, `tifffile` and `imagecodecs`. `--tiles` is a directory of Copernicus GLO-30 tiles (never committed); `--work` caches the mosaic and rays (default `$TMPDIR/ridge-bake-work`); `--sheet` writes the contact sheet at 1/4 of the ring's width (the ring composite, every card's strip alone and the depth image with every seam, the 32 tile boundaries drawn, lit by one fixed light). The bake prints `r_max_m`, the resident run and the worst fit error per card. `python3 -I scripts/ridge-bake/export.py --write-schema` rewrites `ridge-bake.schema.json`, which the tests pin. + +Tests: `RIDGE_PY= RIDGE_TILES=DIR scripts/ridge-bake/tests/run.sh [test_ridge.py|mutate.py]` (`mutate.py` re-introduces each rule's failure into a copy of the baker and fails if a test does not notice). + +## Tiles per preset (`places.json`) + +Files are `Copernicus_DSM_COG_10_dd_00_ddd_00_DEM.tif`; the list below is `ddddd`. + +| place id | tiles | +|---|---| +| vienna | N47E015 N47E016 N47E017 N48E015 N48E016 N48E017 N49E015 N49E016 | +| matterhorn | N45E007 N45E008 N46E007 N46E008 | +| fuji | N34E138 N34E139 N35E137 N35E138 N35E139 | +| halfdome | N37W121 N37W120 N38W120 | +| grandcanyon | N35W113 N35W112 N36W113 N36W112 | +| amadablam | N27E086 N27E087 N28E086 N28E087 | +| trecime | N46E011 N46E012 | + +## Where the bakes ran + +Yggdrasil (16 cores, 62 GB), as `mind-void-self`, work under `/var/tmp/ridge-bake` (never `/tmp`, a 31 GB tmpfs): `venv/` (python 3.13 with `numpy`, `tifffile`, `imagecodecs` from PyPI), `tiles/`, `work//`, one `out//` per place until its look is accepted. Tiles come from the public Copernicus DEM GLO-30 AWS Open Data bucket: `https://copernicus-dem-30m.s3.amazonaws.com//.tif` with `` = `Copernicus_DSM_COG_10_dd_00_ddd_00_DEM` (17 tiles, 598 MB). + +The authored splits sit in depth gaps found by scanning candidate lists (seam medians printed per list): `seams` flees a split that falls inside a continuous mass of visible terrain to the nearest gap, so a split inside the mass yields an empty card 0 (Matterhorn's visible terrain is one mass from 4.9 to 15 km; gaps at 19, 28 and 43 km). Place splits at the gap medians the scan reports. + +## Cards + +`places.json` gives each preset `card_split_km`, an ordered list of 1 to 5 seam depths in km, and optionally `prefilter_m`. A preset without `card_split_km` is refused, and so is a split that leaves a card empty (the message names the splits); K splits make K+1 cards, at most `MAX_CARDS` = 6 per place. New places get a seam probe look before their first bake. + +1. **March.** `stage0` marches 6400 azimuth columns of rays over the DEM with Earth curvature and refraction (`ridge.elev`), cached by a key of its inputs. +2. **Low-pass.** `prefilter` blurs the sampled heights with a Gaussian of `prefilter_m` metres along each ray and across rays at equal distance (sigma = `prefilter_m` / (distance x column width) columns), then recomputes the angles. Roofs go, hills stay. +3. **View.** `set_view` maps angle to row linearly: the highest skyline angle of the whole ring sits at 4% of the frame height, the lowest at 66%, and the horizon keeps `GROUND_ROWS_MIN` = 150 rows under it (the runtime's `groundRowsNeeded`: (1 - 0.85) x 600 / 0.6, so the plane reaches the bottom of every viewport at rest). The scale is the lesser of the two fits, clamped to 0.5x to 10x vertical exaggeration (rulings `ridge-ring-vertical-anchors`, `ridge-ground-rows-below-horizon`: every azimuth sits inside one frame; a place whose whole-ring relief leaves too few ground rows is flattened below 1x); a skyline that cannot hold the rows even at 0.5x is refused naming `sky_deg` and the floor. `export.validate_manifest` refuses a plane with fewer than 150 rows under the horizon and `manifest.ts` refuses it at load. +4. **Seams.** `coverage` counts the visible rows of the opaque view per log-distance bin and column. `seams` finds one seam per authored split per column by dynamic programming (seam carving, forward energy): it sits in a gap between depths, moving it costs 2 per bin plus the visible rows it sweeps (so it never hops across a ridge between two columns and splits it side by side), a seam inside visible terrain is cheap to cross-fade, the authored depth only breaks ties. Seam k stays 0.4 nat beyond seam k-1. The DP runs over the ring three times side by side and keeps the middle lap, so a seam is continuous across the wrap (column 6399 to 0) and a tile boundary is only a crop. +5. **Cards.** `cards` runs per tile, on that tile's columns and the matching normals (it is column-independent: a tile is a crop of per-column results, so no seam appears at a tile boundary). It makes card i from the first visible hit at or beyond seam i-1 (layered depth: a farther card keeps the terrain a nearer ridge hides), alpha 1 minus a smoothstep over seam i in log-distance (the cross-fade), crest rows with fractional coverage, distance and normal interpolated between samples by angle, albedo from a small height and slope material, cropped to the rows where alpha is not zero. The rows of card i > 0 below the angle of its first sample (hit and first sample of the card) are its **wall**: the extruded face of the ridge the card starts at, which keeps that sample's distance, wears the ground material at its height with the face up, and is flagged `wall`. Card 0 also draws the **near march** (ruling `ridge-near-ground-outline`): the place's own DEM from `NEAR_START_M` = 1 m to the near clip `NEAR_CLIP_M` = 500 m (`near_march`: float64 bilinear samples every max(1 m, 0.02 d) up to 10 m, about 170 per column, low-passed with the place's own `prefilter_m`), joined to the far march by `join_near` on the whole ring before the tile cut, its angles capped per column at the angle of the clip sample so the near ground draws inside the silhouette of the terrain at the clip (a near hill above that edge is cut along it). Its rows are ordinary terrain with their own normal and the albedo of their own height and n_up, flagged `near` in memory; `cards` refuses a march that starts at the clip. The runtime reads them as ground at the clip distance (they decode at `log_d_min`) and lights them like any card pixel. The alpha-over composite of the cards equals the opaque view; `check_cover` refuses a tile that differs by more than 0.02. +6. **Tiles.** The ring is absolute compass, column 0 = north, column c at azimuth (c + 0.5) / 6400 x 360; `places.json`'s `az_deg` / `look_at` is only the rest azimuth (`view.look_az_deg`). Tile t owns columns [200 t, 200 t + 200) (11.25 degrees) and its files hold [200 t - 2, 200 t + 202): two columns of real neighbour data each side (the client's ink pass and lighting read one texel each way; the client crops it), taken periodically by `ridge.ring_cols`. Per card and tile the file is cropped to the rows where that tile's 8-bit alpha is not zero (`top`, `h`); a card that holds nothing in a tile is `null` there (the client interpolates its distance from the neighbours); a card with no solid pixel in any tile is refused. +7. **Distance and the offset range.** The bake holds no camera (ruling `ridge-camera-full-ring`). `pack` gives each card tile `distance_m` = exp(median ln d) over the tile's solid pixels that are neither wall nor near ground (its interior 200 columns); the client derives each card's slide from that and the viewer's offset r and heading. `camera.r_max_m` is the largest |r| (never above half the nearest terrain's distance) at which, for every tile, card and phi (24 steps of the camera's angle on the circle against its heading; the offset-only rotation mode moves phi round the whole circle), the least-squares line `a + s beta` fitted to the exact view angle `atan2(R sin beta - r sin phi, R cos beta - r cos phi)` over the widest viewport (`HFOV_MAX_DEG` = 72 / 1.1) errs by at most `FIT_PX_MAX` = 24 card px (the continuous error: the line by quadrature over the viewport, the worst error looked for on 513 points, so a handful of samples cannot undercount it); the distance d is that of the NEAREST solid (alpha >= 0.5, neither wall nor near ground) pixel the card draws in the tile's interior columns, which is where the slide errs most (the line is fitted for the tile's `distance_m`, the median, but the bound is held for the nearest terrain: a tile whose terrain spans 600 to 2000 m is bound at 600 m); each tile's near pixels (under the clip) count as terrain at the clip, 500 m, alongside its solid pixels, whatever else the tile holds (they are drawn at the clip; a tile of near ground only is slid there too), so a tile with any near pixel binds at 500 m at the latest; and the resident gate (below) must hold at r_max_m too. `camera.r_max_forward_m` is the same search at phi = 0 alone (same `FIT_PX_MAX`, the same half-distance cap, the same resident gate): the camera pushed forward along its heading, which is where the offset stays when the view direction turns with it (the modes 'still' and 'both'), so it is at least `r_max_m`; the client takes `r_max_m` for the offset-only mode and for a backward offset, `r_max_forward_m` for a forward one in the other modes (`view.ts` `offsetRange`). `FIT_PX_MAX` is provisional, tuned by eye (ruling `ridge-offset-range-fit`). A bake whose `r_max_m` is below `R_MAX_FLOOR_M` = 25 m is refused, naming the card and tile. `distance_m` and the nearest-terrain table exclude the near ground (a tile with nothing outside it gets `distance_m` = 500 m), so card 0's distances are never nearer than the near clip (`write_bake` refuses one that is), and `r_max_m` and `r_max_forward_m` hold for the nearest solid terrain each card draws in each tile, at or beyond 500 m, a tile with near pixels counts them at 500 m: the ground nearer than that rides card 0's slide and is not measured beyond that. +8. **Normals.** `normals` takes the along-ray slope and the across-ray slope at equal distance (neighbouring columns, same sample), both times the vertical exaggeration. + +Files per card `i` and tile `t`: `card--t-colour.webp` (lossy RGB albedo, lossless straight alpha) and `card--t-geometry.webp` (lossless: R, G = (n + 1) / 2 for the normal's along and across components, B = log-distance normalised between `encoding.log_d_min` and `log_d_max`; wall pixels write R = G = 255, a code outside the unit disc that no real normal reaches), each 204 columns wide. The manifest lists the cards nearest first (`near_m`, `far_m`: the median seam depths over the ring) and `tiles[t][i]` = `{ top, h, distance_m, colour, geometry }` or `null`; the runtime paints the cards last to first. The `bake_id` is the sha256 of the files, tile-major, then card, colour then geometry. + +Budgets (`check_budget`; a cap is never raised to fit a bake, the lever is `TILES` = 64): every file of one tile at most 235 kB (1.5 MB per 72 degrees), every file of the place at most 7.5 MB, at most 6 cards, and the lit canvases (4 bytes x 202 columns x band rows, per card) of the worst run of N consecutive tiles, cyclic, at most 20 MB, where N = ceil(arc_max / 11.25) + 5 and arc_max = `HFOV_MAX_DEG` / s_min + 2 (r_max / Rmin) 57.3 degrees with Rmin the nearest card's smallest tile distance and s_min = Rmin / (Rmin + r_max). The loader decodes one tile at a time, so the decode transient is not gated. + +## Materials + +`places.json` `materials` is the one owner of ground colour (ruling `ridge-place-colour-authored`: the topology is real, the colour is authored). A material is `{ base: rgb, ramps: [{ from_m, to_m, colour }], steep: { colour } | null, snow: { from_m, to_m, colour } | null }`: `ridge.albedo(h, n_up, material)` lerps `base` through each ramp in order by height, then to the steep colour on steep faces (null: strata hold on cliffs), then to the snow colour on flat ground above its band. A place names its `material` (absent: `alpine`, the numbers the baker had before materials, pinned by an oracle test); an unknown name is refused (`ridge.load_material`). The bake id hashes the manifest and tile bytes, not the material, so a material change reaches the id only through the colours it bakes. `canyon` (Grand Canyon strata by height at the Unkar reach) was approved by eye on the contact sheet (ruling `grandcanyon-palette-approved`). + +## Licence + +Elevation: Copernicus DEM GLO-30. The credit line is written into every manifest (`attribution`) and must be shown with any rendering: + +> 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. + +Licence: free, full and open access, with the credit line shown (https://spacedata.copernicus.eu/collections/copernicus-digital-elevation-model). diff --git a/scripts/ridge-bake/export.py b/scripts/ridge-bake/export.py new file mode 100644 index 00000000..42769221 --- /dev/null +++ b/scripts/ridge-bake/export.py @@ -0,0 +1,314 @@ +"""Ridge backdrop export: bake a place with ridge.py and write its K+1 G-buffer cards as 32 azimuth tiles each (colour + geometry WebP per card per tile), a manifest v3 and the index. + + python3 -I scripts/ridge-bake/export.py --tiles DIR --out public/ridge/ [--work DIR] [--sheet contact.png] + python3 -I scripts/ridge-bake/export.py --write-schema (rewrites ridge-bake.schema.json from SCHEMA below) + +The runtime reads manifest.json (SCHEMA is its contract) and nothing else about the bake. The ring is the whole 360 degrees (ruling ridge-camera-full-ring), absolute compass, column 0 = north, cut into TILES tiles of TILE_W columns plus an APRON of real neighbour +columns each side; the bake holds no camera: it ships each card tile's distance_m and camera.r_max_m, the largest offset the per-card linear slide can take (ruling ridge-offset-range-fit); the client lights the cards itself (ruling ridge-cards-runtime-lit). +The pure parts (budget, bake_id, index, schema check) import no baker; bake_place imports ridge, which needs RIDGE_TILES and RIDGE_WORK (main sets them from --tiles / --work), and so do pack, validate_manifest and write_bake, which read ridge's NEAR_CLIP_M and GROUND_ROWS_MIN.""" +import os, sys, json, math, shutil, hashlib, argparse, tempfile +from pathlib import Path +from zoneinfo import ZoneInfo, ZoneInfoNotFoundError +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +from refusal import Refusal +import numpy as np, imagecodecs + +BAKER_VERSION = 7 +RING_W = 6400 # the ring's columns (ridge.W, asserted in bake_place): column c is at azimuth (c + 0.5) / RING_W x 360, column 0 = north +TILES = 32 # azimuth tiles of the ring, each card cut into TILES files per kind (ruling ridge-camera-full-ring: the client loads the arc near its heading) +TILE_W = RING_W // TILES # 200 columns = 11.25 degrees owned by a tile +APRON = 2 # real neighbour columns each side in a tile's file: the client's ink pass and lighting read +-1 texel; the client crops it +LIT_W = TILE_W + 2 # a lit canvas keeps one apron texel each side +TILE_DEG = 360.0 / TILES +MAX_CARDS = 6 # per place; a card is cropped to its row band in every tile, which is what lets a livelier place have more +TILE_BYTES_MAX = 235_000 # every file of one tile (1.5 MB per 72 degrees, scaled to 11.25) +PLACE_BYTES_MAX = 7_500_000 # every file of the place +RESIDENT_BYTES_MAX = 20_000_000 # the lit canvases (4 B x LIT_W x band h per card) of the worst run of consecutive tiles, cyclic; the loader decodes one tile at a time, so the decode transient is not gated +HFOV_MAX_DEG = 72 / 1.1 # the widest viewport: a 16:9 viewport with 1.1 widths of plane (view.ts windowFor) +FIT_PX_MAX = 24.0 # the per-card linear slide may err by this many card pixels over the viewport (provisional, tuned by eye: ruling ridge-offset-range-fit) +R_MAX_FLOOR_M = 25.0 # a bake whose cards cannot take this offset is refused +PHI_STEPS = 24 # the camera's angle on its circle against its heading, sampled by the r_max search +COVER_TOL = 0.02 # the composite of a tile's cards may differ from the opaque view by this much of a pixel, nowhere more +WEBP_QUALITY = 80 +SHEET_SKY = (0.80, 0.86, 0.94) # the flat sky of the contact sheet +SHEET_LIGHT = (-0.35, 0.55, 0.76) # the fixed light of the contact sheet in (along ray, across ray, up); the sheet is a look at the cards, the client lights the real thing +ATTRIBUTION = dict( + credit_line='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.', + licence='Copernicus DEM licence: free, full and open access, with the credit line shown', + dem_source='Copernicus DEM GLO-30 (30 m)', + url='https://spacedata.copernicus.eu/collections/copernicus-digital-elevation-model') + +# ------------------------------------------------------------------------------------ schema (the one dict the schema file and the validator both come from) +_num, _int, _str = {'type': 'number'}, {'type': 'integer'}, {'type': 'string'} +_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 _objnull(**props): return dict(_obj(**props), type=['object', 'null']) +_file = _obj(file=_str, bytes=_int) +SCHEMA = {'$schema': 'https://json-schema.org/draft/2020-12/schema', 'title': 'ridge-bake manifest v3 and index v1', '$defs': { + 'manifest': _obj(schema={'const': 3}, baker_version=_int, bake_id=_str, + place=_obj(id=_str, name=_str, lat=_num, lon=_num, altitude_km=_num, eye_m=_num, tz=_tz), + view=_obj(look_az_deg=_num, ring_w={'const': RING_W}, tile_w={'const': TILE_W}, tiles={'const': TILES}, apron={'const': APRON}, 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), + encoding=_obj(log_d_min=_num, log_d_max=_num, normal={'const': 'rt8'}), + camera=dict(_obj(r_max_m=_num, r_max_forward_m=_num), description="r_max_m (every camera angle on its circle) and r_max_forward_m (the camera on its heading) are the offsets up to which the linear slide holds (the fit error at most FIT_PX_MAX card px) for the NEAREST solid terrain (at or beyond the near clip, ridge.NEAR_CLIP_M, 500 m) that each card draws in each tile, not for the tile's median distance_m; a tile whose card 0 draws only near ground (under the clip) is slid at the clip distance (its distance_m) and binds at 500 m. The ground under the clip is drawn by card 0 from the near march and is otherwise not measured."), + cards={'type': 'array', 'minItems': 1, 'maxItems': MAX_CARDS, 'items': _obj(near_m=_numnull, far_m=_numnull), + 'description': "nearest first; the runtime paints the list last to first. near_m and far_m are the median seam depths over the ring, null at the ends."}, + tiles={'type': 'array', 'minItems': TILES, 'maxItems': TILES, 'items': {'type': 'array', 'minItems': 1, 'maxItems': MAX_CARDS, 'items': _objnull(top=_int, h=_int, distance_m=_num, colour=_file, geometry=_file)}, + 'description': "tiles[t][i] is card i in tile t, or null where the card holds nothing in that tile (the client takes its distance from the neighbouring tiles). Tile t owns the ring columns [tile_w t, tile_w (t + 1)), column c at azimuth (c + 0.5) / ring_w x 360, 0 = north; its files hold [tile_w t - apron, tile_w (t + 1) + apron), wrapping at the ring's end, and are tile_w + 2 apron columns wide. top and h place the card's band back at its rows of the frame; distance_m = exp(median ln d) of the card's solid pixels in the tile that are neither wall nor near ground, under the near clip (the interior tile_w columns); a tile whose card draws only near ground gets the clip distance."}, + bytes=_int, + attribution=_obj(credit_line=_str, licence=_str, dem_source=_str, url=_str)), + 'index': _obj(schema={'const': 1}, default=_str, places={'type': 'object', 'additionalProperties': _str})}} +def tile_file(i, t, kind): return f'card-{i}-t{t:02d}-{kind}.webp' + +def validate(x, s, path='$'): + """The subset of JSON Schema SCHEMA uses; raises Refusal naming the 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)} + if tys and not any(isinstance(x, py[t]) and not (isinstance(x, bool) and t != 'null') for t in tys): raise Refusal(f'{path}: not a {"/".join(tys)}') + if s.get('format') == 'iana-tz': + try: ZoneInfo(x) + except (ZoneInfoNotFoundError, ValueError, OSError): raise Refusal(f'{path}: {x!r} is not a time zone the system knows') + if 'const' in s and x != s['const']: raise Refusal(f"{path}: must be {s['const']!r}") + if 'enum' in s and x not in s['enum']: raise Refusal(f'{path}: not one of {s["enum"]}') + if 'maximum' in s and x > s['maximum']: raise Refusal(f'{path}: above {s["maximum"]}') + if isinstance(x, list): + if not s.get('minItems', 0) <= len(x) <= s.get('maxItems', 1 << 30): raise Refusal(f'{path}: wrong length') + for i, v in enumerate(x): validate(v, s['items'], f'{path}[{i}]') + if isinstance(x, dict): + props = s.get('properties', {}); extra = s.get('additionalProperties', True) + for k in s.get('required', []): + if k not in x: raise Refusal(f'{path}: missing {k}') + for k, v in x.items(): + if k in props: validate(v, props[k], f'{path}.{k}') + elif extra is False: raise Refusal(f'{path}: extra key {k}') + elif isinstance(extra, dict): validate(v, extra, f'{path}.{k}') + +def validate_manifest(m): + """The schema plus what it cannot say: the plane keeps ridge.GROUND_ROWS_MIN rows under the horizon, every tile lists one entry per card, every card holds something in some tile, each file is named for its card and tile, bytes is the sum of the files.""" + import ridge + validate(m, SCHEMA['$defs']['manifest']); k = len(m['cards']); v = m['view'] + if v['plane_h'] - v['horizon_row'] < ridge.GROUND_ROWS_MIN - 1e-6: raise Refusal(f"$.view: {v['plane_h'] - v['horizon_row']:.1f} rows under the horizon, below the {ridge.GROUND_ROWS_MIN} the runtime needs (ridge.GROUND_ROWS_MIN)") + for t, row in enumerate(m['tiles']): + if len(row) != k: raise Refusal(f'$.tiles[{t}]: {len(row)} entries for {k} cards') + for i, e in enumerate(row): + for kind in (('colour', 'geometry') if e else ()): + if e[kind]['file'] != tile_file(i, t, kind): raise Refusal(f'$.tiles[{t}][{i}].{kind}: file {e[kind]["file"]!r} is not {tile_file(i, t, kind)!r}') + for i in range(k): + if all(row[i] is None for row in m['tiles']): raise Refusal(f'card {i} is null in every tile') + if m['bytes'] != sum(e[kind]['bytes'] for row in m['tiles'] for e in row if e for kind in ('colour', 'geometry')): raise Refusal('bytes is not the sum of the files') + +# ------------------------------------------------------------------------------------ cards -> bytes +def u8(a): return np.clip(np.rint(np.asarray(a) * 255.0), 0, 255).astype(np.uint8) +def encode_colour(albedo, alpha): + """Lossy RGB albedo with lossless alpha coverage, straight (not premultiplied); the colour under a zero alpha is zeroed.""" + a = u8(alpha); rgb = u8(albedo) * (a[..., None] > 0); return bytes(imagecodecs.webp_encode(np.dstack([rgb, a]), level=WEBP_QUALITY, lossless=False)) +def encode_geometry(n_r, n_t, logd, enc, wall=None): + """Lossless, opaque RGB: R, G = (n_r + 1) / 2, (n_t + 1) / 2 ('rt8'), B = the log-distance normalised between enc log_d_min and log_d_max (a log-distance under log_d_min, the near ground under the clip, encodes as 0: the clip distance). Wall pixels (the extruded face under a ridge; wall (h, w) bool) write R = G = 255: a code outside the unit disc + that no real normal reaches (real r2 + t2 peaks at 0.998), which the runtime reads as 'normal up, no crease'.""" + b = (np.asarray(logd) - enc['log_d_min']) / (enc['log_d_max'] - enc['log_d_min']); r, t = u8((np.asarray(n_r) + 1) / 2), u8((np.asarray(n_t) + 1) / 2) + if wall is not None: m = np.asarray(wall, bool); r, t = np.where(m, 255, r).astype(np.uint8), np.where(m, 255, t).astype(np.uint8) + return bytes(imagecodecs.webp_encode(np.dstack([r, t, u8(b)]), lossless=True)) +def decode(b): + """A WebP's bytes as RGBA uint8; the codec returns RGB for an image that is opaque everywhere, which is solid.""" + a = imagecodecs.webp_decode(b) + return a if a.shape[-1] == 4 else np.concatenate([a, np.full(a.shape[:2] + (1,), 255, np.uint8)], -1) + +def composite_alpha(cards, h, w): + """Coverage of the alpha-over of all cards, each (top, rgba uint8 or float alpha (rows, w)) placed at its rows of an h x w frame.""" + clear = np.ones((h, w)) + for top, al in cards: clear[top:top + al.shape[0]] *= 1 - np.asarray(al, np.float64) + return 1 - clear +def check_cover(cards, opaque, tol=COVER_TOL): + """Refuse a bake whose cards, alpha-over, differ from the opaque view's coverage by more than tol anywhere: a hole shows the sky through terrain, an excess is a ghost. cards: [(top, alpha 0..1 (rows, w))], opaque (h, w).""" + err = np.abs(composite_alpha(cards, *opaque.shape) - opaque); bad = err > tol + if bad.any(): y, x = np.unravel_index(int(np.argmax(err)), err.shape); raise Refusal(f'the cards do not composite to the opaque view within {tol}: {int(bad.sum())} pixels differ, worst {err.max():.3f} at x={x} row {y}') + +def run_tiles(r_max_m, rmin_m): + """N, the consecutive tiles the loader keeps resident: the viewport arc at the smallest slide rate plus the offset's own swing (arc_max = HFOV_MAX_DEG / s_min + 2 (r_max / Rmin) 57.3 degrees, s_min = Rmin / (Rmin + r_max)), one straddled tile and two tiles of margin each side.""" + s_min = rmin_m / (rmin_m + r_max_m); arc = HFOV_MAX_DEG / s_min + 2 * (r_max_m / rmin_m) * 57.3 + return min(TILES, math.ceil(arc / TILE_DEG) + 1 + 4) +def resident_bytes(bands, n): + """The lit canvases (4 bytes x LIT_W x band rows, per card) of the worst run of n consecutive tiles of the ring, wrapping. bands[t]: the row counts of the cards that tile holds.""" + per = [sum(4 * LIT_W * h for h in b) for b in bands]; n = min(n, TILES) + return max(sum(per[(t + k) % TILES] for k in range(n)) for t in range(TILES)) +def check_budget(n_cards, tile_bytes, bands, r_max_m, rmin_m): + """Refuse a bake the runtime could not hold: more than MAX_CARDS cards, a tile whose files together are above TILE_BYTES_MAX, every file of the place above PLACE_BYTES_MAX, or the worst run of run_tiles(r_max_m, rmin_m) consecutive tiles lit above RESIDENT_BYTES_MAX.""" + if n_cards > MAX_CARDS: raise Refusal(f'{n_cards} cards, above {MAX_CARDS}') + for t, b in enumerate(tile_bytes): + if b > TILE_BYTES_MAX: raise Refusal(f'tile {t} is {b} bytes, above {TILE_BYTES_MAX}') + if sum(tile_bytes) > PLACE_BYTES_MAX: raise Refusal(f'the place is {sum(tile_bytes)} bytes, above {PLACE_BYTES_MAX}') + n = run_tiles(r_max_m, rmin_m); res = resident_bytes(bands, n) + if res > RESIDENT_BYTES_MAX: raise Refusal(f'{n} consecutive tiles light to {res} bytes, above {RESIDENT_BYTES_MAX}') + +FIT_QUAD = 48 # Gauss-Legendre nodes for the least-squares line (exact for the smooth alpha(beta) to far below a card pixel) +FIT_GRID = 513 # points the worst error is looked for on, ends included: the error is smooth between them, so the maximum found is within 0.01 card px of the continuous one +def fit_px(d, r, px_per_deg, phis=None): + """The worst error, in card pixels, of a card tile's linear slide at offset r (m): over the camera's angle phi on its circle against its heading (`phis` steps, PHI_STEPS by default; 1 is phi = 0 alone, the camera pushed forward along its heading) and the viewport (beta in +-HFOV_MAX_DEG / 2), the exact view angle of a cylinder point at the tile's + distance d, alpha = atan2(d sin beta - r sin phi, d cos beta - r cos phi), against the continuous least-squares line a + s beta over the viewport (ruling ridge-offset-range-fit; the line by quadrature, the error on FIT_GRID points: it is the continuous worst error, not the error of a few samples).""" + half = math.radians(HFOV_MAX_DEG) / 2; p = np.linspace(0, 2 * math.pi, PHI_STEPS if phis is None else phis, endpoint=False)[:, None] + alpha = lambda b: np.arctan2(d * np.sin(b) - r * np.sin(p), d * np.cos(b) - r * np.cos(p)); x, w = np.polynomial.legendre.leggauss(FIT_QUAD); bq = half * x[None, :]; A = alpha(bq) + a0 = (A * w).sum(-1, keepdims=True) / 2; s = (A * bq * w).sum(-1, keepdims=True) / (bq * bq * w).sum(); b = np.linspace(-half, half, FIT_GRID)[None, :] + return math.degrees(float(np.abs(alpha(b) - (a0 + s * b)).max())) * px_per_deg +def fit_table(dist, r, px_per_deg, phis=None): + """(tiles, cards) fit_px of every card tile at offset r; nan where the card is null in that tile.""" + return np.array([[np.nan if d is None else fit_px(d, r, px_per_deg, phis) for d in row] for row in dist]) +def solve_r_max(dist, bands, px_per_deg, phis=None): + """dist: [tiles][cards] the distance of the NEAREST solid terrain each card draws in each tile (None where it draws none): the line of a tile is fitted for one distance but its terrain spans many, and the nearest is where the slide errs most (ruling ridge-offset-range-fit, up to where the linear map holds). + The largest offset r (m, down to 0.1 m) at which every card tile fits within FIT_PX_MAX over `phis` camera angles (PHI_STEPS: the whole circle, the offset-only rotation mode; 1: phi = 0 alone, the modes where the offset turns with the view) and the resident gate holds: never above half the nearest card's smallest tile distance. Scans r upward from 0 on 128 steps to the first failure, then bisects that step. + Refuses (naming the card and tile that bind) a bake whose r_max_m is below R_MAX_FLOOR_M.""" + near = min((row[0], t) for t, row in enumerate(dist) if row[0] is not None); rmin = near[0]; cap = 0.5 * rmin + ok = lambda r: bool(np.nanmax(fit_table(dist, r, px_per_deg, phis)) <= FIT_PX_MAX) and resident_bytes(bands, run_tiles(r, rmin)) <= RESIDENT_BYTES_MAX + lo, hi = 0.0, None + for r in np.linspace(0, cap, 129)[1:]: + if ok(r): lo = float(r) + else: hi = float(r); break + if hi is None: lo = cap + else: + for _ in range(24): + mid = 0.5 * (lo + hi) + if ok(mid): lo = mid + else: hi = mid + r_max = math.floor(lo * 10) / 10 + if r_max < R_MAX_FLOOR_M: + if cap < R_MAX_FLOOR_M: raise Refusal(f'r_max_m {r_max:g} is below {R_MAX_FLOOR_M:g} m: card 0 stands {rmin:.0f} m away in tile {near[1]} and the offset stays under half of that') + tb = fit_table(dist, R_MAX_FLOOR_M, px_per_deg, phis); t, i = np.unravel_index(int(np.nanargmax(tb)), tb.shape) + if tb[t, i] > FIT_PX_MAX: raise Refusal(f'r_max_m {r_max:g} is below {R_MAX_FLOOR_M:g} m: card {i} in tile {t} errs {tb[t, i]:.1f} card px at {R_MAX_FLOOR_M:g} m (the bound is {FIT_PX_MAX:g})') + n = run_tiles(R_MAX_FLOOR_M, rmin); raise Refusal(f'r_max_m {r_max:g} is below {R_MAX_FLOOR_M:g} m: at {R_MAX_FLOOR_M:g} m, {n} consecutive tiles light to {resident_bytes(bands, n)} bytes, above {RESIDENT_BYTES_MAX}') + return r_max + +BAKE_ID_BLANK = '0' * 12 +def bake_id(manifest_text, files): + """First 12 hex of sha256 over the whole bake: the manifest.json text as written with its bake_id value BAKE_ID_BLANK (the id cannot hash itself), then the tile files, tile-major then card, colour then geometry (a null card tile writes none), so any change to the manifest or a tile is a new directory. + files: [(colour bytes, geometry bytes)] in that order.""" + h = hashlib.sha256(); h.update(manifest_text.encode('utf-8')) + for colour, geometry in files: h.update(colour); h.update(geometry) + return h.hexdigest()[:12] + +def write_bake(out, place, view, meta, packed, opaque, default=None): + """Write out/-/ (tile WebPs + manifest.json; the id addresses both), rewrite out/index.json, delete the place's previous dir. packed: dict(cards [dict(near_m, far_m)], tiles [TILES][cards] of dict(top, colour bytes, geometry bytes, distance_m) or None, + camera dict(r_max_m, r_max_forward_m)); opaque: TILES arrays (plane_h, TILE_W + 2 APRON), each the opaque view's coverage over a tile's columns. Refuses before writing a bake whose files decode to the wrong size, leave the frame, break a budget (the resident gate at r_max_m and at r_max_forward_m) or composite + away from the opaque view in any tile. meta: dict(curvature, encoding). Returns the directory.""" + cards, tiles, camera = packed['cards'], packed['tiles'], packed['camera']; k = len(cards); h = view['plane_h']; w = TILE_W + 2 * APRON + if len(tiles) != TILES or len(opaque) != TILES or any(len(row) != k for row in tiles): raise Refusal(f'the bake needs {TILES} tiles of {k} cards each') + for i in range(k): + if all(row[i] is None for row in tiles): raise Refusal(f'card {i} is null in every tile') + dec = [[None if e is None else (decode(e['colour']), decode(e['geometry'])) for e in row] for row in tiles]; bands = [[pair[0].shape[0] for pair in row if pair] for row in dec]; tile_bytes = [] + for t, (row, drow) in enumerate(zip(tiles, dec)): + tile_bytes.append(sum(len(e['colour']) + len(e['geometry']) for e in row if e)) + for i, (e, pair) in enumerate(zip(row, drow)): + if e is None: continue + c, g = pair + if c.shape[:2] != g.shape[:2]: raise Refusal(f'tile {t} card {i}: colour and geometry are not one size') + if c.shape[1] != w: raise Refusal(f'tile {t} card {i} is {c.shape[1]} columns wide, not {w} (tile {TILE_W} + 2 apron {APRON})') + if c.shape[0] < 1 or e['top'] < 0 or e['top'] + c.shape[0] > h: raise Refusal(f'tile {t} card {i} leaves the {h} rows of the frame') + if opaque[t].shape != (h, w): raise Refusal(f'tile {t}: the opaque view is {opaque[t].shape}, the frame {(h, w)}') + import ridge + rmin = min(row[0]['distance_m'] for row in tiles if row[0]) # distance_m is exp of a float32 log: it lands a few parts in 1e7 off the clip, so the compare keeps 1e-5 of slack + if rmin < ridge.NEAR_CLIP_M * (1 - 1e-5): raise Refusal(f'card 0 stands {rmin:.1f} m away, nearer than the near clip {ridge.NEAR_CLIP_M:g} m: the distance of card 0 is measured at or beyond the clip (the near ground under it is not measured)') + if camera['r_max_forward_m'] < camera['r_max_m']: raise Refusal(f"r_max_forward_m {camera['r_max_forward_m']:g} is below r_max_m {camera['r_max_m']:g}: phi = 0 is one of the angles r_max_m holds for") + for r in (camera['r_max_m'], camera['r_max_forward_m']): check_budget(k, tile_bytes, bands, r, rmin) + for t, (row, drow) in enumerate(zip(tiles, dec)): + try: check_cover([(e['top'], pair[0][..., 3] / 255.0) for e, pair in zip(row, drow) if e], opaque[t]) + except Refusal as ex: raise Refusal(f'tile {t}: {ex}') + out = Path(out) + manifest = dict(schema=3, baker_version=BAKER_VERSION, bake_id=BAKE_ID_BLANK, place=place, view=dict(view, ring_w=RING_W, tile_w=TILE_W, tiles=TILES, apron=APRON), curvature=meta['curvature'], encoding=dict(meta['encoding'], normal='rt8'), camera=dict(r_max_m=camera['r_max_m'], r_max_forward_m=camera['r_max_forward_m']), + cards=[dict(near_m=c['near_m'], far_m=c['far_m']) for c in cards], + tiles=[[None if e is None else dict(top=e['top'], h=pair[0].shape[0], distance_m=e['distance_m'], colour=dict(file=tile_file(i, t, 'colour'), bytes=len(e['colour'])), geometry=dict(file=tile_file(i, t, 'geometry'), bytes=len(e['geometry']))) + for i, (e, pair) in enumerate(zip(row, drow))] for t, (row, drow) in enumerate(zip(tiles, dec))], bytes=sum(tile_bytes), attribution=ATTRIBUTION) + validate_manifest(manifest); text = json.dumps(manifest, indent=1) + '\n'; blank = f'"bake_id": "{BAKE_ID_BLANK}"'; assert text.count(blank) == 1 + bid = bake_id(text, [(e['colour'], e['geometry']) for row in tiles for e in row if e]); name = f"{place['id']}-{bid}"; dest = out / name; text = text.replace(blank, f'"bake_id": "{bid}"') + out.mkdir(parents=True, exist_ok=True); tmp = Path(tempfile.mkdtemp(dir=out, prefix='.bake-')) + for t, row in enumerate(tiles): + for i, e in enumerate(row): + if e: (tmp / tile_file(i, t, 'colour')).write_bytes(e['colour']); (tmp / tile_file(i, t, 'geometry')).write_bytes(e['geometry']) + (tmp / 'manifest.json').write_bytes(text.encode('utf-8')) # bytes, so the platform's newline cannot move the file under its id + idx_path = out / 'index.json'; idx = json.loads(idx_path.read_text()) if idx_path.exists() else dict(schema=1, default=place['id'], places={}) + old = idx['places'].get(place['id']); idx['places'][place['id']] = name; idx['default'] = default or (idx['default'] if idx['default'] in idx['places'] else place['id']) + validate(idx, SCHEMA['$defs']['index']) + if dest.exists(): shutil.rmtree(dest) + os.rename(tmp, dest); (out / '.index.tmp').write_bytes((json.dumps(idx, indent=1) + '\n').encode('utf-8')); os.replace(out / '.index.tmp', idx_path) + if old and old != name: shutil.rmtree(out / old, ignore_errors=True) + return dest + +# ------------------------------------------------------------------------------------ the bake +def cut_ring(d, a, h, splits_km, near, material): + """The ring cut of a prefiltered march (set_view done) and its near march (ridge.near_march): coverage, the periodic seams and the opaque view on the far march (d, a), the join of the near ground and the normals on all RING_W columns (ridge.join_near), then ridge.cards per tile on its TILE_W + 2 APRON columns of the joined march. Returns dict(cards [TILES][cards] (ridge.cards arrays), + splits_km, seams (K, ring) in m, cov (bins, ring), opaque [TILES] (rows, TILE_W + 2 APRON) coverage, edges).""" + import ridge + cov = ridge.coverage(d, a); sm = ridge.seams(cov, [k * 1000.0 for k in splits_km], d); op = ridge.opaque(a); D, A, Hc, nrm = ridge.join_near(d, a, h, near); cols = lambda x, t: ridge.ring_cols(x, t * TILE_W - APRON, TILE_W + 2 * APRON); tiles = [] + for t in range(TILES): tiles.append(ridge.cards(D, cols(A, t), cols(Hc, t), cols(sm, t), tuple(cols(x, t) for x in nrm), material=material)); print(f'tile {t + 1}/{TILES}', file=sys.stderr, flush=True) + return dict(cards=tiles, splits_km=list(splits_km), seams=sm, cov=cov, opaque=[cols(op, t) for t in range(TILES)], edges=ridge.log_edges(d)) + +def bake_place(pid): + """stage 0, prefilter, set_view on the whole ring, cut_ring: dict(place, view, meta, v, and cut_ring's cards, splits_km, seams, cov, opaque, edges). Needs RIDGE_TILES / RIDGE_WORK.""" + import ridge + assert ridge.W == RING_W and ridge.H > 0 + p = ridge.load_preset(pid); material = ridge.load_material(p.get('material', 'alpine')); p = ridge.configure(p); 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)); ring = cut_ring(d, a, h, p['card_split_km'], ridge.near_march(p.get('prefilter_m', 0) or 0), material) + 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) + 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]))) + return dict(place=place, view=view, meta=meta, v=v, **ring) + +def pack(bake): + """The tiles of a bake as bytes plus their manifest facts. Per card tile: distance_m = exp(median ln d) over the solid (alpha >= 0.5) pixels that are neither wall nor near ground (under the clip) of the interior TILE_W columns (a tile with none falls back to its non-wall, then any, lit pixels, near ground never; a tile with nothing outside the near ground gets ridge.NEAR_CLIP_M: the near ground itself is not measured, but such a tile is slid at that distance and binds r_max there); + a card with no rows in a tile is null there. Per card: the median seam depths over the ring. camera.r_max_m: solve_r_max over the NEAREST solid non-wall pixel of each card tile (not its median distance_m; each tile's near pixels, under the clip, count as terrain at the clip alongside its solid pixels, whatever else the tile holds: they are drawn at the clip) and every camera angle on its circle (the offset-only rotation mode), camera.r_max_forward_m: the same at phi = 0 alone (the modes where the offset turns with the view). Refuses a card empty in every tile (naming the splits) and a card with + no solid terrain apart from its wall in any tile. Returns dict(cards, tiles, camera, report) (report is printed, not written).""" + import ridge + sm = bake['seams']; sp = bake['splits_km']; k = len(sp) + 1; ppd = bake['view']['px_per_deg_h']; inner = slice(APRON, APRON + TILE_W); enc = bake['meta']['encoding'] + for i in range(k): + if all(tile[i]['alpha'].shape[0] == 0 for tile in bake['cards']): raise Refusal(f"card {i} is empty: it lies between the splits {' and '.join(f'{sp[j]:g} km' for j in (i - 1, i) if 0 <= j < len(sp))} (card_split_km {sp}) and holds no terrain nothing nearer hides; move or remove a split") + tiles, dist, near, bands = [], [], [], []; any_solid = [False] * k + for tile in bake['cards']: + row, drow, nrow, brow = [], [], [], [] + for i, c in enumerate(tile): + if c['alpha'].shape[0] == 0: row.append(None); drow.append(None); nrow.append(None); continue + al, wl, ld, nr = c['alpha'][:, inner], c['wall'][:, inner], c['logd'][:, inner], c['near'][:, inner]; solid = (al >= 0.5) & ~wl & ~nr; any_solid[i] |= bool(solid.any()) + pool = next(((m, l) for m, l in ((solid, ld), ((al > 0) & ~wl & ~nr, ld), ((al > 0) & ~nr, ld), ((c['alpha'] > 0) & ~c['near'], c['logd'])) if m.any()), None) + dm = float(np.exp(np.median(pool[1][pool[0]]))) if pool else ridge.NEAR_CLIP_M; nrow.append(min((v for v in (float(np.exp(ld[solid].min())) if solid.any() else None, ridge.NEAR_CLIP_M if ((al >= 0.5) & nr).any() else None) if v is not None), default=None)) # the nearest terrain the card draws in this tile: its solid pixels, and its near pixels as terrain at the clip (they are drawn at the clip whatever else the tile holds); None where it draws only wall or faint pixels + row.append(dict(top=c['top'], colour=encode_colour(c['albedo'], c['alpha']), geometry=encode_geometry(c['n_r'], c['n_t'], c['logd'], enc, c['wall']), distance_m=dm)); drow.append(dm); brow.append(c['alpha'].shape[0]) + tiles.append(row); dist.append(drow); near.append(nrow); bands.append(brow) + for i in range(k): + if not any_solid[i]: raise Refusal(f'card {i} holds no solid terrain apart from its wall rows') + r_max = solve_r_max(near, bands, ppd); r_fwd = solve_r_max(near, bands, ppd, phis=1); rmin = min(row[0] for row in near if row[0] is not None); n = run_tiles(r_fwd, rmin); worst = np.nanmax(fit_table(near, r_max, ppd), axis=0) + cards = [dict(near_m=float(np.median(sm[i - 1])) if i else None, far_m=float(np.median(sm[i])) if i < len(sm) else None) for i in range(k)] + return dict(cards=cards, tiles=tiles, camera=dict(r_max_m=r_max, r_max_forward_m=r_fwd), report=dict(fit_px=[float(x) for x in worst], run_tiles=n, resident_bytes=resident_bytes(bands, n), nearest_m=rmin)) # nearest_m: the nearest solid terrain of the place + +def lit(c): + """albedo x (0.35 + 0.65 max(n.L, 0)) under the fixed sheet light, with the card's alpha: (rgb, alpha). Wall pixels are lit with the face up, as the runtime reads their code.""" + wall = c['wall']; n_r, n_t = np.where(wall, 0.0, c['n_r']), np.where(wall, 0.0, c['n_t']) + up = np.sqrt(np.clip(1 - n_r ** 2 - n_t ** 2, 0, 1)); L = np.array(SHEET_LIGHT) / np.linalg.norm(SHEET_LIGHT); nl = np.clip(n_r * L[0] + n_t * L[1] + up * L[2], 0, 1) + return c['albedo'] * (0.35 + 0.65 * nl)[..., None], c['alpha'] +def sheet(bake): + """Contact sheet (png bytes) at 1/4 of the ring's width, stacked: the ring composite, every card's strip alone, and the depth image (log-distance bins, far at the top, every seam); the TILES tile boundaries drawn on each. All lit by SHEET_LIGHT over the flat + SHEET_SKY; reads the arrays the encoder writes (each tile's interior columns, the apron dropped).""" + h = bake['opaque'][0].shape[0]; k = len(bake['cards'][0]); sky = np.broadcast_to(np.array(SHEET_SKY, np.float32), (h, RING_W, 3)); rgbs = [np.zeros((h, RING_W, 3), np.float32) for _ in range(k)]; als = [np.zeros((h, RING_W), np.float32) for _ in range(k)] + for t, tile in enumerate(bake['cards']): + for i, c in enumerate(tile): + if c['alpha'].shape[0] == 0: continue + rgb, al = lit(c); sl = slice(c['top'], c['top'] + al.shape[0]); x0 = t * TILE_W; rgbs[i][sl, x0:x0 + TILE_W] = rgb[:, APRON:APRON + TILE_W]; als[i][sl, x0:x0 + TILE_W] = al[:, APRON:APRON + TILE_W] + comp = sky.copy(); panels = [] + for rgb, al in zip(rgbs, als): panels.append(sky * (1 - al[..., None]) + rgb * al[..., None]) + for rgb, al in zip(reversed(rgbs), reversed(als)): comp = comp * (1 - al[..., None]) + rgb * al[..., None] + q = lambda a: a.reshape((a.shape[0], RING_W // 4, 4) + a.shape[2:]).mean(2); mark = np.arange(TILES) * TILE_W // 4; red = np.array([1.0, 0.2, 0.2]) + def bounds(img): img[:, mark] = 0.45 * img[:, mark] + 0.55 * red; return img + cov = bake['cov'][:, ::4]; w = cov.shape[1]; img = np.repeat(np.log1p(cov[::-1]) / np.log1p(cov.max()), 2, 0); depth = np.dstack([img] * 3) * 0.92 + 0.04; nb = cov.shape[0]; cols = np.arange(w) + for j, s in enumerate(bake['seams']): + b = np.clip(np.searchsorted(bake['edges'], np.log(s[::4]), 'right') - 1, 0, nb - 1); col = [(0.24, 0.78, 1.0), (1.0, 0.47, 0.24), (0.6, 1.0, 0.4), (1.0, 0.9, 0.3), (0.9, 0.4, 1.0)][j % 5] + for dy in (0, 1): depth[(nb - 1 - b) * 2 + dy, cols] = col + return bytes(imagecodecs.png_encode(u8(np.concatenate([bounds(q(comp))] + [bounds(q(p)) for p in panels] + [bounds(depth)], 0)))) + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__.split('\n')[0]); ap.add_argument('place', nargs='?'); ap.add_argument('--tiles'); ap.add_argument('--out'); ap.add_argument('--work'); ap.add_argument('--sheet'); ap.add_argument('--write-schema', action='store_true') + a = ap.parse_args(argv) + if a.write_schema: (HERE / 'ridge-bake.schema.json').write_bytes((json.dumps(SCHEMA, indent=1, ensure_ascii=False) + '\n').encode('utf-8')); return 0 + if not (a.place and a.tiles and a.out): ap.error('place, --tiles and --out are required') + os.environ['RIDGE_TILES'] = a.tiles; os.environ['RIDGE_WORK'] = a.work or os.path.join(os.environ.get('TMPDIR', tempfile.gettempdir()), 'ridge-bake-work'); os.makedirs(os.environ['RIDGE_WORK'], exist_ok=True) + bake = bake_place(a.place) + if a.sheet: Path(a.sheet).write_bytes(sheet(bake)) + packed = pack(bake); rp = packed['report'] + print(f"r_max_m {packed['camera']['r_max_m']:g} r_max_forward_m {packed['camera']['r_max_forward_m']:g} nearest card {rp['nearest_m']:.0f} m resident run {rp['run_tiles']} tiles = {rp['resident_bytes']} bytes worst fit error per card (card px, bound {FIT_PX_MAX:g}) {[round(x, 1) for x in rp['fit_px']]}", file=sys.stderr, flush=True) + dest = write_bake(a.out, bake['place'], bake['view'], bake['meta'], packed, bake['opaque']); print(dest); return 0 + +if __name__ == '__main__': sys.exit(main()) diff --git a/scripts/ridge-bake/places.json b/scripts/ridge-bake/places.json new file mode 100644 index 00000000..d5101a5d --- /dev/null +++ b/scripts/ridge-bake/places.json @@ -0,0 +1,815 @@ +{ + "_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 is the rest azimuth, where the view looks at rest (or az_deg); the ring itself is the whole 360 degrees, absolute compass, column 0 = north; 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).", + "_materials": "materials = the authored ground colour of a place (the topology is real, the colour is GameCult's own depiction; ruling ridge-place-colour-authored). A material: base = rgb under every ramp; ramps = [{from_m, to_m, colour}] lerped over height in order (each takes the running colour to its own over from_m..to_m, then holds it); steep = {colour} | null: the colour of steep faces (n_up under 0.93, full at 0.68), null keeps the height colour on cliffs; snow = {from_m, to_m, colour} | null: lerped in over its band on flat ground. A place names its `material`; absent means alpine; an unknown name is refused by the baker.", + "materials": { + "alpine": { + "base": [ + 0.36, + 0.44, + 0.26 + ], + "ramps": [ + { + "from_m": 150, + "to_m": 900, + "colour": [ + 0.22, + 0.31, + 0.2 + ] + }, + { + "from_m": 1300, + "to_m": 2000, + "colour": [ + 0.47, + 0.44, + 0.41 + ] + } + ], + "steep": { + "colour": [ + 0.47, + 0.44, + 0.41 + ] + }, + "snow": { + "from_m": 1900, + "to_m": 2300, + "colour": [ + 0.93, + 0.95, + 0.97 + ] + } + }, + "canyon": { + "base": [ + 0.62, + 0.52, + 0.4 + ], + "ramps": [ + { + "from_m": 1000, + "to_m": 1080, + "colour": [ + 0.55, + 0.3, + 0.2 + ] + }, + { + "from_m": 1150, + "to_m": 1300, + "colour": [ + 0.72, + 0.38, + 0.22 + ] + }, + { + "from_m": 1300, + "to_m": 1350, + "colour": [ + 0.45, + 0.33, + 0.25 + ] + }, + { + "from_m": 1400, + "to_m": 1450, + "colour": [ + 0.5, + 0.52, + 0.42 + ] + }, + { + "from_m": 1550, + "to_m": 1600, + "colour": [ + 0.62, + 0.48, + 0.42 + ] + }, + { + "from_m": 1800, + "to_m": 1850, + "colour": [ + 0.52, + 0.24, + 0.18 + ] + }, + { + "from_m": 2050, + "to_m": 2070, + "colour": [ + 0.85, + 0.76, + 0.58 + ] + }, + { + "from_m": 2150, + "to_m": 2170, + "colour": [ + 0.72, + 0.68, + 0.58 + ] + }, + { + "from_m": 2300, + "to_m": 2400, + "colour": [ + 0.3, + 0.38, + 0.24 + ] + } + ], + "steep": null, + "snow": null + } + }, + "presets": [ + { + "id": "vienna", + "tz": "Europe/Vienna", + "name": "Vienna, looking SW to Rax/Schneeberg", + "kind": "far range over a flat foreground", + "lat": 48.1929826, + "lon": 16.3534237, + "eye_h_m": 30.0, + "ground_override_m": 183.3, + "az_deg": 214.0, + "rmax_km": 95, + "card_split_km": [ + 6, + 40 + ], + "prefilter_m": 100, + "viewpoint_source": { + "status": "existing observer of the round-1 mockup (the scene camera used by the game), not photo-sourced; eye 30 m above ground as in round 1" + } + }, + { + "id": "matterhorn", + "tz": "Europe/Zurich", + "name": "Matterhorn from the Gornergrat", + "kind": "lone horn, close, 27 deg of relief", + "lat": 45.983139, + "lon": 7.782466, + "eye_h_m": 1.6, + "look_at": [ + 45.97666, + 7.65678 + ], + "rmax_km": 60, + "initial_guess_not_used": { + "lat": 45.9856, + "lon": 7.7452 + }, + "viewpoint_source": { + "status": "sourced", + "source": "Wikimedia Commons geosearch (namespace 6), geotagged photos", + "query": "geosearch ns=6 gslimit=500 gsradius=10000 around 25 centres (peak + 3 rings x 8 bearings, radii 3600-12000 m), then EXIF GPSImgDirection of every file in range via prop=imageinfo&iiprop=commonmetadata", + "files_found": 5003, + "in_range": 3241, + "with_exif_heading": 205, + "facing_the_peak": 52, + "pool": "photos whose camera heading is within 30 deg of the bearing to the summit", + "rule": "densest 1 km cell of photos 3000-12000 m from the summit whose EXIF camera heading faces the summit (within 30 deg) with the summit visible on the DEM (straight line, first 250 m ignored, 8 m clutter allowed); viewpoint = median coordinate of the cell", + "median_camera_heading_deg": 245.8, + "photos_in_cell": 7, + "cells_tried": [ + { + "n_facing": 7, + "lat": 45.98314, + "lon": 7.78247, + "peak_visible": true + } + ], + "distance_to_peak_m": 9749, + "bearing_to_peak_deg": 265.8, + "dem_ground_m": 3090.7, + "eye_height_rule": "DEM ground at the viewpoint + 1.6 m (the source gives no eye height)", + "sample_files": [ + { + "title": "File:Gornergrat-04.jpg", + "lat": 45.983061, + "lon": 7.782031, + "heading": 256.0, + "url": "https://commons.wikimedia.org/wiki/File%3AGornergrat-04.jpg" + }, + { + "title": "File:Gornergrat-03.jpg", + "lat": 45.983058, + "lon": 7.782038, + "heading": 245.8, + "url": "https://commons.wikimedia.org/wiki/File%3AGornergrat-03.jpg" + }, + { + "title": "File:Gornergrat-07.jpg", + "lat": 45.982653, + "lon": 7.782466, + "heading": 250.2, + "url": "https://commons.wikimedia.org/wiki/File%3AGornergrat-07.jpg" + }, + { + "title": "File:Gornergratsee 2021 10.jpg", + "lat": 45.986958, + "lon": 7.780303, + "heading": 243.4, + "url": "https://commons.wikimedia.org/wiki/File%3AGornergratsee_2021_10.jpg" + }, + { + "title": "File:Early morning Eiger.jpg", + "lat": 45.983242, + "lon": 7.783361, + "heading": 254.7, + "url": "https://commons.wikimedia.org/wiki/File%3AEarly_morning_Eiger.jpg" + }, + { + "title": "File:Klein Matterhorn mit Wolken an Theodulhorn und Furgghorn \u00fcber dem Oberen Theodulgletscher- a view from Gornergrat 2021 02 (cropped).jpg", + "lat": 45.983139, + "lon": 7.784172, + "heading": 242.1, + "url": "https://commons.wikimedia.org/wiki/File%3AKlein_Matterhorn_mit_Wolken_an_Theodulhorn_und_Furgghorn_%C3%BCber_dem_Oberen_Theodulgletscher-_a_view_from_Gornergrat_2021_02_%28cropped%29.jpg" + }, + { + "title": "File:Breithorn and neighbours from Gornergrat 2021 02.jpg", + "lat": 45.983139, + "lon": 7.784172, + "heading": 242.1, + "url": "https://commons.wikimedia.org/wiki/File%3ABreithorn_and_neighbours_from_Gornergrat_2021_02.jpg" + } + ], + "exif_headings": [ + { + "title": "File:Gornergrat-04.jpg", + "heading": 256.0 + }, + { + "title": "File:Gornergrat-03.jpg", + "heading": 245.8 + }, + { + "title": "File:Gornergrat-07.jpg", + "heading": 250.2 + }, + { + "title": "File:Gornergratsee 2021 10.jpg", + "heading": 243.4 + }, + { + "title": "File:Early morning Eiger.jpg", + "heading": 254.7 + }, + { + "title": "File:Klein Matterhorn mit Wolken an Theodulhorn und Furgghorn \u00fcber dem Oberen Theodulgletscher- a view from Gornergrat 2021 02 (cropped).jpg", + "heading": 242.1 + }, + { + "title": "File:Breithorn and neighbours from Gornergrat 2021 02.jpg", + "heading": 242.1 + } + ], + "n_with_exif_heading": 7, + "summit_dem_m": 4324.9, + "summit_nominal": [ + 45.97639, + 7.65833 + ] + }, + "card_split_km": [ + 18, + 28, + 43 + ] + }, + { + "id": "fuji", + "tz": "Asia/Tokyo", + "name": "Fuji from Shiraito Falls", + "kind": "lone cone, smooth", + "lat": 35.312467222222494, + "lon": 138.587223194445, + "eye_h_m": 1.6, + "look_at": [ + 35.36061, + 138.72731 + ], + "rmax_km": 60, + "initial_guess_not_used": { + "lat": 35.4994, + "lon": 138.7686 + }, + "viewpoint_source": { + "status": "sourced", + "source": "Wikimedia Commons geosearch (namespace 6), geotagged photos", + "query": "geosearch ns=6 gslimit=500 gsradius=10000 around 25 centres (peak + 3 rings x 8 bearings, radii 9000-30000 m), then EXIF GPSImgDirection of every file in range via prop=imageinfo&iiprop=commonmetadata", + "files_found": 6494, + "in_range": 4280, + "with_exif_heading": 588, + "facing_the_peak": 132, + "pool": "photos whose camera heading is within 30 deg of the bearing to the summit", + "rule": "densest 1 km cell of photos 8000-30000 m from the summit whose EXIF camera heading faces the summit (within 30 deg) with the summit visible on the DEM (straight line, first 250 m ignored, 8 m clutter allowed); viewpoint = median coordinate of the cell", + "median_camera_heading_deg": 64.4, + "photos_in_cell": 8, + "cells_tried": [ + { + "n_facing": 15, + "lat": 35.36248, + "lon": 138.86287, + "peak_visible": false + }, + { + "n_facing": 8, + "lat": 35.31247, + "lon": 138.58722, + "peak_visible": true + } + ], + "distance_to_peak_m": 13808, + "bearing_to_peak_deg": 67.2, + "dem_ground_m": 486.9, + "eye_height_rule": "DEM ground at the viewpoint + 1.6 m (the source gives no eye height)", + "sample_files": [ + { + "title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 03.JPG", + "lat": 35.31114, + "lon": 138.5886, + "heading": 48.0, + "url": "https://commons.wikimedia.org/wiki/File%3A%E5%AF%8C%E5%A3%AB%E5%B1%B1%EF%BC%88%E3%81%B5%E3%81%98%E3%81%95%E3%82%93%E3%80%81%E8%8B%B1%E8%AA%9E%EF%BC%9AMount_Fuji%EF%BC%89_03.JPG" + }, + { + "title": "File:Mount Fuji, view from Shiraito no Taki.jpg", + "lat": 35.313589, + "lon": 138.588394, + "heading": 68.8, + "url": "https://commons.wikimedia.org/wiki/File%3AMount_Fuji%2C_view_from_Shiraito_no_Taki.jpg" + }, + { + "title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 02.JPG", + "lat": 35.313248055556, + "lon": 138.58760805556, + "heading": 64.2, + "url": "https://commons.wikimedia.org/wiki/File%3A%E5%AF%8C%E5%A3%AB%E5%B1%B1%EF%BC%88%E3%81%B5%E3%81%98%E3%81%95%E3%82%93%E3%80%81%E8%8B%B1%E8%AA%9E%EF%BC%9AMount_Fuji%EF%BC%89_02.JPG" + }, + { + "title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 07.JPG", + "lat": 35.312428055556, + "lon": 138.58723138889, + "heading": 88.8, + "url": "https://commons.wikimedia.org/wiki/File%3A%E5%AF%8C%E5%A3%AB%E5%B1%B1%EF%BC%88%E3%81%B5%E3%81%98%E3%81%95%E3%82%93%E3%80%81%E8%8B%B1%E8%AA%9E%EF%BC%9AMount_Fuji%EF%BC%89_07.JPG" + }, + { + "title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 08.JPG", + "lat": 35.312418055556, + "lon": 138.587215, + "heading": 64.0, + "url": "https://commons.wikimedia.org/wiki/File%3A%E5%AF%8C%E5%A3%AB%E5%B1%B1%EF%BC%88%E3%81%B5%E3%81%98%E3%81%95%E3%82%93%E3%80%81%E8%8B%B1%E8%AA%9E%EF%BC%9AMount_Fuji%EF%BC%89_08.JPG" + }, + { + "title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 04.JPG", + "lat": 35.312478055556, + "lon": 138.58717805556, + "heading": 62.2, + "url": "https://commons.wikimedia.org/wiki/File%3A%E5%AF%8C%E5%A3%AB%E5%B1%B1%EF%BC%88%E3%81%B5%E3%81%98%E3%81%95%E3%82%93%E3%80%81%E8%8B%B1%E8%AA%9E%EF%BC%9AMount_Fuji%EF%BC%89_04.JPG" + }, + { + "title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 06.JPG", + "lat": 35.312456388889, + "lon": 138.58715805556, + "heading": 65.2, + "url": "https://commons.wikimedia.org/wiki/File%3A%E5%AF%8C%E5%A3%AB%E5%B1%B1%EF%BC%88%E3%81%B5%E3%81%98%E3%81%95%E3%82%93%E3%80%81%E8%8B%B1%E8%AA%9E%EF%BC%9AMount_Fuji%EF%BC%89_06.JPG" + }, + { + "title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 05.JPG", + "lat": 35.312479722222, + "lon": 138.58714138889, + "heading": 64.5, + "url": "https://commons.wikimedia.org/wiki/File%3A%E5%AF%8C%E5%A3%AB%E5%B1%B1%EF%BC%88%E3%81%B5%E3%81%98%E3%81%95%E3%82%93%E3%80%81%E8%8B%B1%E8%AA%9E%EF%BC%9AMount_Fuji%EF%BC%89_05.JPG" + } + ], + "exif_headings": [ + { + "title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 03.JPG", + "heading": 48.0 + }, + { + "title": "File:Mount Fuji, view from Shiraito no Taki.jpg", + "heading": 68.8 + }, + { + "title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 02.JPG", + "heading": 64.2 + }, + { + "title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 07.JPG", + "heading": 88.8 + }, + { + "title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 08.JPG", + "heading": 64.0 + }, + { + "title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 04.JPG", + "heading": 62.2 + }, + { + "title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 06.JPG", + "heading": 65.2 + }, + { + "title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 05.JPG", + "heading": 64.5 + } + ], + "n_with_exif_heading": 8, + "summit_dem_m": 3765.5, + "summit_nominal": [ + 35.36061, + 138.72731 + ] + }, + "card_split_km": [ + 1.5, + 16 + ] + }, + { + "id": "halfdome", + "tz": "America/Los_Angeles", + "name": "Half Dome from the Yosemite Valley floor (Sentinel Bridge photo cell)", + "kind": "granite wall across a valley", + "lat": 37.745833333333, + "lon": -119.592606, + "eye_h_m": 1.6, + "look_at": [ + 37.74435, + -119.53426 + ], + "rmax_km": 40, + "initial_guess_not_used": { + "lat": 37.7305, + "lon": -119.5734 + }, + "viewpoint_source": { + "status": "sourced", + "source": "Wikimedia Commons geosearch (namespace 6), geotagged photos", + "query": "geosearch ns=6 gslimit=500 gsradius=10000 around 25 centres (peak + 3 rings x 8 bearings, radii 2700-9000 m), then EXIF GPSImgDirection of every file in range via prop=imageinfo&iiprop=commonmetadata", + "files_found": 2505, + "in_range": 1788, + "with_exif_heading": 181, + "facing_the_peak": 64, + "pool": "photos whose camera heading is within 30 deg of the bearing to the summit", + "rule": "densest 1 km cell of photos 2000-9000 m from the summit whose EXIF camera heading faces the summit (within 30 deg) with the summit visible on the DEM (straight line, first 250 m ignored, 8 m clutter allowed); viewpoint = median coordinate of the cell", + "median_camera_heading_deg": 91.6, + "photos_in_cell": 9, + "cells_tried": [ + { + "n_facing": 9, + "lat": 37.73853, + "lon": -119.57124, + "peak_visible": false + }, + { + "n_facing": 9, + "lat": 37.74583, + "lon": -119.59261, + "peak_visible": true + } + ], + "distance_to_peak_m": 5138, + "bearing_to_peak_deg": 91.8, + "dem_ground_m": 1209.2, + "eye_height_rule": "DEM ground at the viewpoint + 1.6 m (the source gives no eye height)", + "sample_files": [ + { + "title": "File:Yosemite National Park - 51700634719.jpg", + "lat": 37.746606, + "lon": -119.590317, + "heading": 87.0, + "url": "https://commons.wikimedia.org/wiki/File%3AYosemite_National_Park_-_51700634719.jpg" + }, + { + "title": "File:Half Dome, Yosemite National Park - 53324601178.jpg", + "lat": 37.748264, + "lon": -119.592606, + "heading": 98.8, + "url": "https://commons.wikimedia.org/wiki/File%3AHalf_Dome%2C_Yosemite_National_Park_-_53324601178.jpg" + }, + { + "title": "File:Half Dome, Yosemite National Park - 53324824955.jpg", + "lat": 37.748322, + "lon": -119.592736, + "heading": 90.1, + "url": "https://commons.wikimedia.org/wiki/File%3AHalf_Dome%2C_Yosemite_National_Park_-_53324824955.jpg" + }, + { + "title": "File:2013-09-19 18 35 25 Half Dome and the Merced River in Yosemite National Park.JPG", + "lat": 37.7435, + "lon": -119.58966666667, + "heading": 91.6, + "url": "https://commons.wikimedia.org/wiki/File%3A2013-09-19_18_35_25_Half_Dome_and_the_Merced_River_in_Yosemite_National_Park.JPG" + }, + { + "title": "File:Half Dome from the Yosemite Valley floor in mid-Spring.jpeg", + "lat": 37.745833333333, + "lon": -119.59233333333, + "heading": 92.0, + "url": "https://commons.wikimedia.org/wiki/File%3AHalf_Dome_from_the_Yosemite_Valley_floor_in_mid-Spring.jpeg" + }, + { + "title": "File:Sentinel Bridge & Half Dome.jpg", + "lat": 37.743419, + "lon": -119.590562, + "heading": 86.8, + "url": "https://commons.wikimedia.org/wiki/File%3ASentinel_Bridge_%26_Half_Dome.jpg" + }, + { + "title": "File:Half Dome pre Super moon 2.jpg", + "lat": 37.745769, + "lon": -119.592972, + "heading": 106.5, + "url": "https://commons.wikimedia.org/wiki/File%3AHalf_Dome_pre_Super_moon_2.jpg" + }, + { + "title": "File:Half Dome pre Super moon.jpg", + "lat": 37.745747, + "lon": -119.593033, + "heading": 97.1, + "url": "https://commons.wikimedia.org/wiki/File%3AHalf_Dome_pre_Super_moon.jpg" + }, + { + "title": "File:Yosemite National Park 003.jpg", + "lat": 37.750814, + "lon": -119.598664, + "heading": 80.1, + "url": "https://commons.wikimedia.org/wiki/File%3AYosemite_National_Park_003.jpg" + } + ], + "exif_headings": [ + { + "title": "File:Yosemite National Park - 51700634719.jpg", + "heading": 87.0 + }, + { + "title": "File:Half Dome, Yosemite National Park - 53324601178.jpg", + "heading": 98.8 + }, + { + "title": "File:Half Dome, Yosemite National Park - 53324824955.jpg", + "heading": 90.1 + }, + { + "title": "File:2013-09-19 18 35 25 Half Dome and the Merced River in Yosemite National Park.JPG", + "heading": 91.6 + }, + { + "title": "File:Half Dome from the Yosemite Valley floor in mid-Spring.jpeg", + "heading": 92.0 + }, + { + "title": "File:Sentinel Bridge & Half Dome.jpg", + "heading": 86.8 + }, + { + "title": "File:Half Dome pre Super moon 2.jpg", + "heading": 106.5 + }, + { + "title": "File:Half Dome pre Super moon.jpg", + "heading": 97.1 + }, + { + "title": "File:Yosemite National Park 003.jpg", + "heading": 80.1 + } + ], + "n_with_exif_heading": 9, + "summit_dem_m": 2669.1, + "summit_nominal": [ + 37.74597, + -119.5329 + ] + } + }, + { + "id": "amadablam", + "tz": "Asia/Kathmandu", + "name": "Ama Dablam and Everest from Khumjung", + "kind": "far high range behind a near spire", + "lat": 27.822000000000003, + "lon": 86.722666666667, + "eye_h_m": 1.6, + "look_at": [ + 27.8617, + 86.86079 + ], + "rmax_km": 60, + "initial_guess_not_used": { + "lat": 27.8369, + "lon": 86.7643 + }, + "viewpoint_source": { + "status": "sourced", + "source": "Wikimedia Commons geosearch (namespace 6), geotagged photos", + "query": "geosearch ns=6 gslimit=500 gsradius=10000 around 25 centres (peak + 3 rings x 8 bearings, radii 4800-16000 m), then EXIF GPSImgDirection of every file in range via prop=imageinfo&iiprop=commonmetadata", + "files_found": 1398, + "in_range": 1143, + "with_exif_heading": 54, + "facing_the_peak": 13, + "pool": "photos whose camera heading is within 30 deg of the bearing to the summit", + "rule": "densest 1 km cell of photos 4000-16000 m from the summit whose EXIF camera heading faces the summit (within 30 deg) with the summit visible on the DEM (straight line, first 250 m ignored, 8 m clutter allowed); viewpoint = median coordinate of the cell", + "median_camera_heading_deg": 79.6, + "photos_in_cell": 2, + "cells_tried": [ + { + "n_facing": 2, + "lat": 27.822, + "lon": 86.72267, + "peak_visible": true + } + ], + "distance_to_peak_m": 14299, + "bearing_to_peak_deg": 72.0, + "dem_ground_m": 3782.0, + "eye_height_rule": "DEM ground at the viewpoint + 1.6 m (the source gives no eye height)", + "sample_files": [ + { + "title": "File:Thamserku (6).JPG", + "lat": 27.822666666667, + "lon": 86.722666666667, + "heading": 73.6, + "url": "https://commons.wikimedia.org/wiki/File%3AThamserku_%286%29.JPG" + }, + { + "title": "File:Thamserku (7).JPG", + "lat": 27.821333333333, + "lon": 86.722666666667, + "heading": 85.7, + "url": "https://commons.wikimedia.org/wiki/File%3AThamserku_%287%29.JPG" + } + ], + "exif_headings": [ + { + "title": "File:Thamserku (6).JPG", + "heading": 73.6 + }, + { + "title": "File:Thamserku (7).JPG", + "heading": 85.7 + } + ], + "n_with_exif_heading": 2, + "summit_dem_m": 6659.6, + "summit_nominal": [ + 27.8617, + 86.8614 + ] + }, + "card_split_km": [ + 2, + 18, + 34 + ] + }, + { + "id": "trecime", + "tz": "Europe/Rome", + "name": "Tre Cime di Lavaredo from the Dreizinnenhuette area, 2.4 km N (photo cell)", + "kind": "cirque wall, spires", + "lat": 46.636906, + "lon": 12.310064, + "eye_h_m": 1.6, + "look_at": [ + 46.61806, + 12.29583 + ], + "rmax_km": 40, + "initial_guess_not_used": { + "lat": 46.5833, + "lon": 12.2536 + }, + "viewpoint_source": { + "status": "sourced", + "source": "Wikimedia Commons geosearch (namespace 6), geotagged photos", + "query": "geosearch ns=6 gslimit=500 gsradius=10000 around 25 centres (peak + 3 rings x 8 bearings, radii 3000-10000 m), then EXIF GPSImgDirection of every file in range via prop=imageinfo&iiprop=commonmetadata", + "files_found": 2028, + "in_range": 763, + "with_exif_heading": 207, + "facing_the_peak": 33, + "pool": "photos whose camera heading is within 30 deg of the bearing to the summit", + "rule": "densest 1 km cell of photos 1500-10000 m from the summit whose EXIF camera heading faces the summit (within 30 deg) with the summit visible on the DEM (straight line, first 250 m ignored, 8 m clutter allowed); viewpoint = median coordinate of the cell", + "median_camera_heading_deg": 194.6, + "photos_in_cell": 5, + "cells_tried": [ + { + "n_facing": 5, + "lat": 46.63691, + "lon": 12.31006, + "peak_visible": true + } + ], + "distance_to_peak_m": 2363, + "bearing_to_peak_deg": 207.4, + "dem_ground_m": 2403.0, + "eye_height_rule": "DEM ground at the viewpoint + 1.6 m (the source gives no eye height)", + "sample_files": [ + { + "title": "File:Cime e Nuvole.jpg", + "lat": 46.63605, + "lon": 12.310064, + "heading": 200.3, + "url": "https://commons.wikimedia.org/wiki/File%3ACime_e_Nuvole.jpg" + }, + { + "title": "File:DreiZinnenP.jpg", + "lat": 46.636770555556, + "lon": 12.310305555556, + "heading": 180.1, + "url": "https://commons.wikimedia.org/wiki/File%3ADreiZinnenP.jpg" + }, + { + "title": "File:Soffio di sguardo.jpg", + "lat": 46.636906, + "lon": 12.311142, + "heading": 194.6, + "url": "https://commons.wikimedia.org/wiki/File%3ASoffio_di_sguardo.jpg" + }, + { + "title": "File:2405-DreizinnenH.jpg", + "lat": 46.637782777778, + "lon": 12.309966388889, + "heading": 178.4, + "url": "https://commons.wikimedia.org/wiki/File%3A2405-DreizinnenH.jpg" + }, + { + "title": "File:Dolomiten-Fingerkraut in den Sextener Dolomiten - N\u00e4he Drei-Zinnen-H\u00fctte (9801216636).jpg", + "lat": 46.642352, + "lon": 12.30829, + "heading": 200.0, + "url": "https://commons.wikimedia.org/wiki/File%3ADolomiten-Fingerkraut_in_den_Sextener_Dolomiten_-_N%C3%A4he_Drei-Zinnen-H%C3%BCtte_%289801216636%29.jpg" + } + ], + "exif_headings": [ + { + "title": "File:Cime e Nuvole.jpg", + "heading": 200.3 + }, + { + "title": "File:DreiZinnenP.jpg", + "heading": 180.1 + }, + { + "title": "File:Soffio di sguardo.jpg", + "heading": 194.6 + }, + { + "title": "File:2405-DreizinnenH.jpg", + "heading": 178.4 + }, + { + "title": "File:Dolomiten-Fingerkraut in den Sextener Dolomiten - N\u00e4he Drei-Zinnen-H\u00fctte (9801216636).jpg", + "heading": 200.0 + } + ], + "n_with_exif_heading": 5, + "summit_dem_m": 2746.9, + "summit_nominal": [ + 46.6186, + 12.3025 + ] + } + }, + { + "id": "grandcanyon", + "tz": "America/Phoenix", + "name": "Grand Canyon from Unkar and Cardenas", + "kind": "inner canyon from the river: walls rise above the horizon, layered strata", + "material": "canyon", + "lat": 36.0817, + "lon": -111.8551, + "eye_h_m": 1.6, + "az_deg": 290, + "rmax_km": 30, + "card_split_km": [ + 11.5, + 17.3, + 28.2 + ], + "viewpoint_source": { + "status": "chosen from three scanned river candidates (Nankoweap, Unkar/Cardenas, Phantom Ranch) by the operator, ruling ridge-grandcanyon-spot-unkar; the camera stands by the Colorado River inside the canyon (ruling ridge-grandcanyon-camera-inside); the preset is the cand-unkar preset of the candidate bakes (36.0817, -111.8551, az 290), whose camera_r_m -100 is not a field of the ring baker" + } + } + ] +} \ No newline at end of file diff --git a/scripts/ridge-bake/refusal.py b/scripts/ridge-bake/refusal.py new file mode 100644 index 00000000..213d8369 --- /dev/null +++ b/scripts/ridge-bake/refusal.py @@ -0,0 +1,2 @@ +"""The baker's refusal: raised wherever ridge.py or export.py declines a preset, a view or a bake. The fixtures catch this class only, so an exception from numpy or the standard library reaching them is a crash (mutate.py: CRASHED), never a kill.""" +class Refusal(ValueError): pass diff --git a/scripts/ridge-bake/ridge-bake.schema.json b/scripts/ridge-bake/ridge-bake.schema.json new file mode 100644 index 00000000..3f7f9b41 --- /dev/null +++ b/scripts/ridge-bake/ridge-bake.schema.json @@ -0,0 +1,327 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "ridge-bake manifest v3 and index v1", + "$defs": { + "manifest": { + "type": "object", + "required": [ + "schema", + "baker_version", + "bake_id", + "place", + "view", + "curvature", + "encoding", + "camera", + "cards", + "tiles", + "bytes", + "attribution" + ], + "additionalProperties": false, + "properties": { + "schema": { + "const": 3 + }, + "baker_version": { + "type": "integer" + }, + "bake_id": { + "type": "string" + }, + "place": { + "type": "object", + "required": [ + "id", + "name", + "lat", + "lon", + "altitude_km", + "eye_m", + "tz" + ], + "additionalProperties": false, + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "lat": { + "type": "number" + }, + "lon": { + "type": "number" + }, + "altitude_km": { + "type": "number" + }, + "eye_m": { + "type": "number" + }, + "tz": { + "type": "string", + "format": "iana-tz" + } + } + }, + "view": { + "type": "object", + "required": [ + "look_az_deg", + "ring_w", + "tile_w", + "tiles", + "apron", + "plane_h", + "px_per_deg_h", + "px_per_deg_v", + "exaggeration", + "horizon_row", + "sky_row", + "near_row" + ], + "additionalProperties": false, + "properties": { + "look_az_deg": { + "type": "number" + }, + "ring_w": { + "const": 6400 + }, + "tile_w": { + "const": 200 + }, + "tiles": { + "const": 32 + }, + "apron": { + "const": 2 + }, + "plane_h": { + "type": "integer" + }, + "px_per_deg_h": { + "type": "number" + }, + "px_per_deg_v": { + "type": "number" + }, + "exaggeration": { + "type": "number" + }, + "horizon_row": { + "type": "number" + }, + "sky_row": { + "type": "number" + }, + "near_row": { + "type": "number" + } + } + }, + "curvature": { + "type": "object", + "required": [ + "r_earth_m", + "k_ref" + ], + "additionalProperties": false, + "properties": { + "r_earth_m": { + "type": "number" + }, + "k_ref": { + "type": "number" + } + } + }, + "encoding": { + "type": "object", + "required": [ + "log_d_min", + "log_d_max", + "normal" + ], + "additionalProperties": false, + "properties": { + "log_d_min": { + "type": "number" + }, + "log_d_max": { + "type": "number" + }, + "normal": { + "const": "rt8" + } + } + }, + "camera": { + "type": "object", + "required": [ + "r_max_m", + "r_max_forward_m" + ], + "additionalProperties": false, + "properties": { + "r_max_m": { + "type": "number" + }, + "r_max_forward_m": { + "type": "number" + } + }, + "description": "r_max_m (every camera angle on its circle) and r_max_forward_m (the camera on its heading) are the offsets up to which the linear slide holds (the fit error at most FIT_PX_MAX card px) for the NEAREST solid terrain (at or beyond the near clip, ridge.NEAR_CLIP_M, 500 m) that each card draws in each tile, not for the tile's median distance_m; a tile whose card 0 draws only near ground (under the clip) is slid at the clip distance (its distance_m) and binds at 500 m. The ground under the clip is drawn by card 0 from the near march and is otherwise not measured." + }, + "cards": { + "type": "array", + "minItems": 1, + "maxItems": 6, + "items": { + "type": "object", + "required": [ + "near_m", + "far_m" + ], + "additionalProperties": false, + "properties": { + "near_m": { + "type": [ + "number", + "null" + ] + }, + "far_m": { + "type": [ + "number", + "null" + ] + } + } + }, + "description": "nearest first; the runtime paints the list last to first. near_m and far_m are the median seam depths over the ring, null at the ends." + }, + "tiles": { + "type": "array", + "minItems": 32, + "maxItems": 32, + "items": { + "type": "array", + "minItems": 1, + "maxItems": 6, + "items": { + "type": [ + "object", + "null" + ], + "required": [ + "top", + "h", + "distance_m", + "colour", + "geometry" + ], + "additionalProperties": false, + "properties": { + "top": { + "type": "integer" + }, + "h": { + "type": "integer" + }, + "distance_m": { + "type": "number" + }, + "colour": { + "type": "object", + "required": [ + "file", + "bytes" + ], + "additionalProperties": false, + "properties": { + "file": { + "type": "string" + }, + "bytes": { + "type": "integer" + } + } + }, + "geometry": { + "type": "object", + "required": [ + "file", + "bytes" + ], + "additionalProperties": false, + "properties": { + "file": { + "type": "string" + }, + "bytes": { + "type": "integer" + } + } + } + } + } + }, + "description": "tiles[t][i] is card i in tile t, or null where the card holds nothing in that tile (the client takes its distance from the neighbouring tiles). Tile t owns the ring columns [tile_w t, tile_w (t + 1)), column c at azimuth (c + 0.5) / ring_w x 360, 0 = north; its files hold [tile_w t - apron, tile_w (t + 1) + apron), wrapping at the ring's end, and are tile_w + 2 apron columns wide. top and h place the card's band back at its rows of the frame; distance_m = exp(median ln d) of the card's solid pixels in the tile that are neither wall nor near ground, under the near clip (the interior tile_w columns); a tile whose card draws only near ground gets the clip distance." + }, + "bytes": { + "type": "integer" + }, + "attribution": { + "type": "object", + "required": [ + "credit_line", + "licence", + "dem_source", + "url" + ], + "additionalProperties": false, + "properties": { + "credit_line": { + "type": "string" + }, + "licence": { + "type": "string" + }, + "dem_source": { + "type": "string" + }, + "url": { + "type": "string" + } + } + } + } + }, + "index": { + "type": "object", + "required": [ + "schema", + "default", + "places" + ], + "additionalProperties": false, + "properties": { + "schema": { + "const": 1 + }, + "default": { + "type": "string" + }, + "places": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + } + } + } +} diff --git a/scripts/ridge-bake/ridge.py b/scripts/ridge-bake/ridge.py new file mode 100644 index 00000000..46b82662 --- /dev/null +++ b/scripts/ridge-bake/ridge.py @@ -0,0 +1,305 @@ +"""Ridge baker: the ray march of a place, cut into K+1 layered-depth G-buffer cards by K authored seams (places.json), no painter, no sun. +Offline baker for the ridge backdrop (scripts/ridge-bake); export.py drives it. + + load_preset(id) -> configure() : observer, tiles, mosaic origin, ring radius, rest azimuth, card splits and prefilter from places.json + stage0(detail) : ray march of all 6400 azimuth columns (curvature+refraction), optional authored sub-DEM foreground detail, cached + prefilter(d, h, sigma_m) : Gaussian low-pass of the sampled heights (along each ray, across rays at equal distance), angles recomputed with elev + set_view(skyline) : authored Y mapping from the march skyline of the whole ring: angle -> row, see set_view + ring_cols(a, c0, n) : n columns of the ring from column c0, periodic (the tile cut) + coverage(d, a) / seams(cov, ..) : visible rows per log-distance bin; one forward-energy seam per authored split, per column, periodic round the ring + normals(d, h) / cards(...) : per-sample normals; the K+1 cards (coverage, distance, normal, albedo), each cropped to its band of rows +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 os, hashlib +from zoneinfo import ZoneInfo, ZoneInfoNotFoundError +from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from refusal import Refusal +import numpy as np, tifffile + +def _env_dir(name, what): + v = os.environ.get(name) + if not v: raise RuntimeError(f"{name} is not set: it must name {what} (no default location is assumed)") + return Path(v) +B = _env_dir('RIDGE_WORK', 'the work directory (the mosaic / ray caches)') +COP = _env_dir('RIDGE_TILES', 'the directory of Copernicus GLO-30 tiles (Copernicus_DSM_COG_10_*_DEM.tif)') +W = 6400 # ring columns: 360 deg at 17.78 px/deg +HPX_DEG = W / 360.0 +H = 600 # frame rows +COLW = math.radians(360.0 / W) +R_EARTH, KREF = 6371000.0, 0.13 + +P = {} # configured preset +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'): + """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') + from export import MAX_CARDS + if not sp: raise Refusal(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 Refusal(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 Refusal(f"preset {pid}: tz is required (an IANA time zone name such as Europe/Vienna)") + try: ZoneInfo(tz) + except (ZoneInfoNotFoundError, ValueError, OSError): raise Refusal(f"preset {pid}: tz {tz!r} is not a time zone the system knows") + return p + +# ====================================================================== configuration, DEM +def tiles_for(p): + lat, lon, r = p['lat'], p['lon'], p['rmax_km']; dl = r / 111.32; dn = r / (111.32 * math.cos(math.radians(lat))); out = [] + for la in range(math.floor(lat - dl), math.floor(lat + dl) + 1): + for lo in range(math.floor(lon - dn), math.floor(lon + dn) + 1): + cy = min(max(lat, la), la + 1); cx = min(max(lon, lo), lo + 1) + if math.hypot((cy - lat) * 111.32, (cx - lon) * 111.32 * math.cos(math.radians(lat))) <= r: out.append((la, lo)) + return out +def tile_path(la, lo): return COP / f"Copernicus_DSM_COG_10_{'N' if la >= 0 else 'S'}{abs(la):02d}_00_{'E' if lo >= 0 else 'W'}{abs(lo):03d}_00_DEM.tif" + +def cache_key(*parts): + """Short digest of everything a cached array was computed from. A cache file is read only under the key of its own inputs, so a changed preset field, tile list or baker constant never meets a stale file.""" + h = hashlib.sha256() + for q in parts: h.update(q.tobytes() if isinstance(q, np.ndarray) else repr(q).encode()); h.update(b'|') + return h.hexdigest()[:12] +def mosaic_key(p): return cache_key('mosaic.v1', sorted(tiles_for(p)), 3600) + +_mos = {} +def mosaic(p): + """Tile grid covering the circle (bounding rows/cols), cached as .npy per preset. Missing tiles (open sea has no GLO-30 tile) are zero.""" + key = (p['id'], mosaic_key(p)) + if key in _mos: return _mos[key] + ts = tiles_for(p); las = [t[0] for t in ts]; los = [t[1] for t in ts]; lat_top = max(las) + 1; lon_left = min(los) + c = B / f"mosaic-{p['id']}-{key[1]}.npy" + if c.exists(): m = np.load(c, mmap_mode='r') + else: + rows = [] + for la in range(max(las), min(las) - 1, -1): + rows.append(np.concatenate([tifffile.imread(tile_path(la, lo)) if tile_path(la, lo).exists() else np.zeros((3600, 3600), np.float32) for lo in range(min(los), max(los) + 1)], axis=1)) + m = np.concatenate(rows, axis=0).astype(np.float32); np.save(c, m) + _mos[key] = (m, lat_top, lon_left); return _mos[key] + +def bil(a, lat_top, lon_left, lat, lon): + y = (lat_top - lat) * 3600 - 0.5; x = (lon - lon_left) * 3600 - 0.5 + y0 = np.clip(np.floor(y).astype(int), 0, a.shape[0] - 2); x0 = np.clip(np.floor(x).astype(int), 0, a.shape[1] - 2) + fy = np.clip(y - y0, 0, 1); fx = np.clip(x - x0, 0, 1) + return (a[y0, x0] * (1 - fx) * (1 - fy) + a[y0, x0 + 1] * fx * (1 - fy) + a[y0 + 1, x0] * (1 - fx) * fy + a[y0 + 1, x0 + 1] * fx * fy) + +def configure(p): + """Set the module state for a preset: observer, eye elevation (DEM ground + eye height, or ground_override), rest azimuth (az_center: where the view looks at rest; the ring itself is absolute compass, column 0 = north).""" + global P + P = p; m, lt, ll = mosaic(p) + ground = p['ground_override_m'] if 'ground_override_m' in p else float(bil(m, lt, ll, np.array(p['lat']), np.array(p['lon']))) + P['ground_m'] = ground; P['eye_m'] = ground + p['eye_h_m'] + if 'look_at' in p: + la, lo = p['look_at']; P['az_center'] = (math.degrees(math.atan2((lo - p['lon']) * math.cos(math.radians(p['lat'])), la - p['lat'])) + 360) % 360 + else: P['az_center'] = p['az_deg'] + return P + +def ring_cols(a, c0, n): + """n columns of the ring array a (last axis W) from column c0 (negative or past W wraps): the one periodic take, the wrap at 0 / 360 degrees is handled here.""" + return np.take(a, (c0 + np.arange(n)) % W, axis=-1) + +# ====================================================================== authored sub-DEM foreground detail (Aetheria / CultMath ridged multifractal) +def _frac(v): return v - np.floor(v) +def _hash2(x, y): return _frac(np.sin(x * 127.1 + y * 311.7) * 43758.5453) # cultmath_hash(vec2), as Ratatoskr noise.ts +def _vnoise2(x, y): # cultmath_value_noise: 4 hashed corners, smoothstep blend + cx, cy = np.floor(x), np.floor(y); u = x - cx; v = y - cy; u = u * u * (3 - 2 * u); v = v * v * (3 - 2 * v) + a, b, c, d = _hash2(cx, cy), _hash2(cx + 1, cy), _hash2(cx, cy + 1), _hash2(cx + 1, cy + 1) + return (a + (b - a) * u) * (1 - v) + (c + (d - c) * u) * v +LACUN, WEIGHT_GAIN, AMP_GAIN, CRAG = 2.07, 2.0, 0.5, 0.5 # ridgeWorld.ts constants +DETAIL = dict(cell_m=60.0, octaves=4, amp_m=24.0, fade_from_m=500.0, fade_to_m=4000.0, seed=17) +def detail_height(E, N, dist): + """Ridged multifractal (ridgeWorld.ts `profile`, folded value noise weighted by the previous octave) in WORLD metres (east, north of the observer), + so it is automatically periodic around the ring. First octave wavelength = 60 m = two GLO-30 cells (nothing coarser than the DEM can resolve is + touched), then x2.07. Amplitude fades to zero between fade_from and fade_to metres of distance. Seeded, deterministic, authored.""" + cfg = DETAIL; e = 0.03 + (1 - CRAG) * 0.4; top = math.sqrt(1 + e * e); s = 0.0; nrm = 0.0; amp = 1.0; f = 1.0 / cfg['cell_m']; w = 1.0 + for k in range(cfg['octaves']): + v = 2 * _vnoise2(E * f + cfg['seed'] * 7.31, N * f + cfg['seed'] * 3.17 + k * 13) - 1 + sig = (1 - np.sqrt(v * v + e * e) / top) ** 2 * w; w = np.minimum(1.0, sig * WEIGHT_GAIN); s = s + sig * amp; nrm += amp; amp *= AMP_GAIN; f *= LACUN + t = np.clip((dist - cfg['fade_from_m']) / (cfg['fade_to_m'] - cfg['fade_from_m']), 0, 1); fade = 1 - t * t * (3 - 2 * t) + return cfg['amp_m'] * fade * (s / nrm - 0.3) + +# ====================================================================== stage 0: march +NEAR_CLIP_M = 500.0 # authored: the far march's first sample and the boundary of parallax authority: coverage, seams, the encoding range, distance_m and r_max read terrain at or beyond it. The ground under it is the near march (near_march), drawn by card 0 only +def schedule(detail): + d = [NEAR_CLIP_M] + while d[-1] < P['rmax_km'] * 1000: + d.append(d[-1] + min(250.0, max(10.0 if detail else 40.0, 0.004 * d[-1]))) + return np.array(d) + +def elev(h, d, curvature=True): + """Elevation angle (degrees) of height h (m) at distance d (m) from the eye: Earth curvature with refraction. The one formula of march and prefilter.""" + drop = d * d / (2 * R_EARTH) * (1 - KREF) if curvature else 0.0 + return np.degrees(np.arctan2(h - P['eye_m'] - drop, d)) + +def march(detail=False, curvature=True): + m, lt, ll = mosaic(P); az = np.radians((np.arange(W) + 0.5) / W * 360.0); d = schedule(detail); cosl = math.cos(math.radians(P['lat'])) + A = np.zeros((len(d), W), np.float32); Hh = np.zeros_like(A); sa, ca = np.sin(az), np.cos(az) + for k, dk in enumerate(d): + lat = P['lat'] + dk * ca / 111320.0; lon = P['lon'] + dk * sa / (111320.0 * cosl) + h = bil(m, lt, ll, lat, lon) + if detail and dk < DETAIL['fade_to_m']: h = h + detail_height(dk * sa, dk * ca, dk) + A[k] = elev(h, dk, curvature); Hh[k] = h + return d, A, Hh + +def rays_key(detail): + """Inputs of the ray march: observer, eye elevation, range, the DEM mosaic, the sample schedule (hashed as the array it produces), the Earth / refraction constants, the ring width, and (detail) the foreground detail noise.""" + return cache_key('rays.v1', P['lat'], P['lon'], P['rmax_km'], round(float(P['eye_m']), 3), mosaic_key(P), schedule(detail), R_EARTH, KREF, W, bool(detail), + (sorted(DETAIL.items()), LACUN, WEIGHT_GAIN, AMP_GAIN, CRAG) if detail else None) +def stage0(detail=False, force=False): + c = B / f"rays-{P['id']}{'-detail' if detail else ''}-{rays_key(detail)}.npz" + if c.exists() and not force: + z = np.load(c); return z['d'], z['ang'], z['h'], None + t0 = time.time(); mosaic(P); t1 = time.time(); d, A, Hh = march(detail); t2 = time.time(); np.savez(c, d=d, ang=A, h=Hh) + return d, A, Hh, dict(mosaic=t1 - t0, march=t2 - t1, samples=len(d)) + +# ====================================================================== the near march: the ground under the near clip +NEAR_START_M = 1.0 # authored: the ray of the frame bottom meets flat ground from a 1.6 m eye farther out than this; a 5 m start leaves a wall at grandcanyon h100, where the ground at 5 m stands 8 degrees up +def near_schedule(): + """Sample distances (m) of the near march: NEAR_START_M, then steps of max(1 m, 0.02 d) capped at 10 m, every sample below NEAR_CLIP_M (about 170).""" + d = [NEAR_START_M] + while d[-1] + min(10.0, max(1.0, 0.02 * d[-1])) < NEAR_CLIP_M: d.append(d[-1] + min(10.0, max(1.0, 0.02 * d[-1]))) + return np.array(d) +def near_march(sigma_m=0.0): + """(d, a, h) of the ground under the near clip: the place's own DEM, bilinear, sampled along near_schedule() on all W columns in float64 (no cache: one pass is about 170 x 6400 samples), low-passed with the place's own prefilter (sigma_m = prefilter_m) like the far march.""" + m, lt, ll = mosaic(P); az = np.radians((np.arange(W) + 0.5) / W * 360.0); d = near_schedule(); cosl = math.cos(math.radians(P['lat'])); sa, ca = np.sin(az), np.cos(az) + h = np.stack([np.asarray(bil(m, lt, ll, P['lat'] + dk * ca / 111320.0, P['lon'] + dk * sa / (111320.0 * cosl)), np.float64) for dk in d]); a, h = prefilter(d, h, sigma_m) + return d, a, h +def join_near(d, a, h, near): + """The one join of the near march to the far march (d, a, h: (K, W), set_view done): returns (D, A, Hc, nrm) for cards, near samples first. The near angles are capped per column at the angle of the far march's first sample, a[0]: the near ground draws inside the silhouette of the terrain at the clip + and no near hill rises above it (ruling ridge-near-ground-outline). The normals of the two marches are computed apart and concatenated, so the far normals are those of the far march alone. Needs the whole ring (the cap and the lateral normal read ring columns): cut the tiles from the result.""" + dn, an, hn = near; a = np.asarray(a); an = np.minimum(an, a[0][None, :]); nn, nf = normals(dn, hn), normals(d, h) + return np.concatenate([dn, d]), np.concatenate([an, a]), np.concatenate([hn, h]), tuple(np.concatenate([x, y]) for x, y in zip(nn, nf)) + +# ====================================================================== periodic helpers + +# ====================================================================== prefilter: the march is a heightfield of roofs and hills; the cards want the hills +def prefilter(d, h, sigma_m): + """Gaussian low-pass of the ray heights h (K, W): along each ray with sigma sigma_m metres (weighted by sample spacing, the schedule is not uniform), then across rays at equal distance with + sigma = sigma_m / (d * COLW) columns (periodic, exact in the Fourier domain). Angles are recomputed from the filtered heights with elev. Returns (angles, heights); sigma_m 0 leaves the heights as they are.""" + d = np.asarray(d, np.float64); h = np.asarray(h, np.float64) + if sigma_m > 0: + f = np.fft.rfftfreq(h.shape[1]); sc = sigma_m / (d * COLW) + h = np.fft.irfft(np.fft.rfft(h, axis=1) * np.exp(-2 * (np.pi * f[None, :] * sc[:, None]) ** 2), n=h.shape[1], axis=1) + dd = np.gradient(d); out = np.empty_like(h) + for k in range(len(d)): + r = int(min(3 * sigma_m / dd[k] + 1, 60)); lo, hi = max(0, k - r), min(len(d), k + r + 1) + w = np.exp(-0.5 * ((d[lo:hi] - d[k]) / sigma_m) ** 2) * dd[lo:hi]; out[k] = (w[:, None] * h[lo:hi]).sum(0) / w.sum() + h = out + return elev(h, d[:, None]), h + +def normals(d, h): + """Surface normal at every ray sample (n_r, n_t, n_up), each (K, W): n_r along the ray, n_t across it (towards increasing azimuth), n_up vertical. The slopes are the ray's own dh/dd and the difference of the + neighbouring columns at the SAME sample (equal distance, never equal row) over 2 d COLW, both times the authored vertical exaggeration PXDEG_V / HPX_DEG, so a face reads as steep as the view draws it.""" + d = np.asarray(d, np.float64); h = np.asarray(h, np.float64); E = PXDEG_V / HPX_DEG + sr = E * np.gradient(h, d, axis=0); st = E * (np.roll(h, -1, axis=1) - np.roll(h, 1, axis=1)) / (2 * d[:, None] * COLW); nz = 1.0 / np.sqrt(1 + sr * sr + st * st) + return -sr * nz, -st * nz, nz + +# ====================================================================== the authored Y mapping +GROUND_ROWS_MIN = 150 # rows every bake keeps under the horizon: (1 - HORIZON_AT) x plane_h / RIDGE_BAND_FRAC of the runtime (view.ts groundRowsNeeded; ridgeAssets.test pins the two together) +E_MIN = 0.5 # the vertical exaggeration may go down to this to keep GROUND_ROWS_MIN (ruling ridge-ground-rows-below-horizon) +def set_view(skyline, sky_row=0.04, near_row=0.66): + """AUTHORED vertical mapping, linear in elevation angle: row = (TOP_DEG - angle) * PXDEG_V over the whole 600-row frame (cylindrical, horizontal 17.78 px/deg). skyline is the highest angle any sample reaches in each + ring column (W,), straight from the march. Three anchors on the whole ring (rulings ridge-ring-vertical-anchors, ridge-ground-rows-below-horizon): the highest skyline angle of the ring sits at `sky_row` (4%) of the frame height, the LOWEST sits at + `near_row` (66%) where the scale allows, and the horizon keeps GROUND_ROWS_MIN rows under it. PXDEG_V = the lesser of (near_row - sky_row) * 600 / (highest - lowest) and (600 - GROUND_ROWS_MIN - sky_row * 600) / highest, clamped to + [E_MIN, 10] x 17.78 px/deg = vertical exaggeration 0.5x..10x; a skyline whose highest angle cannot keep the ground rows even at E_MIN refuses (Refusal naming sky_deg, the scale needed and the floor). + TOP_DEG = highest + sky_row*600/PXDEG_V; BOTTOM_DEG = TOP_DEG - 600/PXDEG_V. Returns the view, with `binds` naming the anchor that set the scale: 'skyline', 'horizon', 'floor' or 'ceiling'.""" + global rowang, PXDEG_V, TOP_DEG, BOTTOM_DEG + sk = np.asarray(skyline); sky = float(sk.max()); low = float(sk.min()); lo, hi = E_MIN * HPX_DEG, 10 * HPX_DEG + fit = (near_row - sky_row) * H / max(sky - low, 0.05); hold = (H - GROUND_ROWS_MIN - sky_row * H) / sky if sky > 0 else math.inf + if hold < lo: raise Refusal(f"the whole-ring skyline reaches {sky:.2f} degrees: holding {GROUND_ROWS_MIN} rows under the horizon needs {hold:.2f} px/deg, below the floor {lo:.2f} px/deg ({E_MIN:g}x)") + ppd = float(np.clip(min(fit, hold), lo, hi)); binds = 'horizon' if hold < fit and ppd == hold else 'floor' if ppd == lo else 'ceiling' if ppd == hi else 'skyline' + PXDEG_V = ppd; TOP_DEG = sky + sky_row * H / ppd; BOTTOM_DEG = TOP_DEG - H / ppd; rowang = TOP_DEG - (np.arange(H) + 0.5) / PXDEG_V + return dict(top_deg=TOP_DEG, bottom_deg=BOTTOM_DEG, px_per_deg=PXDEG_V, exaggeration=PXDEG_V / HPX_DEG, horizon_row=TOP_DEG * PXDEG_V, sky_deg=sky, low_deg=low, sky_row=sky_row, near_row=near_row, binds=binds) + +# ====================================================================== coverage and seams +COV_BINS = 160 # log-distance bins between the first and the last sample +SIG_B = 1.5 # blur of the coverage along depth (bins): seams settle in gaps +SEAM_LAM, SEAM_UNARY = 2.0, 0.25 # forward energy: a seam that moves a bin between neighbouring columns pays SEAM_LAM per bin plus every visible row it sweeps; one that sits in visible terrain pays SEAM_UNARY x those rows (cross-fadable) +SEAM_PRIOR = 0.02 # the authored depth is a faint pull, rows per nat^2 (the tests pin the window: six synthetic receding ridges, a sawtooth round the ring, tear at 0.05, and without the swept-rows term at 0.02 they tear too) +SEAM_SEP = 0.4 # seams at least this far apart in log-distance (nat) +XF = 0.07 # half-width of a seam's cross-fade, nat (about two bins) + +def log_edges(d, nb=COV_BINS): L = np.log(np.asarray(d, np.float64)); return np.linspace(L[0], L[-1] + 1e-9, nb + 1) + +def opaque(a): + """Coverage 0..1 of every frame row by the opaque view of angles a (K, n): the share of the row's angular span under the column skyline.""" + p = 1.0 / PXDEG_V; lo = rowang - 0.5 * p; return np.clip((np.asarray(a, np.float64).max(0)[None, :] - lo[:, None]) / p, 0, 1) + +def coverage(d, a, nb=COV_BINS): + """(nb, n): rows of the opaque view first revealed by the samples of each log-distance bin, per column. The first sample reveals every row from the frame bottom up to its angle, so the rows below it (nearer than it) count in bin 0. Needs set_view.""" + a = np.asarray(a, np.float64); edges = log_edges(d, nb); kb = np.clip(np.searchsorted(edges, np.log(d), 'right') - 1, 0, nb - 1) + runmax = np.maximum.accumulate(a, axis=0); prev = np.vstack([np.full((1, a.shape[1]), BOTTOM_DEG), runmax[:-1]]) + C = np.zeros((nb, a.shape[1])); np.add.at(C, kb, np.clip(np.minimum(a, TOP_DEG) - np.maximum(prev, BOTTOM_DEG), 0, None) * PXDEG_V) + return C + +def _dt(f, u): + """out[i] = min_k f[k] + |u[i] - u[k]| along axis 0, u increasing: two cumulative-minimum passes (Felzenszwalb & Huttenlocher's L1 distance transform).""" + u = u.reshape((-1,) + (1,) * (f.ndim - 1)); return np.minimum(np.minimum.accumulate(f - u, axis=0) + u, np.flip(np.minimum.accumulate(np.flip(f + u, 0), axis=0), 0) - u) + +def seams(cov, targets, d): + """(K, n) ordered seam distances (m), one per authored target (m), each column of a RING (cov is periodic: the last column neighbours the first). One 1D forward-energy DP per seam, in target order (seam carving, Avidan & Shamir 2007; forward energy, Rubinstein et al. 2008): unary + SEAM_UNARY x the rows at the seam; moving a bin between neighbouring columns costs SEAM_LAM per bin plus the rows swept, an L1 distance in u = cumsum(rows) + SEAM_LAM x bin; a weak prior to the target. Seam k is held at + least SEAM_SEP nat beyond seam k-1 in every column. Sequential, not joint: a joint DP has NB^K states per column and seams in gaps do not interact. Periodic: the DP runs over the ring three times side by side and keeps the middle lap, + so a seam is continuous across the wrap and a tile boundary is only a crop.""" + cov = np.tile(np.asarray(cov, np.float64), (1, 3)); nb, n3 = cov.shape; n = n3 // 3; edges = log_edges(d, nb); bc = 0.5 * (edges[:-1] + edges[1:]); sep = int(math.ceil(SEAM_SEP / (edges[1] - edges[0]))); INF = 1e12 + r = int(3 * SIG_B) + 1; kern = np.exp(-0.5 * (np.arange(-r, r + 1) / SIG_B) ** 2); kern /= kern.sum(); pad = np.pad(cov, ((r, r), (0, 0)), mode='edge'); Cs = sum(kv * pad[i:i + nb] for i, kv in enumerate(kern)) + bins = np.arange(nb); lo = np.zeros(n3, int); out = np.zeros((len(targets), n3)) + for t, T in enumerate(targets): + prior = SEAM_PRIOR * (bc - math.log(T)) ** 2; need = np.minimum(lo + (sep if t else 0), nb - 1); feas = bins[:, None] >= need[None, :] + warp = lambda x: np.cumsum(0.5 * (cov[:, x - 1] + cov[:, x])) + SEAM_LAM * bins + cost = np.where(feas[:, 0], SEAM_UNARY * Cs[:, 0] + prior, INF); store = [cost] + for x in range(1, n3): cost = np.where(feas[:, x], _dt(cost, warp(x)) + SEAM_UNARY * Cs[:, x] + prior, INF); store.append(cost) + j = np.zeros(n3, int); j[-1] = int(np.argmin(store[-1])) + for x in range(n3 - 1, 0, -1): u = warp(x); j[x - 1] = int(np.argmin(store[x - 1] + np.abs(u - u[j[x]]))) + out[t] = np.exp(bc[j]); lo = j + return out[:, n:2 * n] + +# ====================================================================== cards: layered depth, one per band between seams +def load_material(name, path=Path(__file__).resolve().parent / 'places.json'): + """The named material of places.json `materials` (its one owner), checked for shape; an unknown name is a Refusal, never a fallback. A material: base rgb, ramps [{from_m, to_m, colour}] lerped over height in order, steep {colour} | None (the steep-face override), snow {from_m, to_m, colour} | None (gated by flatness).""" + tab = json.load(open(path)).get('materials') or {} + if name not in tab: raise Refusal(f"material {name!r} is not in places.json materials ({', '.join(sorted(tab)) or 'none'})") + m = tab[name]; rgb = lambda c: isinstance(c, list) and len(c) == 3 and all(isinstance(v, (int, float)) and 0 <= v <= 1 for v in c) + ok = isinstance(m, dict) and set(m) == {'base', 'ramps', 'steep', 'snow'} and rgb(m['base']) and isinstance(m['ramps'], list) and all(isinstance(r, dict) and set(r) == {'from_m', 'to_m', 'colour'} and r['from_m'] < r['to_m'] and rgb(r['colour']) for r in m['ramps']) + ok = ok and (m['steep'] is None or (isinstance(m['steep'], dict) and set(m['steep']) == {'colour'} and rgb(m['steep']['colour']))) and (m['snow'] is None or (isinstance(m['snow'], dict) and set(m['snow']) == {'from_m', 'to_m', 'colour'} and m['snow']['from_m'] < m['snow']['to_m'] and rgb(m['snow']['colour']))) + if not ok: raise Refusal(f"material {name!r} is malformed (base rgb, ramps [{{from_m < to_m, colour}}], steep {{colour}} | null, snow {{from_m < to_m, colour}} | null; rgb in 0..1)") + return m +def albedo(h, n_up, material): + """Evaluate a material (load_material) at height h and up-component n_up: the base colour, each ramp lerped by height in order, the steep colour where the face is steep, the snow colour above its band where the face is flat. Straight colour, no light in it.""" + t = lambda a, b: np.clip((h - a) / (b - a), 0, 1)[..., None]; c = np.asarray(material['base']) + for r in material['ramps']: c = c + (np.asarray(r['colour']) - c) * t(r['from_m'], r['to_m']) + if material['steep']: c = c + (np.asarray(material['steep']['colour']) - c) * np.clip((0.93 - n_up) / 0.25, 0, 1)[..., None] + sn = material['snow'] + return c + (np.asarray(sn['colour']) - c) * (t(sn['from_m'], sn['to_m']) * np.clip((n_up - 0.55) / 0.3, 0, 1)[..., None]) if sn else c + +def cards(d, a, h, seams, nrm=None, *, material): + """K+1 cards, nearest first, from the angles a and heights h (samples, n) of n columns and the (K, n) seams (m). Card i holds per pixel the FIRST VISIBLE hit at or beyond seam i-1 (less XF): layered depth, so a farther + card keeps the terrain a nearer ridge hides. Its alpha is that pixel's coverage (a crest row holds the share of its angular span under the card's running maximum) times 1 - smoothstep over seam i +- XF in + log-distance of the hit; card 0 owns the rows below the first sample, the last card has no far edge. Alphas are then made nested so the alpha-over composite of all cards is exactly the opaque coverage (a row two + cards both hold partly is not counted twice). Distance and normal are interpolated between sample k-1 and k by angle. Each card is cropped to the rows where its 8-bit alpha is not zero. + material is the place's (load_material), the one colour rule of wall, near and far rows. nrm is normals(d, h) of the same columns (default: computed from h as given, so pass it for columns cut from the ring: the lateral slope reads the neighbouring columns). Rows of any card below the angle of its first sample (hit and idx == 0) are its wall: they keep that sample's distance, their albedo is the ground material at their height with the face up (n_up = 1), + and `wall` flags them (card 0's first sample is the near march's NEAR_START_M, so no row of it is wall under a real frame). Card 0 draws the near march (join_near; the samples nearer than NEAR_CLIP_M) under the silhouette of the terrain at the clip as ordinary terrain: its own normal, the albedo of its own height and n_up; `near` (h, n) bool flags the pixels whose hit lies on the near side of the clip sample (the rows that were card 0's wall), whose distance is then never above the clip. Each card: dict(top, alpha (h,n), albedo (h,n,3), n_r, n_t, logd (ln metres) (h,n), wall (h,n) bool, near (h,n) bool).""" + d = np.asarray(d, np.float64); a = np.asarray(a, np.float64); h = np.asarray(h, np.float64); seams = np.asarray(seams, np.float64); nk, n = a.shape; nc = len(seams) + 1 + if d[0] >= NEAR_CLIP_M: raise Refusal(f"card 0 draws the ground under the near clip from the near march, but the first sample is at {d[0]:g} m (the clip is {NEAR_CLIP_M:g} m): pass join_near") + n_r, n_t, n_u = nrm if nrm is not None else normals(d, h); ld = np.broadcast_to(np.log(d)[:, None], (nk, n)); p = 1.0 / PXDEG_V; lo = rowang - 0.5 * p; kn = int(np.searchsorted(d, NEAR_CLIP_M)) # kn: the samples nearer than the clip + ks0 = [np.searchsorted(d, seams[i - 1] * math.exp(-XF)) for i in range(1, nc)]; ks1 = [np.searchsorted(d, seams[i] * math.exp(XF)) for i in range(nc - 1)] + F = np.zeros((nc, H, n)); X = np.ones((nc, H, n)); G = np.zeros((nc, 5, H, n)); Wl = np.zeros((nc, H, n), bool); Nr = np.zeros((nc, H, n), bool) # coverage, far fade, then (logd, h, n_r, n_t, n_u); wall rows; near rows (the ground under the clip) + for x in range(n): + for i in range(nc): + k0 = 0 if i == 0 else int(ks0[i - 1][x]); k1 = nk if i == nc - 1 else int(ks1[i][x]) + if k1 <= k0: continue + rm = np.maximum.accumulate(a[k0:k1, x]); idx = np.searchsorted(rm, lo, 'right'); hit = idx < len(rm); idx = np.minimum(idx, len(rm) - 1); kk = k0 + idx + if not hit.any(): continue + kp = np.maximum(kk - 1, k0); prev = np.where(idx > 0, rm[np.maximum(idx - 1, 0)], rm[idx] - 1.0) + t = np.where(idx > 0, np.clip((rowang - prev) / np.maximum(rm[idx] - prev, 1e-9), 0, 1), 1.0); mix = lambda arr: arr[kp, x] + t * (arr[kk, x] - arr[kp, x]) + F[i, :, x] = np.where(hit, np.clip((rm[-1] - lo) / p, 0, 1), 0); lh = mix(ld) + G[i, :, :, x] = np.where(hit, np.stack([lh, mix(h), mix(n_r), mix(n_t), mix(n_u)]), 0) + Wl[i, :, x] = hit & (idx == 0); Nr[i, :, x] = hit & (kp < kn) # rows below the card's first sample: the extruded wall; hits on the near side of the clip sample (below it, or between the last near sample and it): the near ground (only card 0 reaches it) + if i < nc - 1: s = np.clip((lh - (math.log(seams[i, x]) - XF)) / (2 * XF), 0, 1); X[i, :, x] = 1 - s * s * (3 - 2 * s) + out = []; A = np.zeros((H, n)) + for i in range(nc): + part = np.where(F[i] < 1, np.clip((np.maximum(A, F[i]) - A) / np.maximum(1 - A, 1e-6), 0, 1), F[i]); al = np.where(np.rint(X[i] * part * 255) > 0, X[i] * part, 0.0); A = 1 - (1 - A) * (1 - al) + rows = np.flatnonzero(al.max(1) > 0) + if not len(rows): out.append(dict(top=0, alpha=np.zeros((0, n), np.float32), albedo=np.zeros((0, n, 3), np.float32), n_r=np.zeros((0, n), np.float32), n_t=np.zeros((0, n), np.float32), logd=np.zeros((0, n), np.float32), wall=np.zeros((0, n), bool), near=np.zeros((0, n), bool))); continue + sl = slice(int(rows[0]), int(rows[-1]) + 1); g = G[i, :, sl]; nz = np.sqrt(g[2] ** 2 + g[3] ** 2 + g[4] ** 2) + 1e-12 + out.append(dict(top=int(rows[0]), alpha=al[sl].astype(np.float32), albedo=albedo(g[1], np.where(Wl[i, sl], 1.0, g[4] / nz), material).astype(np.float32), n_r=(g[2] / nz).astype(np.float32), n_t=(g[3] / nz).astype(np.float32), logd=g[0].astype(np.float32), wall=Wl[i, sl].copy(), near=Nr[i, sl].copy())) + return out diff --git a/scripts/ridge-bake/tests/mutate.py b/scripts/ridge-bake/tests/mutate.py new file mode 100644 index 00000000..94702e0d --- /dev/null +++ b/scripts/ridge-bake/tests/mutate.py @@ -0,0 +1,130 @@ +"""Mutation check: re-introduce a cause into a COPY of the baker, run the fixtures against it, and require that at least one fails. + venv/bin/python tests/mutate.py [word ...] (runs the unmutated copy first and exits 2 if a fixture fails; prints one line per mutant whose name holds every word; exit 1 if a mutant survives or only crashes the run: a kill is an AssertionError raised by the fixtures' own code)""" +import os, shutil, subprocess, sys, tempfile +HERE = os.path.dirname(os.path.abspath(__file__)); SRC = os.path.join(HERE, '..') +MUTANTS = { # name -> (text in ridge.py or export.py, replacement) + 'seam cost: the rows a seam sweeps are not paid (it hops across a receding ridge)': ("np.cumsum(0.5 * (cov[:, x - 1] + cov[:, x])) + SEAM_LAM * bins", "SEAM_LAM * bins"), + 'seam prior pulls hard to the target (2.0, or 0.1: the seam hops across a ridge)': ("SEAM_PRIOR = 0.02 ", "SEAM_PRIOR = 2.0 "), + 'normals: the authored exaggeration is dropped': ("h = np.asarray(h, np.float64); E = PXDEG_V / HPX_DEG", "h = np.asarray(h, np.float64); E = 1.0"), + 'normals: the lateral neighbour is one sample nearer (not equal distance)': ("st = E * (np.roll(h, -1, axis=1) - np.roll(h, 1, axis=1))", "st = E * (np.roll(np.roll(h, -1, axis=1), 1, axis=0) - np.roll(h, 1, axis=1))"), + 'cards: the near edge is ignored (every card starts at sample 0)': ("k0 = 0 if i == 0 else int(ks0[i - 1][x])", "k0 = 0"), + 'cards: the farther card fades in over the window too (both cards translucent)': ("X[i, :, x] = 1 - s * s * (3 - 2 * s)", "X[i, :, x] = 1 - s * s * (3 - 2 * s); X[i + 1, :, x] = s * s * (3 - 2 * s)"), + 'cards: a crest row is all or nothing (no fractional coverage)': ("F[i, :, x] = np.where(hit, np.clip((rm[-1] - lo) / p, 0, 1), 0)", "F[i, :, x] = np.where(hit, 1.0, 0)"), + 'prefilter ignores sigma': ("if sigma_m > 0:", "if False:"), + 'prefilter across rays uses one sigma in columns (not per distance)': ("sc = sigma_m / (d * COLW)", "sc = sigma_m / (d[0] * COLW) * np.ones_like(d)"), + 'bake_id hashes geometry before colour': ("h.update(colour); h.update(geometry)", "h.update(geometry); h.update(colour)"), + 'check_cover accepts any composite': ("if bad.any(): y, x", "if False: y, x"), + 'load_preset accepts splits that do not increase': ("or any(b <= a for a, b in zip(sp, sp[1:]))", ""), + 'geometry: n_r and n_t channels swapped': ("r, t = u8((np.asarray(n_r) + 1) / 2), u8((np.asarray(n_t) + 1) / 2)", "r, t = u8((np.asarray(n_t) + 1) / 2), u8((np.asarray(n_r) + 1) / 2)"), + 'geometry: log-distance not normalised by the encoding range': ("b = (np.asarray(logd) - enc['log_d_min']) / (enc['log_d_max'] - enc['log_d_min'])", "b = np.asarray(logd) / 12.0"), + 'colour: albedo zeroed in the file': ("rgb = u8(albedo) * (a[..., None] > 0)", "rgb = u8(albedo) * 0"), + 'colour: premultiplied instead of straight': ("rgb = u8(albedo) * (a[..., None] > 0)", "rgb = u8(np.asarray(albedo) * np.asarray(alpha)[..., None])"), + 'seams: the separation between seams is ignored': ("SEAM_SEP = 0.4 ", "SEAM_SEP = 0.0 "), + 'elev: curvature and refraction dropped': ("drop = d * d / (2 * R_EARTH) * (1 - KREF) if curvature else 0.0", "drop = 0.0"), + 'coverage: the rows below the first sample are not counted': ("prev = np.vstack([np.full((1, a.shape[1]), BOTTOM_DEG), runmax[:-1]])", "prev = np.vstack([np.full((1, a.shape[1]), 100.0), runmax[:-1]])"), + 'coverage: the rows below the first sample are counted twice': ("* PXDEG_V)\n return C", "* PXDEG_V); C[0] += np.clip(np.minimum(a[0], TOP_DEG) - BOTTOM_DEG, 0, None) * PXDEG_V\n return C"), + 'cards: the hit is not interpolated between samples': ("t = np.where(idx > 0, np.clip((rowang - prev) / np.maximum(rm[idx] - prev, 1e-9), 0, 1), 1.0)", "t = np.ones_like(rowang)"), + 'cards: the blended normal is not renormalised': ("nz = np.sqrt(g[2] ** 2 + g[3] ** 2 + g[4] ** 2) + 1e-12", "nz = 1.0"), + 'wall: no row is flagged (the flag is dropped)': ("Wl[i, :, x] = hit & (idx == 0)", "Wl[i, :, x] = False"), + 'near: the cap to the silhouette of the terrain at the clip is dropped': ("an = np.minimum(an, a[0][None, :])", "an = an"), + 'near: rows under the clip are flagged wall': ("Wl[i, :, x] = hit & (idx == 0); Nr[i, :, x] = hit & (kp < kn)", "Wl[i, :, x] = hit & ((idx == 0) | (kp < kn)); Nr[i, :, x] = hit & (kp < kn)"), + 'near: albedo takes the face up (the wall rule on near rows)': ("albedo(g[1], np.where(Wl[i, sl], 1.0, g[4] / nz), material)", "albedo(g[1], np.where(Wl[i, sl] | Nr[i, sl], 1.0, g[4] / nz), material)"), + 'near: albedo reads the height of the far march first sample': ("albedo(g[1], np.where(Wl[i, sl]", "albedo(np.where(Nr[i, sl], h[int(np.searchsorted(d, NEAR_CLIP_M))][None, :], g[1]), np.where(Wl[i, sl]"), + 'near: the march starts at 20 m': ("NEAR_START_M = 1.0 ", "NEAR_START_M = 20.0 "), + 'near: the heights are stored float32': (", np.float64) for dk in d])", ", np.float32) for dk in d])"), + 'near: the place prefilter is not applied': ("; a, h = prefilter(d, h, sigma_m)\n", "; a, h = prefilter(d, h, 0.0)\n"), + 'near: the far normals are computed over the joined march (not apart)': ("nn, nf = normals(dn, hn), normals(d, h)", "nj_ = normals(np.concatenate([dn, d]), np.concatenate([hn, h])); nn, nf = tuple(x[:len(dn)] for x in nj_), tuple(x[len(dn):] for x in nj_)"), + 'near: cards accepts a march that starts at the clip': ("if d[0] >= NEAR_CLIP_M: raise Refusal", "if False: raise Refusal"), + 'pack: near pixels count as solid terrain': ("solid = (al >= 0.5) & ~wl & ~nr;", "solid = (al >= 0.5) & ~wl;"), + 'pack: the non-wall fallback pool reads near pixels': ("((al > 0) & ~wl & ~nr, ld)", "((al > 0) & ~wl, ld)"), + 'pack: the lit fallback pool reads near pixels': ("((al > 0) & ~nr, ld)", "(al > 0, ld)"), + 'pack: the apron fallback pool reads near pixels': ("((c['alpha'] > 0) & ~c['near'], c['logd'])", "(c['alpha'] > 0, c['logd'])"), + 'pack: a tile with nothing outside the near ground is not at the clip': ("if pool else ridge.NEAR_CLIP_M", "if pool else 0.0"), + 'r_max: the tile median binds, not the nearest terrain': ("r_max = solve_r_max(near, bands, ppd); r_fwd = solve_r_max(near, bands, ppd, phis=1)", "r_max = solve_r_max(dist, bands, ppd); r_fwd = solve_r_max(dist, bands, ppd, phis=1)"), + 'r_max: near pixels do not bind at the clip': ("ridge.NEAR_CLIP_M if ((al >= 0.5) & nr).any() else None", "None"), + 'r_max: near pixels bind only in a tile with no other solid pixel': ("ridge.NEAR_CLIP_M if ((al >= 0.5) & nr).any() else None", "ridge.NEAR_CLIP_M if ((al >= 0.5) & nr).any() and not solid.any() else None"), + 'r_max: near pixels bind only where they outnumber the solid ones': ("ridge.NEAR_CLIP_M if ((al >= 0.5) & nr).any() else None", "ridge.NEAR_CLIP_M if ((al >= 0.5) & nr).sum() > solid.sum() else None"), + 'r_max: the nearest pixel is the farthest solid one': ("float(np.exp(ld[solid].min())) if solid.any() else None, ridge", "float(np.exp(ld[solid].max())) if solid.any() else None, ridge"), + 'near clip: the writer compares the float32 distance strictly': ("if rmin < ridge.NEAR_CLIP_M * (1 - 1e-5): raise", "if rmin < ridge.NEAR_CLIP_M: raise"), + 'near clip: the march starts nearer than the clip': ("d = [NEAR_CLIP_M]", "d = [100.0]"), + 'near clip: a card 0 inside the clip is accepted by the writer': ("if rmin < ridge.NEAR_CLIP_M * (1 - 1e-5): raise", "if False: raise"), + 'view: the 1x floor is back': ("lo, hi = E_MIN * HPX_DEG, 10 * HPX_DEG", "lo, hi = HPX_DEG, 10 * HPX_DEG"), + 'view: the horizon anchor is dropped (the scale is the skyline fit alone)': ("ppd = float(np.clip(min(fit, hold), lo, hi))", "ppd = float(np.clip(fit, lo, hi))"), + 'view: a skyline that cannot hold the ground rows is not refused': ("if hold < lo: raise", "if False: raise"), + 'view: the ground rows are not asked for (GROUND_ROWS_MIN 0)': ("GROUND_ROWS_MIN = 150 ", "GROUND_ROWS_MIN = 0 "), + 'validate_manifest: a plane short of its ground rows is accepted': ("if v['plane_h'] - v['horizon_row'] < ridge.GROUND_ROWS_MIN - 1e-6: raise", "if False: raise"), + 'wall: albedo takes the face normal, not the face up': ("np.where(Wl[i, sl], 1.0, g[4] / nz)", "g[4] / nz"), + 'wall: the code is not written to the geometry': ("if wall is not None: m = np.asarray(wall, bool)", "if False: m = np.asarray(wall, bool)"), + 'wall: the sheet lights wall rows with their normal': ("wall = c['wall']; n_r, n_t = np.where(wall, 0.0, c['n_r']), np.where(wall, 0.0, c['n_t'])", "n_r, n_t = c['n_r'], c['n_t']"), + 'ring: the seam DP is not periodic (the first lap is kept, not the middle)': ("return out[:, n:2 * n]", "return out[:, :n]"), + 'ring: the tile take does not wrap (the ring ends repeat their edge column)': ("return np.take(a, (c0 + np.arange(n)) % W, axis=-1)", "return np.take(a, np.clip(c0 + np.arange(n), 0, W - 1), axis=-1)"), + 'tile: the apron is shifted (a tile starts at its own first column)': ("ridge.ring_cols(x, t * TILE_W - APRON, TILE_W + 2 * APRON)", "ridge.ring_cols(x, t * TILE_W, TILE_W + 2 * APRON)"), + 'tile: the seams are cut from tile 0 for every tile': ("cols(sm, t), tuple(cols(x, t) for x in nrm)", "cols(sm, 0), tuple(cols(x, t) for x in nrm)"), + 'view: the vertical anchors read the first 72 degrees only (the old window)': ("sk = np.asarray(skyline); sky", "sk = np.asarray(skyline)[:1280]; sky"), + 'bake_id: card-major instead of tile-major': ("bake_id(text, [(e['colour'], e['geometry']) for row in tiles for e in row if e])", "bake_id(text, [(row[i]['colour'], row[i]['geometry']) for i in range(k) for row in tiles if row[i]])"), + 'bake_id: the manifest is not hashed (a manifest moves under its id)': ("h = hashlib.sha256(); h.update(manifest_text.encode('utf-8'))", "h = hashlib.sha256()"), + 'bake_id: the manifest is hashed with the id already in it (the blank is skipped)': ("bid = bake_id(text, [", "bid = bake_id(text.replace(BAKE_ID_BLANK, '111111111111'), ["), + 'write: the per-tile cover check is dropped': ("except Refusal as ex: raise Refusal(f'tile {t}: {ex}')", "except Refusal as ex: pass"), + 'write: the apron width is not checked': ("if c.shape[1] != w: raise", "if False: raise"), + 'budget: the tile cap is ignored': ("if b > TILE_BYTES_MAX: raise", "if False: raise"), + 'budget: the place cap is ignored': ("if sum(tile_bytes) > PLACE_BYTES_MAX: raise", "if False: raise"), + 'budget: the resident gate is ignored': ("if res > RESIDENT_BYTES_MAX: raise", "if False: raise"), + 'budget: the resident run does not wrap the ring': ("sum(per[(t + k) % TILES] for k in range(n))", "sum(per[t + k] for k in range(n) if t + k < TILES)"), + 'budget: the run length forgets the margin tiles': ("math.ceil(arc / TILE_DEG) + 1 + 4", "math.ceil(arc / TILE_DEG)"), + 'r_max: the camera sweeps forward only (phi = 0)': ("PHI_STEPS = 24 ", "PHI_STEPS = 1 "), + 'r_max: every card of a tile is fitted at the nearest card distance': ("fit_px(d, r, px_per_deg, phis) for d in row", "fit_px(row[0] if row[0] is not None else d, r, px_per_deg, phis) for d in row"), + 'r_max_forward: the forward offset is searched over the whole circle': ("r_fwd = solve_r_max(near, bands, ppd, phis=1)", "r_fwd = solve_r_max(near, bands, ppd)"), + 'r_max_forward: the resident gate is not checked at the forward offset': ("for r in (camera['r_max_m'], camera['r_max_forward_m']): check_budget", "for r in (camera['r_max_m'],): check_budget"), + 'r_max_forward: a forward offset below r_max_m is accepted': ("if camera['r_max_forward_m'] < camera['r_max_m']: raise", "if False: raise"), + 'fit: the line is the least squares of 33 uniform samples, as the first gate drew it': ("x, w = np.polynomial.legendre.leggauss(FIT_QUAD)", "x = np.linspace(-1, 1, 33); w = np.full(33, 2 / 33)"), + 'fit: the line is a two-node quadrature': ("FIT_QUAD = 48 ", "FIT_QUAD = 2 "), + 'write: the manifest is written as platform text (CRLF on Windows)': ("(tmp / 'manifest.json').write_bytes(text.encode('utf-8'))", "(tmp / 'manifest.json').write_text(text)"), + 'write: the index is written as platform text (CRLF on Windows)': ("(out / '.index.tmp').write_bytes((json.dumps(idx, indent=1) + '\\n').encode('utf-8'))", "(out / '.index.tmp').write_text(json.dumps(idx, indent=1) + '\\n')"), + 'r_max: not capped at half the nearest distance': ("cap = 0.5 * rmin", "cap = 5.0 * rmin"), + 'r_max: the resident gate is not part of the search': (" and resident_bytes(bands, run_tiles(r, rmin)) <= RESIDENT_BYTES_MAX\n", "\n"), + 'r_max: a bake below the floor is accepted': ("if r_max < R_MAX_FLOOR_M:", "if False:"), + 'pack: the distance counts wall rows': ("solid = (al >= 0.5) & ~wl & ~nr; any_solid", "solid = (al >= 0.5) & ~nr; any_solid"), + 'pack: the distance reads the apron columns too': ("inner = slice(APRON, APRON + TILE_W)", "inner = slice(0, TILE_W + 2 * APRON)"), + 'sheet: the tile boundaries are not drawn': ("def bounds(img): img[:, mark] = 0.45 * img[:, mark] + 0.55 * red; return img", "def bounds(img): return img"), + 'export: an empty card is not refused': ("if all(tile[i]['alpha'].shape[0] == 0 for tile in bake['cards']): raise", "if False: raise"), + 'material: a null steep override still paints steep faces rock grey (strata do not hold on cliffs)': ("if material['steep']: c = c + (np.asarray(material['steep']['colour'])", "if True: c = c + (np.asarray((material['steep'] or dict(colour=[0.47, 0.44, 0.41]))['colour'])"), + 'material: the ramps apply in reverse order': ("for r in material['ramps']:", "for r in reversed(material['ramps']):"), + 'material: a null snow still snows': ("sn = material['snow']", "sn = material['snow'] or dict(from_m=1900, to_m=2300, colour=[0.93, 0.95, 0.97])"), + 'material: an unknown name falls back to alpine': ("if name not in tab: raise Refusal(", "if name not in tab: name = 'alpine'; ("), + 'material: the cards take the alpine colours whatever the place names': ("ridge.cards(D, cols(A, t), cols(Hc, t), cols(sm, t), tuple(cols(x, t) for x in nrm), material=material)", "ridge.cards(D, cols(A, t), cols(Hc, t), cols(sm, t), tuple(cols(x, t) for x in nrm), material=ridge.load_material('alpine'))"), + 'rays cache key ignores the refraction constant': ("R_EARTH, KREF, W, bool(detail)", "R_EARTH, W, bool(detail)"), + 'rays cache key ignores the eye elevation': ("round(float(P['eye_m']), 3), ", ""), + 'mosaic cache key ignores the tile list': ("sorted(tiles_for(p)), 3600", "3600"), +} +EQUIVALENT = {'fit: the error is looked for between four points': "the worst error of the best line is at the viewport's two ends for every distance and offset the bound is searched over (checked against a 20001-sample brute force in test_fit_px_is_the_continuous_error); the grid only guards a shape where it is not"} # mutant name -> one line on why it is behaviourally equivalent (reported, not run) +def execute(edit): + """Run the fixtures on a COPY of the baker, with edit = (text, replacement) applied or None for the unmutated copy: (returncode or None if the text is gone, [(fixture, exception class, directory of the innermost traceback frame)] of every FAIL line, last stderr line).""" + d = tempfile.mkdtemp(); shutil.copytree(SRC, os.path.join(d, 'src'), ignore=shutil.ignore_patterns('tests', '__pycache__')) + try: + if edit: + a, b = edit; p = next((q for q in (os.path.join(d, 'src', f) for f in ('ridge.py', 'export.py')) if a in open(q).read()), None) + if p is None: return None, [], 'the mutant text is in neither ridge.py nor export.py' + s = open(p).read(); open(p, 'w').write(s.replace(a, b)) + r = subprocess.run([sys.executable, os.path.join(HERE, 'test_ridge.py')], env=dict(os.environ, RIDGE_SRC=os.path.join(d, 'src')), capture_output=True, text=True) + finally: shutil.rmtree(d) + fails = [(f[0][4:].strip(), f[1].strip(), os.path.dirname(os.path.abspath(f[2].strip()))) for f in (l.split(' | ', 3) for l in r.stdout.splitlines() if l.startswith('FAIL')) if len(f) == 4] + return r.returncode, fails, (r.stderr.strip().splitlines() or ['no output'])[-1][:200] +def run(item): + """KILLED: at least one fixture failed on an assertion the test code itself raised (an AssertionError whose innermost traceback frame lies in the tests directory). CRASHED: the run failed but no fixture did that (every FAIL is another exception, NameError or a numpy error and the like, or an assert inside the baker, or none printed, or the mutant text is gone), which proves nothing and fails the run. SURVIVED: every fixture passed.""" + name, (a, b) = item; rc, fails, err = execute((a, b)); asserts = [n for n, c, w in fails if c == 'AssertionError' and w == HERE] + state = 'CRASHED ' if rc is None or (rc and not asserts) else 'KILLED ' if rc else 'SURVIVED ' + why = ', '.join(f'{n}[{c}{"" if w == HERE else " in " + os.path.basename(w)}]' for n, c, w in fails) if fails else err + line = state + name + ' -> ' + why; print(line, file=sys.stderr, flush=True) # progress: a killed run keeps what finished + return line, state != 'KILLED ' +def baseline(): + """The unmutated copy must pass every fixture before any mutant means anything: a broken environment would kill them all.""" + rc, fails, err = execute(None) + if rc or fails: print('BASELINE FAILED: the unmutated baker does not pass its fixtures: ' + (', '.join(f'{n}[{c}]' for n, c, w in fails) or err), file=sys.stderr, flush=True); sys.exit(2) + print('BASELINE ok: the unmutated copy passes every fixture', file=sys.stderr, flush=True) +if __name__ == '__main__': + from concurrent.futures import ThreadPoolExecutor + baseline() + with ThreadPoolExecutor(int(os.environ.get('MUTATE_JOBS', '6'))) as ex: res = list(ex.map(run, [(n, v) for n, v in MUTANTS.items() if n not in EQUIVALENT and all(w in n for w in sys.argv[1:])])) + for line, _ in res: print(line, flush=True) + for n, why in EQUIVALENT.items(): print('EQUIVALENT ' + n + ' -> ' + why) + sys.exit(1 if any(sv for _, sv in res) else 0) diff --git a/scripts/ridge-bake/tests/run.sh b/scripts/ridge-bake/tests/run.sh new file mode 100755 index 00000000..f97a126c --- /dev/null +++ b/scripts/ridge-bake/tests/run.sh @@ -0,0 +1,7 @@ +#!/bin/sh +# Usage: RIDGE_PY= RIDGE_TILES= tests/run.sh [test_ridge.py|mutate.py] +# RIDGE_WORK (cache dir) defaults to a fresh directory under $TMPDIR. +: "${RIDGE_PY:?RIDGE_PY must name the python of the baker venv}" +export RIDGE_WORK="${RIDGE_WORK:-${TMPDIR:-/tmp}/ridge-bake-work}"; mkdir -p "$RIDGE_WORK" +HERE=$(cd "$(dirname "$0")" && pwd) +exec "$RIDGE_PY" -I "$HERE/${1:-test_ridge.py}" diff --git a/scripts/ridge-bake/tests/test_ridge.py b/scripts/ridge-bake/tests/test_ridge.py new file mode 100644 index 00000000..2979947e --- /dev/null +++ b/scripts/ridge-bake/tests/test_ridge.py @@ -0,0 +1,725 @@ +"""Fixtures for the ridge baker (march, prefilter, coverage, seams, normals, cards, export). Plain asserts, no pytest needed: venv/bin/python tests/test_ridge.py (exit code 1 on failure). +RIDGE_SRC selects the source directory (default ..) (the mutation runner points it at a patched copy). +Synthetic terrain has a known right answer; the Vienna tests bake the real preset (its rays come from stage0: RIDGE_TILES needs the tiles, or a cached rays file must exist).""" +import os, sys, math, json, shutil, tempfile, traceback +SRC = os.environ.get('RIDGE_SRC') or os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'); sys.path.insert(0, SRC) # RIDGE_WORK and RIDGE_TILES must be set (tests/run.sh sets them) +import numpy as np, ridge, export +from ridge import W, H +ALPINE = ridge.load_material('alpine') # the places.json material of every place that names none +NW = 1280 # the synthetic bakes' window: columns 0..NW of the ring (azimuth 0..72); the pieces that need the whole ring (seams across the wrap, the tile cut) run on the ring +TW = export.TILE_W + 2 * export.APRON +_w = lambda x: ridge.ring_cols(x, 0, NW) + +EYE = 100.0; GROUND = 50.0 # ground below the eye: every ray climbs, so only the placed blocks make ridges +ridge.P = dict(id='synthetic', rmax_km=95, eye_m=100.0) +D = ridge.schedule(False) +def az_of(x): return (x + 0.5) / W * 360.0 +def col_of(az): return int(round(az / 360.0 * W - 0.5)) % W + +def rays(hfun, eye=EYE): + az = (np.arange(W) + 0.5) / W * 360.0; A = np.zeros((len(D), W), np.float32); Hh = np.zeros_like(A) + for k, dk in enumerate(D): + h = hfun(dk, az); Hh[k] = h; A[k] = np.degrees(np.arctan2(h - eye - dk * dk / (2 * ridge.R_EARTH) * (1 - ridge.KREF), dk)) + return A, Hh +def near_rays(hfun, sigma=0.0): + """The near march of a synthetic terrain: hfun over ridge.near_schedule() on all W columns, float64, prefiltered like the far march (angles from ridge.P['eye_m']): (d, a, h) as ridge.near_march returns it.""" + dn = ridge.near_schedule(); az = (np.arange(W) + 0.5) / W * 360.0; hn = np.stack([np.broadcast_to(np.asarray(hfun(dk, az), np.float64), az.shape) for dk in dn]); a, h = ridge.prefilter(dn, hn, sigma); return dn, a, h +def _join(hfun, A, Hh, sigma=0.0): + """ridge.join_near of raw far rays (K, W) and the near march of the same terrain, cut to the window 0..NW: (D, a, h, nrm) as ridge.cards reads them.""" + d, a, h, nrm = ridge.join_near(D, A, Hh, near_rays(hfun, sigma)); return d, _w(a), _w(h), tuple(_w(x) for x in nrm) +def theta(h, d): return math.degrees(math.atan2(h - EYE - d * d / (2 * ridge.R_EARTH) * (1 - ridge.KREF), d)) +def in_arc(az, a0, a1): return ((az - a0) % 360.0) <= ((a1 - a0) % 360.0) +def block(a0, a1, d0, d1, h): return lambda dk, az: np.where(in_arc(az, a0, a1) & (dk >= d0) & (dk < d1), h, 0.0) +def terrain(*blocks): return lambda dk, az: np.maximum.reduce([np.full_like(az, GROUND)] + [np.asarray(b(dk, az), float) for b in blocks]) +def test_cache_keys_follow_every_input_of_the_cached_array(): + """mosaic-/rays- cache files are keyed by a digest of their inputs. Right answer: identical inputs -> identical key (the preset id does not enter), a changed preset field (eye height, range, position), tile list or baker constant (refraction, detail noise) -> a different key.""" + saved = ridge.P + try: + base = dict(id='k1', lat=47.0, lon=11.0, rmax_km=40, eye_m=2000.0); ridge.P = dict(base); k0 = (ridge.rays_key(False), ridge.rays_key(True), ridge.mosaic_key(ridge.P)) + ridge.P = dict(base, id='other'); assert (ridge.rays_key(False), ridge.rays_key(True), ridge.mosaic_key(ridge.P)) == k0, 'the preset id changed the key' + for fld, v in (('eye_m', 2010.0), ('rmax_km', 41), ('lon', 11.001), ('lat', 47.001)): + ridge.P = dict(base, **{fld: v}); assert ridge.rays_key(False) != k0[0], ('rays key ignores', fld) + ridge.P = dict(base, lat=47.0, lon=13.5); assert ridge.mosaic_key(ridge.P) != k0[2], 'mosaic key ignores the tile list' + ridge.P = dict(base); old = ridge.KREF; ridge.KREF = 0.2 + try: assert ridge.rays_key(False) != k0[0], 'rays key ignores the refraction constant' + finally: ridge.KREF = old + old = ridge.DETAIL; ridge.DETAIL = dict(old, amp_m=30.0) + try: assert ridge.rays_key(True) != k0[1] and ridge.rays_key(False) == k0[0], 'detail key ignores the noise settings (or the plain key follows them)' + finally: ridge.DETAIL = old + finally: ridge.P = saved +def test_paths_come_from_the_environment_with_no_default(): + """Importing the baker without RIDGE_WORK / RIDGE_TILES fails with a message naming the variable (no location is assumed).""" + import subprocess; env = {k: v for k, v in os.environ.items() if not k.startswith('RIDGE_')} + for var in ('RIDGE_WORK', 'RIDGE_TILES'): + e = dict(env); e.update({'RIDGE_WORK': '.', 'RIDGE_TILES': '.'}); del e[var] + r = subprocess.run([sys.executable, '-I', '-c', 'import sys; sys.path.insert(0, %r); import ridge' % SRC], env=e, capture_output=True, text=True); assert r.returncode and var in r.stderr and 'not set' in r.stderr, (var, r.stderr[-200:]) + +# ---------------------------------------------------------------------------------------- synthetic bakes: the shared steps of export.bake_place on rays the fixtures make +def _bake(hfun, splits_km, sigma=0.0, fixed_m=None): + """prefilter, whole-ring set_view, coverage and the periodic seams on the whole ring (or fixed_m, one seam depth in m for every column), the join of the near march on the whole ring, then the window columns 0..NW (azimuth 0..72) of them and the cards on those, of synthetic rays: the pieces of the bake a fixture can look at cheaply. + D, a, h, nrm of the result are the JOINED march's window (the near samples first); opaque and edges are the far march's.""" + A, Hh = rays(hfun); ridge.P.update(eye_m=EYE); a, h = ridge.prefilter(D, Hh, sigma); v = ridge.set_view(a.max(0)); cov_ring = ridge.coverage(D, a); cov = _w(cov_ring) + sm = _w(ridge.seams(cov_ring, [k * 1000.0 for k in splits_km], D)) if fixed_m is None else np.array([np.full(NW, float(v)) for v in fixed_m]) + Dj, aj, hj, nj = ridge.join_near(D, a, h, near_rays(hfun, sigma)); aw, hw, nrm = _w(aj), _w(hj), tuple(_w(x) for x in nj) + return dict(cards=ridge.cards(Dj, aw, hw, sm, nrm, material=ALPINE), splits_km=list(splits_km), seams=sm, cov=cov, opaque=ridge.opaque(_w(a)), edges=ridge.log_edges(D), D=Dj, a=aw, h=hw, nrm=nrm, v=v) +def _canvas(card, key='alpha'): + out = np.zeros((H, NW) + card[key].shape[2:], np.float32); out[card['top']:card['top'] + card[key].shape[0]] = card[key]; return out +def _row(deg): return int(np.argmin(np.abs(ridge.rowang - deg))) +THREE = terrain(block(0, 359.99, 3000, 3600, 350), block(0, 359.99, 20000, 21500, 1800), block(0, 359.99, 70000, 72000, 7000)) # ridges at 3, 20 and 70 km, each taller in angle than the one before +WIDE3 = terrain(block(0, 359.99, 9000, 10000, 300), block(0, 359.99, 38000, 40000, 2000), block(0, 359.99, 70000, 72000, 3000)) # low near hills, then ridges at 39 and 71 km: the frame reaches below the ground at the seams (so cards have wall rows) and the horizon is inside it +WALLED = terrain(block(0, 359.99, 9000, 10000, 300), block(0, 359.99, 38000, 40000, 2000)) +def _ramp(dk, az): return np.maximum(GROUND, np.where(dk > 12000, (dk - 12000) * 0.045 + 50.0, 0.0)) # a slope the first sample of card 1 stands on: n_up about 0.9, so the material would be rock if the face counted + +def test_the_vertical_anchors_read_the_whole_ring(): + """set_view anchors the highest skyline angle of the ring at 4% of the frame and the lowest at 66%, wherever they are: a peak at column 3555 and a low at column 5333, both outside the first 72 degrees, set the mapping.""" + sk = np.full(W, 1.0); sk[3555] = 3.0; sk[5333] = -1.0; sk[10] = 1.5; v = ridge.set_view(sk) + assert v['sky_deg'] == 3.0 and v['low_deg'] == -1.0 and abs(v['px_per_deg'] - 0.62 * H / 4.0) < 1e-9 and abs(v['horizon_row'] - ridge.TOP_DEG * v['px_per_deg']) < 1e-9 and abs(ridge.TOP_DEG - (3.0 + 0.04 * H / v['px_per_deg'])) < 1e-9, v +def test_seams_fall_in_depth_gaps(): + """Three ridges at 3, 20 and 70 km: targets [6, 40] give a seam in (3, 20) and one in (20, 70) in EVERY column, ordered with at least 0.4 nat between; targets [6] give one seam in (3, 20).""" + b = _bake(THREE, [6, 40]); s = b['seams']; assert s.shape == (2, NW) + assert (s[0] > 3600).all() and (s[0] < 20000).all() and (s[1] > 21500).all() and (s[1] < 70000).all(), (s.min(1), s.max(1)); assert (np.log(s[1]) - np.log(s[0]) >= 0.4 - 1e-9).all() + s1 = _bake(THREE, [6])['seams']; assert s1.shape == (1, NW) and (s1[0] > 3600).all() and (s1[0] < 20000).all(), (s1.min(), s1.max()) +def _recede(d0, d1, thick=300.0, hgt=1500.0): + """A ridge `thick` m thick whose distance runs from d0 m at azimuth 0 to d1 m at azimuth 72, and again in every 72 degrees of the ring (so the ring's skyline is the ridge's everywhere, as the window's was).""" + return terrain(lambda dk, az: np.where(np.abs(dk - (d0 + (d1 - d0) * ((az % 72) / 72.0))) < thick / 2, hgt, 0.0)) +def _receding(dk, az): return _recede(4000.0, 15000.0)(dk, az) +def test_the_swept_rows_term_keeps_the_seam_from_hopping_under_a_stronger_pull(): + """With the authored depth pulling five times as hard (0.1 instead of 0.02) the seams of the 3-12, 4-15 (split 10) and 6-14 km ridges still follow the ridge, and twice as hard (0.04) those of the 4-15 (split 6), 5-30 and 8-40 km ridges: only the cost of the visible rows it would sweep holds it back (with that term out of the cost it hops between two columns).""" + old = ridge.SEAM_PRIOR + try: + ridge.SEAM_PRIOR = 0.1 + for d0, d1, sp in ((3, 12, 6), (4, 15, 10), (6, 14, 9)): + j0, j1, cover = _alpha_jumps(d0, d1, sp); assert j0 < 0.35 and j1 < 0.35 and cover > 0.999, ('the seam hopped across the ridge', (d0, d1, sp), j0, j1) + ridge.SEAM_PRIOR = 0.04 # these three tear above 0.04 (measured: 0.05 tears 5-30 and 8-40, 0.1 tears 4-15/6): the seam is closed on the ring, so a stronger pull makes one tear per period cheaper than staying beyond the ridge + for d0, d1, sp in ((4, 15, 6), (5, 30, 12), (8, 40, 15)): + j0, j1, cover = _alpha_jumps(d0, d1, sp); assert j0 < 0.35 and j1 < 0.35 and cover > 0.999, ('the seam hopped across the ridge', (d0, d1, sp), j0, j1) + finally: ridge.SEAM_PRIOR = old +RECEDING = [(4, 15, 6), (3, 12, 6), (5, 30, 12), (8, 40, 15), (4, 15, 10), (6, 14, 9)] # km at azimuth 0, km at azimuth 72, authored split km +def _alpha_jumps(d0, d1, split): + """The two cards' alpha on the ridge body (crest + 4 rows), column to column: the largest step of each. """ + b = _bake(_recede(d0 * 1000.0, d1 * 1000.0), [split]); c0 = _canvas(b['cards'][0]); c1 = _canvas(b['cards'][1]); crest = np.argmax(b['opaque'] > 0.5, axis=0); r = np.clip(crest + 4, 0, H - 1); ok = crest > 0 + a0 = c0[r, np.arange(NW)]; a1 = c1[r, np.arange(NW)]; return float(np.abs(np.diff(a0[ok])).max()), float(np.abs(np.diff(a1[ok])).max()), (a0 + (1 - a0) * a1)[ok].min() +def test_seam_never_splits_a_receding_ridge_side_by_side(): + """Six synthetic ridges whose distance recedes across the window (4 to 15, 3 to 12, 5 to 30, 8 to 40, 4 to 15 and 6 to 14 km, targets 6, 6, 12, 15, 10, 9 km): the nearer and the farther card's alpha on the ridge's body never jumps by 0.35 between neighbouring + columns (a tear: one card here, the other next door; fading slowly over the cross-fade is fine) and the two cards together cover the body. With the swept-rows term out of the seam cost the seam hops across the ridge; with the prior at 0.1 it hops on two of the six.""" + for d0, d1, sp in RECEDING: + j0, j1, cover = _alpha_jumps(d0, d1, sp); assert j0 < 0.35 and j1 < 0.35, ('a card appears or vanishes between neighbouring columns', (d0, d1, sp), j0, j1); assert cover > 0.999, ('the ridge body is not covered by the two cards together', (d0, d1, sp)) +def test_far_card_keeps_terrain_hidden_behind_a_nearer_ridge(): + """Layered depth: a far ridge (20 km) lower in angle than the near ridge (3 km) in azimuth 0..36 and higher in 36..72. Where the near card is opaque in front of the far ridge (columns 100..500) the mid card still holds that ridge, at its distance; + where the far ridge shows above the near one (column 900) the near card is empty and the mid card holds it.""" + b = _bake(terrain(block(0, 359.99, 3000, 3600, 350), block(0, 36, 20000, 21500, 1500), block(36, 359.99, 20000, 21500, 2400)), [6]); c0, c1 = _canvas(b['cards'][0]), b['cards'][1]; a1 = _canvas(c1); ld1 = _canvas(c1, 'logd'); r = _row(theta(1500, 20000) - 0.2) + for x in (100, 300, 500): + assert c0[r, x] > 0.99, ('the near ridge does not cover the far one here', x); assert a1[r, x] > 0.99, ('the far card lost the terrain behind the near ridge', x); assert abs(math.exp(ld1[r, x]) - 20000) < 1500, (x, math.exp(ld1[r, x])) + r = _row(0.5 * (theta(350, 3000) + theta(2400, 20000))); assert c0[r, 900] < 0.01 and a1[r, 900] > 0.99 and abs(math.exp(ld1[r, 900]) - 20000) < 1500, (c0[r, 900], a1[r, 900]) +def test_crossfade_is_complementary(): + """A ridge across the seam (seam fixed at 6 km, the ridge's front face at 5.9 km inside the cross-fade): the nearer card is partly transparent over the window, the farther card is opaque on the ridge, and the composite stays at coverage 1 below the crest.""" + hf = terrain(block(0, 359.99, 5900, 6100, 900)); A, Hh = rays(hf); ridge.P.update(eye_m=EYE); ridge.set_view(A.max(0)); aw = _w(A); Dj, aj, hj, nj = _join(hf, A, Hh) + cs = ridge.cards(Dj, aj, hj, np.full((1, NW), 6000.0), nj, material=ALPINE); c0, c1 = _canvas(cs[0]), _canvas(cs[1]); crest = int(np.argmax(ridge.opaque(aw)[:, 500] > 0.5)); r = crest + 6 + assert 0.2 < c0[r, 500] < 0.8, ('the near card does not fade over the window', c0[r, 500]); assert c1[r, 500] > 0.99, 'the far card is not opaque on the ridge' + comp = 1 - (1 - c0) * (1 - c1); assert (comp[crest + 3:, :] > 0.999).all(), 'the composite dips below coverage 1 under the crest' +def test_normals_of_a_tilted_plane(): + """A plane with front slope s (north) and lateral slope l (east), seen towards azimuth 0: n = (-E s, -E l, 1) normalised, E the authored exaggeration (a dropped E fails).""" + s, l, E = 0.12, -0.08, 3.0; saved = ridge.PXDEG_V; ridge.PXDEG_V = E * ridge.HPX_DEG + try: + az = (np.arange(W) + 0.5) / W * 2 * math.pi; h = 300.0 + s * D[:, None] * np.cos(az)[None, :] + l * D[:, None] * np.sin(az)[None, :]; nr, nt, nu = ridge.normals(D, h); k = len(D) // 2; x = [0, 1, 2, W - 2, W - 1] + want = np.array([-E * s, -E * l, 1.0]); want /= np.linalg.norm(want); got = np.array([nr[k, x].mean(), nt[k, x].mean(), nu[k, x].mean()]); assert np.abs(got - want).max() < 2e-3, (got, want) + assert np.abs(nr ** 2 + nt ** 2 + nu ** 2 - 1).max() < 1e-9 + finally: ridge.PXDEG_V = saved +def test_lateral_slope_uses_equal_distance_not_equal_row(): + """A plane with lateral slope l at 20 km, a 3 km ridge only for azimuth above 40 deg: at the 20 km samples, in the columns around the ridge's azimuth edge, the across-ray slope is the plane's own l (neighbouring columns at the same distance), not a step between the ridge and the plane.""" + l = 0.05; saved = ridge.PXDEG_V; ridge.PXDEG_V = 2.0 * ridge.HPX_DEG + try: + az = (np.arange(W) + 0.5) / W * 360.0; A, Hh = rays(lambda dk, a: np.where(dk > 10000, GROUND + l * dk * np.radians(a), GROUND) + np.where((a > 40) & (dk >= 3000) & (dk < 3600), 400.0, 0.0)) + nr, nt, nu = ridge.normals(D, Hh); k = int(np.searchsorted(D, 20000)); x0 = int(40 / 360 * W); want = -2.0 * l / math.sqrt(1 + 4 * l * l + (2.0 * 0.0) ** 2) + assert np.abs(nt[k, x0 - 20:x0 + 20] / nu[k, x0 - 20:x0 + 20] + 2.0 * l).max() < 5e-3, nt[k, x0 - 5:x0 + 5] / nu[k, x0 - 5:x0 + 5] + finally: ridge.PXDEG_V = saved +def test_prefilter_flattens_roofs_and_keeps_hills(): + """A 25 m bump 60 m wide at 2 km drops below 5 m; a 400 m hill (3 km scale) keeps at least 90% of its height.""" + ridge.P.update(eye_m=EYE); roof = lambda dk, az: GROUND + np.where((az < 1.72) & (dk >= 2000) & (dk < 2060), 25.0, 0.0) + hill = lambda dk, az: GROUND + 400.0 * np.exp(-((dk - 10000.0) / 3000.0) ** 2 - ((np.radians(((az + 180) % 360) - 180) * dk) / 3000.0) ** 2) + for f, name in ((roof, 'roof'), (hill, 'hill')): + A, Hh = rays(f); a, h = ridge.prefilter(D, Hh, 100.0); k = int(np.argmin(np.abs(D - (2030 if name == 'roof' else 10000)))); x = int(np.argmax(Hh[k])) + if name == 'roof': assert h[k, x] - GROUND < 5.0 and Hh[k, x] - GROUND >= 24.9, ('the roof survives the low-pass', h[k, x] - GROUND) + else: assert h[k, x] - GROUND >= 0.9 * 400.0, ('the hill is flattened', h[k, x] - GROUND) + assert np.allclose(ridge.prefilter(D, Hh, 0.0)[1], Hh), 'sigma 0 changed the heights' +def test_crest_rows_have_fractional_coverage(): + """The top row of a card's run has alpha equal to the share of its angular span under the running maximum, and the rows below it are 1 (a lower ridge in columns 0..640 so its crest is not at the frame's top edge).""" + hf = terrain(block(0, 36, 5000, 5600, 500), block(36, 359.99, 5000, 5600, 560)); A, Hh = rays(hf); ridge.P.update(eye_m=EYE); ridge.set_view(A.max(0)); aw = _w(A); Dj, aj, hj, nj = _join(hf, A, Hh); c = ridge.cards(Dj, aj, hj, np.zeros((0, NW)), nj, material=ALPINE)[0] + cv = _canvas(c)[:, 300]; r = int(np.argmax(cv > 0)); top = float(aw.max(0)[300]); p = 1.0 / ridge.PXDEG_V; want = (top - (ridge.rowang[r] - 0.5 * p)) / p + assert 0.0 < want < 1.0 and abs(cv[r] - want) < 0.01, (cv[r], want, r); assert (cv[r + 1:] > 0.999).all() +def test_cards_composite_to_the_opaque_view(): + """Alpha-over of all cards, last to first, equals the opaque march coverage within 0.02 everywhere, and where opaque the nearest solid card's distance is the first-hit distance of the march.""" + for hf, sp in ((THREE, [6, 40]), (terrain(_receding), [6]), (terrain(block(0, 359.99, 3000, 3600, 350), block(0, 36, 20000, 21500, 700), block(36, 359.99, 20000, 21500, 1800)), [6])): + b = _bake(hf, sp); comp = 1 - np.prod([1 - _canvas(c) for c in b['cards']], axis=0); assert np.abs(comp - b['opaque']).max() < 0.02, np.abs(comp - b['opaque']).max() + rm = np.maximum.accumulate(b['a'], axis=0); col = 640; r = _row(float(b['a'][:, col].max()) - 0.5); k = int(np.searchsorted(rm[:, col], ridge.rowang[r], 'left')); first = None + for c in b['cards']: + if _canvas(c)[r, col] > 0.99: first = math.exp(_canvas(c, 'logd')[r, col]); break + assert first is not None and abs(first - b['D'][k]) < 0.1 * b['D'][k] + 60, (first, b['D'][k]) + +# ---------------------------------------------------------------------------------------- the ring: tiles are crops of per-column results, the wrap is periodic +_RING = {} +def _ring(key, hfun, splits_km): + """export.cut_ring on synthetic rays (prefilter, whole-ring set_view, then the ring cut), cached by key: dict(bake = what export.bake_place returns, minus the place).""" + if key not in _RING: + A, Hh = rays(hfun); ridge.P.update(eye_m=EYE); a, h = ridge.prefilter(D, Hh, 0.0); v = ridge.set_view(a.max(0)); r = export.cut_ring(D, a, h, splits_km, near_rays(hfun), ALPINE) + _RING[key] = dict(r, op_ring=ridge.opaque(a), place=dict(id='synthetic', name='Synthetic', lat=48.0, lon=16.0, altitude_km=0.05, eye_m=EYE, tz='Europe/Vienna'), v=v, + 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])))) + return _RING[key] +def _tile_canvas(card, key='alpha'): + out = np.zeros((H, TW) + card[key].shape[2:], np.float32); out[card['top']:card['top'] + card[key].shape[0]] = card[key]; return out +def _across_north(dk, az): return np.where(in_arc(az, 340, 20) & (np.abs(dk - (12000.0 + 400.0 * (((az + 180) % 360) - 180))) < 200), 1500.0, 0.0) # a ridge across the wrap at 4 km (az -20) to 20 km (az +20) +ACROSS = terrain(block(0, 359.99, 3000, 3600, 350), _across_north, block(0, 359.99, 70000, 72000, 3000), block(0.0, 0.05, 6000, 7000, 2500), block(359.95, 359.99, 6000, 7000, 2500)) # and a tower one column wide on each side of north +def test_ring_wrap(): + """A ridge across column 6399 / 0 (receding from 4 km at -20 deg to 20 km at +20 deg): the seam is continuous over the wrap (its jump there no larger than the largest jump elsewhere), tile 31's right apron equals tile 0's first columns and tile 0's left apron + tile 31's last (every card, pixel for pixel), neighbouring tiles agree on their shared apron, and the interiors of all tiles composite to the opaque ring.""" + b = _ring('across', ACROSS, [8]); sm = np.log(b['seams'][0]); jumps = np.abs(np.diff(np.append(sm, sm[0]))); assert jumps[-1] <= jumps[:-1].max() + 1e-9, ('the seam jumps over the wrap', jumps[-1], jumps[:-1].max()) + A_ = export.APRON; T_ = export.TILE_W; ring = np.zeros((H, W)); op = np.zeros((H, W)) + for t, tile in enumerate(b['cards']): + nxt = b['cards'][(t + 1) % export.TILES] + for i, c in enumerate(tile): + assert (_tile_canvas(c)[:, T_ + A_:T_ + 2 * A_] == _tile_canvas(nxt[i])[:, A_:2 * A_]).all(), ('the apron differs from the neighbour', t, i); seen = _tile_canvas(c)[:, T_ + A_:T_ + 2 * A_] > 0 + for key in ('logd', 'wall'): assert (_tile_canvas(c, key)[:, T_ + A_:T_ + 2 * A_][seen] == _tile_canvas(nxt[i], key)[:, A_:2 * A_][seen]).all(), ('the apron differs from the neighbour', t, i, key) + comp = 1 - np.prod([1 - _tile_canvas(c) for c in tile], axis=0); ring[:, t * T_:(t + 1) * T_] = comp[:, A_:A_ + T_]; op[:, t * T_:(t + 1) * T_] = b['opaque'][t][:, A_:A_ + T_] + assert np.abs(ring - op).max() < 0.02, np.abs(ring - op).max(); assert np.abs(ring - b['op_ring']).max() < 0.02 and b['op_ring'][:, [0, W - 1]].sum(0).min() > b['op_ring'][:, [1, W - 2]].sum(0).max() + 10, 'the tiles hold the wrong columns of the ring (a tower on column 0 and column 6399 is the fixture)' + assert b['opaque'][0].shape == (H, T_ + 2 * A_) and (b['opaque'][0][:, :A_] == b['opaque'][export.TILES - 1][:, T_:T_ + A_]).all(), 'the left apron of tile 0 is not the last columns of tile 31' +def test_every_tile_is_cut_at_its_own_seam(): + """The seams sweep from 5 km to 30 km once round the ring (ridge.seams stands in): in every tile the near card holds nothing beyond its columns' seam (plus the cross-fade) and the far card nothing before it, so no tile is cut with another tile's seams.""" + saved = ridge.seams; sweep = 5000.0 * 6.0 ** (np.arange(W) / W) + ridge.seams = lambda cov, targets, d: sweep[None, :] + try: b = _ring('swept', terrain(block(0, 359.99, 3000, 3600, 350), block(0, 359.99, 20000, 21500, 1800), block(0, 359.99, 70000, 72000, 3000)), [8]) + finally: ridge.seams = saved + T_, A_ = export.TILE_W, export.APRON; ix = slice(A_, A_ + T_); xf = ridge.XF; seen = 0 + for t, tile in enumerate(b['cards']): + s_t = np.broadcast_to(sweep[np.arange(T_) + t * T_], (H, T_)); c0, c1 = tile[0], tile[1]; d0 = np.exp(_tile_canvas(c0, 'logd')[:, ix]); d1 = np.exp(_tile_canvas(c1, 'logd')[:, ix]) + n0 = (_tile_canvas(c0)[:, ix] >= 0.5) & (_tile_canvas(c0, 'wall')[:, ix] < 0.5); n1 = (_tile_canvas(c1)[:, ix] >= 0.5) & (_tile_canvas(c1, 'wall')[:, ix] < 0.5); seen += int(n0.sum() + n1.sum()) + assert (d0[n0] <= s_t[n0] * math.exp(xf) * 1.02 + 100).all() and (d1[n1] >= s_t[n1] * math.exp(-xf) * 0.98 - 100).all(), ('a card tile is cut at another tile seam', t) + assert seen > 100_000, 'the fixture holds no card pixels' +def test_tile_is_a_crop_of_the_columns(): + """ridge.cards on a tile's columns (the 200 it owns and the apron) equals the same columns of ridge.cards on a wider run of columns, pixel for pixel, for fixed seams: the tile cut changes no pixel and adds no seam.""" + b = _bake(terrain(_receding, block(0, 359.99, 3000, 3600, 350)), [6]); x0 = 500; n = export.TILE_W + 2 * export.APRON; sl = slice(x0, x0 + n) + tile = ridge.cards(b['D'], b['a'][:, sl], b['h'][:, sl], b['seams'][:, sl], tuple(x[:, sl] for x in b['nrm']), material=ALPINE) + for c, w in zip(tile, b['cards']): + assert np.array_equal(_canvas(w)[:, sl], _tile_canvas(c)), 'a tile is not a crop of the columns'; seen = _tile_canvas(c) > 0 + for key in ('albedo', 'n_r', 'n_t', 'logd', 'wall', 'near'): assert np.array_equal(_canvas(w, key)[:, sl][seen], _tile_canvas(c, key)[seen]), ('a tile is not a crop of the columns', key) + +# ---------------------------------------------------------------------------------------- toy bakes: tile data made by hand, for the packer and the writer +def _toy(dists=(3000.0, 15000.0, 50000.0), bands=(300, 400, 500), tops=(300, 150, 60), amp=0.01): + """TILES tiles of len(dists) cards: card i is a solid band of rows (top, h) whose distance is dists[i] x (1 + amp sin x) across the columns, no wall; the opaque view is their composite. Returns the bake dict pack() reads.""" + n = export.TILE_W + 2 * export.APRON; x = np.arange(n); tile = []; k = len(dists) + for i in range(k): + ld = np.log(dists[i] * (1 + amp * np.sin(x * 0.3)))[None, :].repeat(bands[i], 0).astype(np.float32) + tile.append(dict(top=tops[i], alpha=np.ones((bands[i], n), np.float32), albedo=np.full((bands[i], n, 3), 0.4, np.float32), n_r=np.full((bands[i], n), 0.1, np.float32), n_t=np.full((bands[i], n), -0.1, np.float32), logd=ld, wall=np.zeros((bands[i], n), bool), near=np.zeros((bands[i], n), bool))) + comp = export.composite_alpha([(c['top'], c['alpha']) for c in tile], H, n) + return dict(cards=[[dict(c) for c in tile] for _ in range(export.TILES)], splits_km=[6.0 * (j + 1) for j in range(k - 1)], seams=np.tile(np.array(dists[:-1])[:, None] * 0.5, (1, W)), opaque=[comp.copy() for _ in range(export.TILES)], + view=dict(look_az_deg=36.0, plane_h=H, px_per_deg_h=ridge.HPX_DEG, px_per_deg_v=100.0, exaggeration=5.0, horizon_row=60.0, sky_row=24.0, near_row=396.0), meta=dict(curvature=dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF), encoding=dict(log_d_min=math.log(500.0), log_d_max=math.log(100000.0))), + place=dict(id='toy', name='Toy', lat=0.0, lon=0.0, altitude_km=0.0, eye_m=1.0, tz='UTC')) +def _write(out, b, packed, **kw): + args = dict(place=b['place'], view=b['view'], meta=b['meta'], packed=packed, opaque=b['opaque']); args.update(kw); return export.write_bake(out, **args) +def _refuses(out, b, packed, why, **kw): + try: _write(out, b, packed, **kw) + except export.Refusal: assert not os.path.exists(out), ('a refused bake left files', why) + else: assert False, why +def _pins(): + assert (export.RING_W, export.TILES, export.TILE_W, export.APRON, export.MAX_CARDS, export.BAKER_VERSION) == (6400, 32, 200, 2, 6, 7), 'the ring layout is pinned' + assert (export.TILE_BYTES_MAX, export.PLACE_BYTES_MAX, export.RESIDENT_BYTES_MAX, export.FIT_PX_MAX, export.R_MAX_FLOOR_M, export.PHI_STEPS) == (235_000, 7_500_000, 20_000_000, 24.0, 25.0, 24), 'the budgets and the fit bound are pinned' + assert abs(export.HFOV_MAX_DEG - 72 / 1.1) < 1e-12 + +def test_schema3(): + """The manifest validates; a tile array of the wrong length, a missing apron, a file named for another tile, and any key of schema 2 left behind (the camera's heading range and offset, the window, the plane width, the card's median and scale, the whole-bake w and h) are refused; the schema file is pinned; the layout constants are pinned.""" + _pins(); d = tempfile.mkdtemp() + try: + b = _toy(); pk = export.pack(b); dest = _write(d, b, pk); m = json.load(open(dest / 'manifest.json')); export.validate_manifest(m); mk = lambda: json.loads(json.dumps(m)) + assert m['schema'] == 3 and m['baker_version'] == 7 and set(m['view']) >= {'ring_w', 'tile_w', 'tiles', 'apron'} and 'rows_above' not in m['view'] and m['camera'] == dict(r_max_m=pk['camera']['r_max_m'], r_max_forward_m=pk['camera']['r_max_forward_m']) and m['camera']['r_max_forward_m'] >= m['camera']['r_max_m'] and len(m['tiles']) == 32 and 'w' not in m and 'h' not in m + def bad(f, why): + x = mk(); f(x) + try: export.validate_manifest(x) + except export.Refusal: return + raise AssertionError(why) + bad(lambda x: x['camera'].pop('r_max_forward_m'), 'a camera without its forward offset validated'); bad(lambda x: x['camera'].pop('r_max_m'), 'a camera without its offset validated') + bad(lambda x: x['tiles'].pop(), 'a manifest of 31 tiles validated'); bad(lambda x: x['tiles'][3].pop(), 'a tile with a card missing validated'); bad(lambda x: x['tiles'][3].append(None), 'a tile with an extra card validated'); bad(lambda x: x['view'].pop('apron'), 'a missing apron validated') + bad(lambda x: x['view'].update(apron=0), 'an apron of 0 validated'); bad(lambda x: x['tiles'][2][1]['colour'].update(file='card-1-t03-colour.webp'), 'a file named for another tile validated') + bad(lambda x: x['tiles'].__setitem__(slice(None), [[None] * 3 for _ in range(32)]), 'a card null in every tile validated'); bad(lambda x: x.update(bytes=x['bytes'] + 1), 'a wrong byte total validated') + for where, key in (('camera', 'heading_max' + '_deg'), ('view', 'window' + '_deg'), ('view', 'plane' + '_w'), ('view', 'rows_above'), ('camera', 'r_m'), (None, 'w'), (None, 'h')): # schema 2's names are spelled in pieces: the baker's tree must hold none of them + bad(lambda x: (x[where] if where else x).update({key: 1}), f'a leftover {key} validated') + bad(lambda x: x['cards'][0].update(**{'median' + '_m': 1.0}), 'a leftover median validated'); bad(lambda x: x['cards'][0].update(scale=1.0), 'a leftover scale validated'); bad(lambda x: x['tiles'][0][0].update(scale=1.0), 'a tile entry with a scale validated') + bad(lambda x: x['tiles'][0][0].update(distance_m='far'), 'a distance that is not a number validated'); bad(lambda x: x['place'].update(tz='Mars/Olympus'), 'a zone the system does not know validated') + assert json.load(open(os.path.join(SRC, 'ridge-bake.schema.json'))) == json.loads(json.dumps(export.SCHEMA)), 'ridge-bake.schema.json is stale (export.py --write-schema)' + finally: shutil.rmtree(d) +def test_manifest_v3_writer(): + """Two packs of one bake give the same bytes and bake_id; tiles[t][i] files are where the manifest says with the sizes it says and decode to tile_w + 2 apron columns; the bake_id is the sha256 of the files tile-major, then card, colour then geometry; the index points at the dir, a + rebake replaces the old dir, cards are nearest first with their seam medians, the attribution is the four pinned strings.""" + d = tempfile.mkdtemp() + try: + b = _toy(); pk = export.pack(b); pk2 = export.pack(b); files = lambda p: [(e['colour'], e['geometry']) for row in p['tiles'] for e in row if e]; assert files(pk) == files(pk2), 'two packs gave different bytes' + a = _write(d + '/a', b, pk); m = json.load(open(a / 'manifest.json')); export.validate_manifest(m); text = (a / 'manifest.json').read_bytes().decode('utf-8'); blank = text.replace(f'"bake_id": "{m["bake_id"]}"', f'"bake_id": "{export.BAKE_ID_BLANK}"'); assert blank != text and a.name == 'toy-' + m['bake_id'] and sorted(os.listdir(d + '/a')) == sorted(['index.json', a.name]) + import hashlib; want = hashlib.sha256(blank.encode() + b''.join(c + g for c, g in files(pk))).hexdigest()[:12]; assert m['bake_id'] == want and export.bake_id(blank, files(pk)) == want, 'bake_id is not the sha256 of the manifest with its id blanked, then the tile files tile-major, then card, colour then geometry' + assert export.bake_id(blank, [(g, c) for c, g in files(pk)]) != want and export.bake_id(blank, files(pk)[::-1]) != want and export.bake_id(blank, [f for i, f in enumerate(files(pk)) if i % 3 != 1] + [f for i, f in enumerate(files(pk)) if i % 3 == 1]) != want, 'bake_id ignores the file order' + pk3 = [list(f) for f in files(pk)]; pk3[40][1] += b'x'; assert export.bake_id(blank, [tuple(f) for f in pk3]) != want, 'a changed byte kept the bake_id' + assert export.bake_id(blank.replace('"r_max_forward_m"', '"r_max_forward_m "', 1), files(pk)) != want and export.bake_id(blank + ' ', files(pk)) != want, 'a changed manifest kept the bake_id' + import pathlib; was = pathlib.Path.write_text; pathlib.Path.write_text = lambda self, data, *a, **k: open(self, 'wb').write(data.replace('\n', '\r\n').encode('utf-8')) # a platform whose text files end lines with CRLF + try: w = _write(d + '/crlf', b, pk) + finally: pathlib.Path.write_text = was + raw = (w / 'manifest.json').read_bytes(); idx_raw = open(d + '/crlf/index.json', 'rb').read(); assert w.name == a.name and b'\r' not in raw and b'\r' not in idx_raw, 'the manifest or the index was written with the platform newline: the bytes served are not the bytes the id was hashed from' + assert hashlib.sha256(raw.replace(m['bake_id'].encode(), export.BAKE_ID_BLANK.encode()) + b''.join(c + g for c, g in files(pk))).hexdigest()[:12] == m['bake_id'] + pk4 = dict(pk, camera=dict(pk['camera'], r_max_forward_m=pk['camera']['r_max_forward_m'] + 0.1)); a4 = _write(d + '/d', b, pk4); assert a4.name != a.name and [(e['colour'], e['geometry']) for row in pk4['tiles'] for e in row if e] == files(pk), 'a manifest moved under the same bake id (tile bytes identical, camera differs)' + 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 len(m['cards']) == 3 + for t, row in enumerate(m['tiles']): + for i, e in enumerate(row): + for kind in ('colour', 'geometry'): f = a / e[kind]['file']; assert f.stat().st_size == e[kind]['bytes'] and export.decode(f.read_bytes()).shape[:2] == (e['h'], export.TILE_W + 2 * export.APRON), (t, i, kind) + assert m['bytes'] == sum(e[k]['bytes'] for row in m['tiles'] for e in row 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='toy', places={'toy': a.name}) + want = dict(credit_line='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.', + licence='Copernicus DEM licence: free, full and open access, with the credit line shown', dem_source='Copernicus DEM GLO-30 (30 m)', url='https://spacedata.copernicus.eu/collections/copernicus-digital-elevation-model'); assert m['attribution'] == want, m['attribution'] + c = _write(d + '/a', b, pk); assert c.name == a.name; other = dict(b['place'], id='other'); _write(d + '/a', b, pk, place=other); assert json.load(open(d + '/a/index.json'))['default'] == 'toy' + _write(d + '/a', b, pk, place=other, default='other'); assert json.load(open(d + '/a/index.json'))['default'] == 'other' + idx = json.load(open(d + '/a/index.json')); idx['default'] = 'gone'; open(d + '/a/index.json', 'w').write(json.dumps(idx)); _write(d + '/a', b, pk, place=other); assert json.load(open(d + '/a/index.json'))['default'] == 'other' + finally: shutil.rmtree(d) +def test_tile_crop_and_null(): + """Each card tile is exactly the rows where its 8-bit alpha is non-zero (top and h in the manifest are those rows, the files decode to that band, the written alpha is the card's); a card with no rows in a tile is null there, writes no file and the bake still validates; + a card empty everywhere is refused naming the splits, and a card with no solid terrain in any tile is refused.""" + d = tempfile.mkdtemp() + try: + b = _ring('wide3', WIDE3, [20, 55]); pk = export.pack(b); dest = _write(d, b, pk); m = json.load(open(dest / 'manifest.json')) + for t in (0, 9, 31): + for c, e in zip(b['cards'][t], m['tiles'][t]): + rows = np.flatnonzero(np.rint(_tile_canvas(c) * 255).max(1) > 0); assert e['top'] == rows[0] and e['h'] == rows[-1] - rows[0] + 1 == c['alpha'].shape[0], (t, e, rows[0], rows[-1]) + col = export.decode((dest / e['colour']['file']).read_bytes()); assert col.shape[:2] == (e['h'], export.TILE_W + 2 * export.APRON) and np.abs(col[..., 3].astype(int) - np.rint(c['alpha'] * 255)).max() == 0, 'the written alpha is not the card alpha' + t0 = _toy(); cs = [[dict(c) for c in tile] for tile in t0['cards']]; empty = dict(top=0, alpha=np.zeros((0, 204), np.float32), albedo=np.zeros((0, 204, 3), np.float32), n_r=np.zeros((0, 204), np.float32), n_t=np.zeros((0, 204), np.float32), logd=np.zeros((0, 204), np.float32), wall=np.zeros((0, 204), bool)) + cs[5][2] = empty; op = [x.copy() for x in t0['opaque']]; op[5] = export.composite_alpha([(c['top'], c['alpha']) for c in cs[5] if c['alpha'].shape[0]], H, 204); b5 = dict(t0, cards=cs, opaque=op); pk5 = export.pack(b5) + assert pk5['tiles'][5][2] is None and pk5['tiles'][4][2] is not None; dest = _write(d + '/null', b5, pk5); m5 = json.load(open(dest / 'manifest.json')); assert m5['tiles'][5][2] is None and not (dest / export.tile_file(2, 5, 'colour')).exists() and (dest / export.tile_file(2, 4, 'colour')).exists() + for i, why in ((1, '20 km'), (2, '55 km')): + gone = [[empty if j == i else c for j, c in enumerate(tile)] for tile in b['cards']] + try: export.pack(dict(b, cards=gone)) + except export.Refusal as e: assert f'card {i} is empty' in str(e) and why in str(e), str(e) + else: assert False, ('an empty card', i, 'was packed') + liquid = [[dict(c, alpha=c['alpha'] * 0.4) if j == 1 else c for j, c in enumerate(tile)] for tile in t0['cards']] + try: export.pack(dict(t0, cards=liquid)) + except export.Refusal as e: assert 'no solid terrain' in str(e), str(e) + else: assert False, 'a card with no solid pixel in any tile was packed' + walled = [[dict(c, wall=np.ones_like(c['wall'])) if j == 1 else c for j, c in enumerate(tile)] for tile in t0['cards']] + try: export.pack(dict(t0, cards=walled)) + except export.Refusal as e: assert 'no solid terrain' in str(e), str(e) + else: assert False, 'a card that is all wall was packed' + finally: shutil.rmtree(d) +def test_cover_and_size_refusals_write_nothing(): + """write_bake measures the files it is handed: a hole in one tile's card (alpha zeroed over a band of columns) fails that tile's cover check and names the tile, a card leaving the frame, a tile file without its apron, colour and geometry of two sizes and an opaque view of the wrong + rows are refused, and nothing is written.""" + d = tempfile.mkdtemp() + try: + b = _toy(); pk = export.pack(b); c = b['cards'][3][2]; hole = c['alpha'].copy(); hole[:, 100:140] = 0; bad = [list(r) for r in pk['tiles']]; bad[3][2] = dict(bad[3][2], colour=export.encode_colour(c['albedo'], hole)); _refuses(d + '/hole', b, dict(pk, tiles=bad), 'a bake whose card leaves a hole was written') + try: _write(d + '/hole', b, dict(pk, tiles=bad)) + except export.Refusal as e: assert 'tile 3' in str(e), str(e) + off = [list(r) for r in pk['tiles']]; off[7][0] = dict(off[7][0], top=H - 5); _refuses(d + '/off', b, dict(pk, tiles=off), 'a card leaving the frame was written') + narrow = [list(r) for r in pk['tiles']]; c0 = b['cards'][2][0]; narrow[2][0] = dict(narrow[2][0], colour=export.encode_colour(c0['albedo'][:, 2:-2], c0['alpha'][:, 2:-2]), geometry=export.encode_geometry(c0['n_r'][:, 2:-2], c0['n_t'][:, 2:-2], c0['logd'][:, 2:-2], b['meta']['encoding'])); _refuses(d + '/apron', b, dict(pk, tiles=narrow), 'a tile without its apron was written') + try: _write(d + '/apron', b, dict(pk, tiles=narrow)) + except export.Refusal as e: assert 'apron' in str(e), str(e) + mism = [list(r) for r in pk['tiles']]; mism[4][1] = dict(mism[4][1], geometry=export.encode_geometry(c0['n_r'][:50], c0['n_t'][:50], c0['logd'][:50], b['meta']['encoding'])); _refuses(d + '/size', b, dict(pk, tiles=mism), 'a colour and geometry of two sizes were written') + _refuses(d + '/rows', b, pk, 'view plane_h disagreeing with the opaque view was written', view=dict(b['view'], plane_h=H + 1)); _refuses(d + '/short', b, dict(pk, tiles=pk['tiles'][:31]), 'a bake of 31 tiles was written') + finally: shutil.rmtree(d) +def _flat_entry(top, h, w=export.TILE_W + 2 * export.APRON, seed=0, noise=False, distance_m=1000.0): + rng = np.random.default_rng(seed); alpha = np.ones((h, w), np.float32); rgb = rng.random((h, w, 3)).astype(np.float32) if noise else np.full((h, w, 3), 0.5, np.float32); geo = rng.random((h, w)).astype(np.float32) if noise else np.full((h, w), 0.5, np.float32) + enc = dict(log_d_min=0.0, log_d_max=1.0); return dict(top=top, colour=export.encode_colour(rgb, alpha), geometry=export.encode_geometry(geo, geo, geo, enc), distance_m=distance_m) +def test_card_cap_refusals(): + """A preset with 6 splits, or splits not increasing, is refused by load_preset before any march; a bake of 7 cards is refused; 6 cards that fit the budgets are written; 6 full-frame cards in every tile (the lit canvases of 13 tiles are 38 MB) are refused and write nothing.""" + d = tempfile.mkdtemp() + try: + for bad in ([5, 10, 20, 30, 40, 50], [6, 6], [6, 5], []): + p = os.path.join(d, 'p.json'); json.dump(dict(presets=[dict(id='x', tz='UTC', card_split_km=bad)]), open(p, 'w')) # a valid zone, so only the splits can refuse it + try: ridge.load_preset('x', p) + except export.Refusal: pass + else: assert False, ('a preset with splits', bad, 'was accepted') + json.dump(dict(presets=[dict(id='x')]), open(os.path.join(d, 'q.json'), 'w')) + try: ridge.load_preset('x', os.path.join(d, 'q.json')) + except export.Refusal: pass + else: assert False, 'a preset without card_split_km was defaulted' + 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] + 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 export.Refusal: 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)); 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, 204)) for _ in range(32)]; cards = lambda k: [dict(near_m=None if i == 0 else 1.0, far_m=None if i == k - 1 else 1.0) for i in range(k)]; cam = dict(r_max_m=100.0, r_max_forward_m=100.0) + big = dict(cards=cards(6), tiles=[[_flat_entry(0, H, seed=0)] + [_flat_entry(0, H) for _ in range(5)] for _ in range(32)], camera=cam) + try: export.write_bake(d + '/big', place, view, meta, big, full) + except export.Refusal as e: assert 'consecutive tiles' in str(e), str(e) + else: assert False, 'six full-frame cards in every tile were written' + assert not os.path.exists(d + '/big') + ok = dict(cards=cards(6), tiles=[[_flat_entry(0, H, seed=0)] + [_flat_entry(0, 100, seed=i) for i in range(1, 6)] for _ in range(32)], camera=cam); dest = export.write_bake(d + '/six', place, view, meta, ok, full); assert len(json.load(open(dest / 'manifest.json'))['cards']) == 6 + fwd = lambda r: dict(ok, camera=dict(r_max_m=100.0, r_max_forward_m=r)); bands6 = [[H] + [100] * 5] * 32; assert export.resident_bytes(bands6, export.run_tiles(100.0, 1000.0)) <= export.RESIDENT_BYTES_MAX < export.resident_bytes(bands6, export.run_tiles(1e6, 1000.0)), 'the fixture cannot tell the gate at r_max_forward_m from the gate at r_max_m' + try: export.write_bake(d + '/fwd', place, view, meta, fwd(1e6), full) + except export.Refusal as e: assert 'consecutive tiles' in str(e), str(e) + else: assert False, 'a bake whose forward offset breaks the resident gate was written' + try: export.write_bake(d + '/low', place, view, meta, fwd(50.0), full) + except export.Refusal as e: assert 'below r_max_m' in str(e), str(e) + else: assert False, 'a bake whose forward offset is below the worst-case offset was written' + assert not os.path.exists(d + '/fwd') and not os.path.exists(d + '/low') + try: export.check_budget(7, [1000] * 32, [[10] * 7] * 32, 100.0, 1000.0) + except export.Refusal as e: assert 'above 6' in str(e) + else: assert False, '7 cards were accepted' + finally: shutil.rmtree(d) +def test_budgets(): + """A tile over 235 kB, a place over 7.5 MB and a resident run over 20 MB each refuse and one byte (one band row) under passes; the resident run wraps the ring: the last tiles and the first count as consecutive.""" + none = [[] for _ in range(export.TILES)]; call = lambda tb, bands, r=100.0, rmin=1000.0: export.check_budget(3, tb, bands, r, rmin) + def refused(*a, **k): + try: call(*a, **k) + except export.Refusal: return True + return False + assert not refused([235_000] + [0] * 31, none) and refused([235_001] + [0] * 31, none), 'the tile cap' + assert not refused([234_375] * 32, none) and refused([234_375] * 31 + [234_376], none), 'the place cap' + rows = 20_000_000 // (4 * export.LIT_W); one = lambda h: [[h]] + [[] for _ in range(31)] + assert not refused([0] * 32, one(rows)) and refused([0] * 32, one(rows + 1)), 'the resident cap' + n = export.run_tiles(100.0, 1000.0); assert 5 < n < 32; split = [[] for _ in range(32)]; split[31] = [rows // 2]; split[0] = [rows - rows // 2 + 1] + assert refused([0] * 32, split), 'the resident run does not wrap the ring (tile 31 and tile 0 are consecutive)'; split[0] = [rows - rows // 2]; assert not refused([0] * 32, split) + far = [[] for _ in range(32)]; far[0] = [rows // 2]; far[n + 3] = [rows - rows // 2 + 1]; assert not refused([0] * 32, far), 'a run is only N tiles long'; far[n - 1] = far[n + 3]; far[n + 3] = []; assert refused([0] * 32, far) + assert export.run_tiles(0.0, 1000.0) == math.ceil(export.HFOV_MAX_DEG / 11.25) + 5 and export.run_tiles(250.0, 20000.0) > export.run_tiles(25.0, 20000.0) and export.run_tiles(1e9, 1.0) == 32, 'N = ceil(arc_max / 11.25) + 1 + 4' + rows_t = [[10, 20] if t in (30, 31, 0, 1) else [] for t in range(32)]; assert export.resident_bytes(rows_t, 4) == 4 * export.LIT_W * 120 and export.resident_bytes(rows_t, 3) == 4 * export.LIT_W * 90 and export.resident_bytes(rows_t, 40) == 4 * export.LIT_W * 120 +def _fit(d, r, phis=None): return export.fit_px(d, r, ridge.HPX_DEG, phis) +def _brute_fit(d, r, phis, ppd, n=20001): + """The worst error of the best line, by brute force: the least-squares line over n uniform samples (the integral to within 1e-4 of itself), the error on the same n.""" + half = math.radians(export.HFOV_MAX_DEG) / 2; b = np.linspace(-half, half, n)[None, :]; p = np.linspace(0, 2 * math.pi, phis, endpoint=False)[:, None]; A = np.arctan2(d * np.sin(b) - r * np.sin(p), d * np.cos(b) - r * np.cos(p)) + bc = b - b.mean(); s = (A * bc).sum(-1, keepdims=True) / (bc * bc).sum(); return math.degrees(float(np.abs(A - (A.mean(-1, keepdims=True) + s * bc)).max())) * ppd +def test_fit_px_is_the_continuous_error(): + """fit_px is the worst error of the best line over the whole viewport, not of a few samples of it: it equals a brute-force measure (20001 samples, line and error) within 0.1 card px at the offsets the bound is set at (an offset a few samples undercount by more than that), over the whole circle and at phi = 0.""" + ppd = ridge.HPX_DEG; seen = 0 + for d, r, phis in ((410.0, 205.0, 1), (410.0, 98.0, export.PHI_STEPS), (1500.0, 600.0, 1), (1500.0, 300.0, export.PHI_STEPS), (60.0, 30.0, export.PHI_STEPS), (20000.0, 9000.0, 1)): + got, want = _fit(d, r, phis), _brute_fit(d, r, phis, ppd); assert abs(got - want) < 0.1, ('fit_px is not the continuous error', d, r, phis, got, want); seen += want > 5 + assert seen >= 4, 'the cases are too tame to tell a coarse measure from the continuous one' +def test_r_max(): + """On a card at 1.5 km: r_max_m falls as FIT_PX_MAX falls and is at most half the distance; it is the largest offset within the bound (the fit error at r_max is within it, a little more is not); a forward-only sweep of phi finds a larger r_max than the whole circle (the error is in the phi + that is not forward); the binding card tile is the nearest one (each tile's line is fitted at its own distance_m); the resident gate binds when its tiles are heavy; a place whose r_max_m is below 25 refuses and names the card and tile.""" + ppd = ridge.HPX_DEG; dist = [[1500.0] for _ in range(32)]; bands = [[100] for _ in range(32)]; saved = (export.FIT_PX_MAX, export.PHI_STEPS) + try: + r = export.solve_r_max(dist, bands, ppd); assert 25 < r <= 750 and _fit(1500.0, r) <= export.FIT_PX_MAX + 1e-9 and _fit(1500.0, r + 0.5) > export.FIT_PX_MAX, ('r_max is not the largest offset within the bound', r, _fit(1500.0, r), _fit(1500.0, r + 0.5)) + export.FIT_PX_MAX = 12.0; r12 = export.solve_r_max(dist, bands, ppd); export.FIT_PX_MAX = 60.0; r60 = export.solve_r_max(dist, bands, ppd); export.FIT_PX_MAX = saved[0]; assert r12 < r < r60, (r12, r, r60) + export.FIT_PX_MAX = 1e9; assert export.solve_r_max(dist, bands, ppd) == 750.0, 'r_max is not capped at half the nearest distance'; export.FIT_PX_MAX = saved[0] + export.PHI_STEPS = 1; rf = export.solve_r_max(dist, bands, ppd); export.PHI_STEPS = saved[1]; assert rf > r + 5, ('a forward-only sweep finds the same r_max', rf, r) + rp = export.solve_r_max(dist, bands, ppd, phis=1); assert rp == rf and 25 < rp <= 750 and _fit(1500.0, rp, 1) <= export.FIT_PX_MAX + 1e-9 and _fit(1500.0, rp + 0.5, 1) > export.FIT_PX_MAX, ('the phi = 0 bound is not the largest offset within the bound at phi = 0', rp, rf) + assert _fit(1500.0, rp) > export.FIT_PX_MAX, 'the forward offset fits at some other phi, so the two numbers do not differ' + mixed = [[1500.0 if t == 3 else 9000.0] for t in range(32)]; assert export.solve_r_max(mixed, bands, ppd) == r, 'the binding tile is not the nearest one' + dist2 = [[20000.0] for _ in range(32)]; free = export.solve_r_max(dist2, bands, ppd); heavy = [[1700000 // (4 * export.LIT_W)] for _ in range(32)]; held = export.solve_r_max(dist2, heavy, ppd) + assert held < free - 100 and export.resident_bytes(heavy, export.run_tiles(held, 20000.0)) <= export.RESIDENT_BYTES_MAX < export.resident_bytes(heavy, export.run_tiles(held + 1.0, 20000.0)), ('the resident gate does not bind r_max', held, free) + held_f = export.solve_r_max(dist2, heavy, ppd, phis=1); assert held_f >= held and export.resident_bytes(heavy, export.run_tiles(held_f, 20000.0)) <= export.RESIDENT_BYTES_MAX < export.resident_bytes(heavy, export.run_tiles(held_f + 1.0, 20000.0)), ('the resident gate does not bind the forward offset', held_f, held) + two = [[5000.0, 40.0 if t == 7 else 5000.0] for t in range(32)] + try: export.solve_r_max(two, [[100, 100] for _ in range(32)], ppd) + except export.Refusal as e: assert 'below 25' in str(e) and 'card 1' in str(e) and 'tile 7' in str(e), str(e) + else: assert False, 'a bake whose r_max_m is below 25 was accepted' + close = [[30.0] for _ in range(32)] + try: export.solve_r_max(close, bands, ppd) + except export.Refusal as e: assert 'below 25' in str(e) and 'card 0' in str(e), str(e) + else: assert False, 'a nearest card at 30 m was accepted' + finally: export.FIT_PX_MAX, export.PHI_STEPS = saved +def test_pack_distance_and_r_max_in_the_bake(): + """pack: a card tile's distance_m is exp(median ln d) over the interior solid pixels that are not wall (not the wall rows, not the apron columns); the manifest camera is the r_max_m of those distances and no per-card scale or median is written.""" + b = _toy(); cs = [[dict(c) for c in tile] for tile in b['cards']]; c = dict(cs[10][1]); n = c['alpha'].shape[0]; wall = np.zeros_like(c['wall']); wall[:n * 3 // 4] = True; ld = np.where(wall, c['logd'] + 3.0, c['logd']).copy(); ld[:, :2] += 2.0; ld[:, -2:] += 2.0; cs[10][1] = dict(c, wall=wall, logd=ld) + pk = export.pack(dict(b, cards=cs)); inner = (slice(None), slice(2, -2)); want = float(np.exp(np.median(ld[inner][~wall[inner]]))); with_wall = float(np.exp(np.median(ld[inner]))); assert abs(with_wall - want) > 0.05 * want, 'the fixture cannot tell wall rows from ground' + assert abs(pk['tiles'][10][1]['distance_m'] - want) < 1e-9 * want, ('the distance counted wall rows or the apron', pk['tiles'][10][1]['distance_m'], want); assert set(pk['tiles'][10][1]) == {'top', 'colour', 'geometry', 'distance_m'} and set(pk['cards'][0]) == {'near_m', 'far_m'} + base = export.pack(b); assert base['camera']['r_max_m'] >= 25 and base['camera']['r_max_forward_m'] >= base['camera']['r_max_m'] and abs(base['report']['nearest_m'] - min(float(np.exp(c[0]['logd'][:, 2:-2].min())) for c in b['cards'])) < 1e-6 and len(base['report']['fit_px']) == 3 and max(base['report']['fit_px']) <= export.FIT_PX_MAX + 1e-6 + near = export.pack(_toy(dists=(1500.0, 15000.0, 50000.0))); assert near['camera']['r_max_forward_m'] > near['camera']['r_max_m'] + 5, ('the forward offset was searched over the whole circle', near['camera']) + assert abs(base['cards'][0]['far_m'] - 1500.0) < 1e-6 and base['cards'][0]['near_m'] is None and base['cards'][1]['near_m'] == base['cards'][0]['far_m'] +def test_the_sheet_draws_the_ring(): + """The contact sheet is the ring at 1/4 width (1600 px) with a mark on each of the 32 tile boundaries, in the composite, every card's strip and the depth image, stacked: composite, K cards, depth.""" + b = _ring('wide3', WIDE3, [20, 55]); png = export.sheet(b); img = export.imagecodecs.png_decode(png); k = 3; nb = b['cov'].shape[0]; assert img.shape == ((1 + k) * H + 2 * nb, W // 4, 3), img.shape + mark = np.arange(32) * 200 // 4; sky = np.array(export.SHEET_SKY); reddish = lambda px: (px[..., 0] > px[..., 2] + 40); assert reddish(img[2, mark].astype(int)).all() and not reddish(img[2, mark + 7].astype(int)).any(), 'the tile boundaries are not drawn on the composite' + assert reddish(img[(1 + k) * H + 3, mark].astype(int)).all(), 'the tile boundaries are not drawn on the depth image'; assert abs(img[2, 1].astype(int) - np.rint(np.array(export.SHEET_SKY) * 255)).max() <= 2, 'the sky is not the flat sky' + +# ---------------------------------------------------------------------------------------- the real thing: Vienna +_VIENNA = {} +def _vienna_bake(): + if 'b' not in _VIENNA: + saved = ridge.P + try: b = export.bake_place('vienna'); _VIENNA.update(b=b, pxv=ridge.PXDEG_V, P=dict(ridge.P), rowang=ridge.rowang.copy(), skyline=None) + finally: ridge.P = saved + return _VIENNA['b'] +def _vienna_ring(splits, tiles): + """Vienna's whole-ring march and seams for the given splits, cards on only the given tiles: (d, seams, {t: cards}, {t: opaque}).""" + saved = ridge.P + try: + p = ridge.configure(dict(ridge.load_preset('vienna'), card_split_km=splits)); d, _, Hh, _ = ridge.stage0(False); a, h = ridge.prefilter(d, Hh, p['prefilter_m']); ridge.set_view(a.max(0)); sm = ridge.seams(ridge.coverage(d, a), [k * 1000.0 for k in splits], d); op = ridge.opaque(a); D_, A_, H_, nrm = ridge.join_near(d, a, h, ridge.near_march(p['prefilter_m'])) + cols = lambda x, t: ridge.ring_cols(x, t * export.TILE_W - export.APRON, export.TILE_W + 2 * export.APRON) + return d, sm, {t: ridge.cards(D_, cols(A_, t), cols(H_, t), cols(sm, t), tuple(cols(x, t) for x in nrm), material=ALPINE) for t in tiles}, {t: cols(op, t) for t in tiles} + finally: ridge.P = saved +def test_vienna_k1_k2_k3(): + """Vienna with card_split_km [6], [6, 40] and [6, 20, 40]: 2, 3 and 4 cards, seams ordered in every column of the ring, each composite of a tile (the rest azimuth's, the north's and the last one) equals the opaque view within 0.02; the cross-fade column count is printed.""" + for sp in ([6], [6, 40], [6, 20, 40]): + d, sm, cs, op = _vienna_ring(sp, (0, 19, 31)); assert sm.shape == (len(sp), W) + if len(sp) > 1: assert (np.diff(np.log(sm), axis=0) >= 0.4 - 1e-9).all(), 'seams out of order' + for t, tile in cs.items(): + assert len(tile) == len(sp) + 1; comp = 1 - np.prod([1 - _tile_canvas(c) for c in tile], axis=0); assert np.abs(comp - op[t]).max() < 0.02, (sp, t, np.abs(comp - op[t]).max()) + xf = int(np.any([((0.02 < _tile_canvas(c)) & (_tile_canvas(c) < 0.98)).sum(0) > 3 for c in cs[19]], axis=0).sum()) + print(f' K={len(sp)} splits {sp}: {len(cs[19])} cards, tile 19 bands {[(c["top"], c["alpha"].shape[0]) for c in cs[19]]}, seam medians km {[round(float(np.median(s)) / 1000, 1) for s in sm]}, cross-fade columns {xf} of {export.TILE_W + 4} in tile 19') +def test_bake_place_manifest_fields_on_vienna(): + """bake_place on the real Vienna preset: 32 tiles of three cards, the place carries the ground (km) and the eye, horizon_row is the row where the elevation angle is 0, px_per_deg_h is the ring's, look_az_deg is the rest azimuth; the shared apron of neighbouring tiles is the same pixels + (the tile cut at the real preset), and write_bake of its packed tiles validates with index default 'vienna', no temp dir left, r_max_m and the worst fit error per card printed.""" + b = _vienna_bake(); P = _VIENNA['P']; rowang = _VIENNA['rowang']; pxv = _VIENNA['pxv']; pl, view = b['place'], b['view']; assert len(b['cards']) == 32 and all(len(t) == 3 for t in b['cards']) and len(b['opaque']) == 32 and b['seams'].shape == (2, W) + assert abs(pl['altitude_km'] * 1000 - P['ground_m']) < 1e-6 and abs(pl['eye_m'] - P['eye_m']) < 1e-9 and pl['id'] == 'vienna' and view['look_az_deg'] == P['az_center'] == 214.0 + assert 0 < view['sky_row'] < view['horizon_row'] < view['near_row'] < H and abs(rowang[int(view['horizon_row'])]) <= 1.0 / pxv, (view, rowang[int(view['horizon_row'])]); assert view['px_per_deg_h'] == ridge.HPX_DEG and abs(view['exaggeration'] - pxv / ridge.HPX_DEG) < 1e-9 + T_, A_ = export.TILE_W, export.APRON + for t in (0, 19, 31): + nxt = b['cards'][(t + 1) % 32] + for i, c in enumerate(b['cards'][t]): + assert (_tile_canvas(c)[:, T_ + A_:T_ + 2 * A_] == _tile_canvas(nxt[i])[:, A_:2 * A_]).all(), ('the apron is not the neighbour tile', t, i); seen = _tile_canvas(c)[:, T_ + A_:T_ + 2 * A_] > 0 + assert (_tile_canvas(c, 'logd')[:, T_ + A_:T_ + 2 * A_][seen] == _tile_canvas(nxt[i], 'logd')[:, A_:2 * A_][seen]).all(), ('the apron is not the neighbour tile', t, i, 'logd') + d = tempfile.mkdtemp() + try: + pk = export.pack(b); rp = pk['report']; print(' vienna r_max_m', pk['camera']['r_max_m'], 'r_max_forward_m', pk['camera']['r_max_forward_m'], 'nearest card m', round(rp['nearest_m']), 'resident run', rp['run_tiles'], 'tiles', rp['resident_bytes'], 'bytes; worst fit error per card (card px)', [round(x, 1) for x in rp['fit_px']], 'sky/low deg', round(b['v']['sky_deg'], 2), round(b['v']['low_deg'], 2), 'exaggeration', round(view['exaggeration'], 2)) + dest = _write(d, b, pk); m = json.load(open(dest / 'manifest.json')); export.validate_manifest(m); assert m['camera']['r_max_m'] >= export.R_MAX_FLOOR_M and m['camera']['r_max_forward_m'] >= m['camera']['r_max_m'] + assert json.load(open(d + '/index.json'))['default'] == 'vienna' and sorted(os.listdir(d)) == sorted(['index.json', dest.name]), os.listdir(d); print(' vienna manifest bytes', m['bytes'], 'largest tile', max(sum(e[k]['bytes'] for e in row if e for k in ('colour', 'geometry')) for row in m['tiles'])) + finally: shutil.rmtree(d) + +# ---------------------------------------------------------------------------------------- the written files are the cards +def test_written_cards_decode_to_the_cards_in_memory(): + """Vienna's cards in three tiles (north, the rest azimuth's, the wrap), written and decoded again: alpha exactly, albedo within the lossy codec (and straight, not premultiplied, at partial alpha), the normal channels in their order (R along the ray, G across it), and the log-distance over the encoding + range, within quantisation.""" + b = _vienna_bake(); d = tempfile.mkdtemp() + try: + dest = _write(d, b, export.pack(b)); m = json.load(open(dest / 'manifest.json')); enc = m['encoding']; span = enc['log_d_max'] - enc['log_d_min']; partial_seen = near_seen = 0 + for t in (0, 19, 31): + for c, rec in zip(b['cards'][t], m['tiles'][t]): + col = export.decode((dest / rec['colour']['file']).read_bytes()); geo = export.decode((dest / rec['geometry']['file']).read_bytes()); al = c['alpha']; wall = c['wall']; nr = c['near']; solid = (al > 0) & ~wall & ~nr; part = (al > 0.05) & (al < 0.95) & ~wall & ~nr; partial_seen += int(part.sum()); near_seen += int((nr & (al > 0)).sum()) + assert (col[..., 3] == np.rint(al * 255)).all(), 'alpha is not exact'; e = np.abs(col[..., :3] / 255.0 - c['albedo']).max(-1) + assert e[solid].mean() < 0.021 and np.percentile(e[solid], 99) < 0.081, ('albedo is off', e[solid].mean(), np.percentile(e[solid], 99)); assert part.sum() == 0 or e[part].mean() < 0.1, ('albedo at partial alpha is off: premultiplied?', e[part].mean()) + assert (geo[..., 3] == 255).all(); q = 1.0 / 255 + 1e-6; assert (((geo[..., 0] == 255) & (geo[..., 1] == 255)) == wall).all(), 'the wall code is not R = G = 255 on exactly the wall pixels' + assert np.abs(geo[..., 0] / 255.0 * 2 - 1 - c['n_r'])[solid].max() < 2 * q and np.abs(geo[..., 1] / 255.0 * 2 - 1 - c['n_t'])[solid].max() < 2 * q, 'a normal channel is off or swapped' + assert np.abs(enc['log_d_min'] + geo[..., 2] / 255.0 * span - c['logd'])[solid].max() < span * q, 'the log-distance is off or not over the encoding range' + assert np.abs(c['n_r'][solid]).mean() > 0.05 and np.abs(c['n_t'][solid]).mean() > 0.01 and np.abs(c['n_r'][solid].mean() - c['n_t'][solid].mean()) > 0.0, 'the fixture does not tell the channels apart' + assert col[..., :3][solid].mean() > 20, 'albedo is zeroed'; assert (geo[..., 2][nr & (al > 0)] == 0).all(), 'a near pixel is not at the clip distance (B = 0)' + assert partial_seen > 0, 'the fixture has no partial alpha'; assert near_seen > 1000, 'the fixture has no near ground' + finally: shutil.rmtree(d) + +# ---------------------------------------------------------------------------------------- wall rows +def _first_sample_angle(b, i): + """Per column, the angle of the first sample card i reads: the first sample at or beyond its near seam, less the cross-fade half-width (card 0: sample 0 of the joined march, the near start).""" + k0 = np.zeros(NW, int) if i == 0 else np.array([np.searchsorted(b['D'], b['seams'][i - 1][x] * math.exp(-ridge.XF)) for x in range(NW)]); return k0, b['a'][k0, np.arange(NW)] +def test_wall_rows_flagged(): + """Every card, card 0 included, flags as wall exactly the rows below the angle of its first sample (the extruded face of the ridge it starts at; card 0's first sample is the near march's, under the frame, so it has none); the wall carries R = G = 255 in the geometry file and no other pixel has r2 + t2 above 1.02; wall pixels keep that sample's + distance and their albedo is the ground material of the sample's height with the face up (so a steep face is not rock), constant down the column.""" + steep = 0 + for make in (lambda: _bake(WALLED, [20]), lambda: _bake(WIDE3, [20, 55]), lambda: _bake(_receding, [6]), lambda: _bake(_ramp, [20], fixed_m=[20000.0])): # the ramp's seam is fixed: the wall must stand on the slope, below the height where every material is rock or snow + b = make(); lo = ridge.rowang - 0.5 / ridge.PXDEG_V; seen = 0 + for i, c in enumerate(b['cards']): + k0, a0 = _first_sample_angle(b, i); want = (lo[:, None] < a0[None, :])[c['top']:c['top'] + c['alpha'].shape[0]]; assert (c['wall'] == want).all(), ('wall rows are not the rows below the first sample', i, int((c['wall'] != want).sum())); seen += int(want.sum()) + geo = export.decode(export.encode_geometry(c['n_r'], c['n_t'], c['logd'], dict(log_d_min=math.log(D[0]), log_d_max=math.log(D[-1])), c['wall'])); r, t = geo[..., 0] / 255.0 * 2 - 1, geo[..., 1] / 255.0 * 2 - 1; code = (geo[..., 0] == 255) & (geo[..., 1] == 255) + assert (code == c['wall']).all() and (r[~code] ** 2 + t[~code] ** 2 <= 1.02).all(), 'the wall code is not on exactly the wall pixels, or a real normal reaches it' + for x in np.flatnonzero(c['wall'].any(0)): + rows = np.flatnonzero(c['wall'][:, x]); ld = c['logd'][rows, x]; assert np.ptp(ld) < 1e-5 and abs(math.exp(ld[0]) - b['D'][k0[x]]) < 1e-3 * b['D'][k0[x]] + 60, ('a wall keeps its sample distance', x) + want_alb = ridge.albedo(np.array([b['h'][k0[x], x]]), np.array([1.0]), ALPINE)[0]; assert np.abs(c['albedo'][rows, x] - want_alb).max() < 1e-5, ('wall albedo is not the ground material with the face up', x) + assert seen > 1000, 'the fixture has no wall' + for i in range(1, len(b['cards'])): + c = b['cards'][i]; steep += int((np.sqrt(np.clip(1 - c['n_r'] ** 2 - c['n_t'] ** 2, 0, 1))[c['wall']] < 0.93).sum()) + assert steep > 1000, 'no wall pixel has a steep face under it: a wall lit by its own normal would pass' +def test_the_sheet_lights_a_wall_with_the_face_up(): + """The contact sheet shades a wall pixel as an up-facing one whatever normal the card carries there, and a non-wall pixel by its normal.""" + n = 4; c = dict(albedo=np.ones((n, n, 3), np.float32), alpha=np.ones((n, n), np.float32), n_r=np.full((n, n), 0.9, np.float32), n_t=np.zeros((n, n), np.float32), wall=np.zeros((n, n), bool)); c['wall'][:, :2] = True + rgb, _ = export.lit(c); L = np.array(export.SHEET_LIGHT) / np.linalg.norm(export.SHEET_LIGHT); up = 0.35 + 0.65 * L[2]; tilted = 0.35 + 0.65 * np.clip(0.9 * L[0] + np.sqrt(1 - 0.81) * L[2], 0, 1) + assert np.allclose(rgb[:, :2], up) and np.allclose(rgb[:, 2:], tilted) and abs(up - tilted) > 0.05, (rgb[0, 0], rgb[0, 3]) +# ---------------------------------------------------------------------------------------- the near clip, the ground rows +def _nearest_solid(c): + """The nearest solid (alpha >= 0.5) pixel that is neither wall nor near ground of a card tile's interior columns, metres; None where there is none (computed here from the arrays, not by pack).""" + ld, al, wl, nr = (c[k][:, 2:-2] for k in ('logd', 'alpha', 'wall', 'near')); m = (al >= 0.5) & ~wl & ~nr; return float(np.exp(np.float64(ld[m].min()))) if m.any() else None +def test_r_max_holds_for_the_nearest_terrain_of_every_tile_and_near_only_tiles_bind_at_the_clip(): + """The offset range is where the linear map holds for the NEAREST solid terrain each card draws in each tile (ruling ridge-offset-range-fit), not its median: a tile whose card 0 spans 600 to 2000 m has its median near 1200 m, and at the r_max the median would give the 600 m pixels err past FIT_PX_MAX. + So the fit at every tile's nearest solid pixel is within the bound at r_max_m (over the circle) and at r_max_forward_m (phi 0), and the bound is reached: a little more offset breaks it at the binding tile. A tile whose card 0 draws only near ground (under the clip) is slid at the clip distance (its distance_m) and binds there.""" + b = _toy(); cs = [[dict(c) for c in tile] for tile in b['cards']]; c = dict(cs[7][0]); n = c['alpha'].shape[1] + ld = np.log(np.linspace(600.0, 2000.0, n))[None, :].repeat(c['alpha'].shape[0], 0).astype(np.float32); cs[7][0] = dict(c, logd=ld) + bad = dict(cs[5][0]); cs[5][0] = dict(bad, near=np.ones_like(bad['near']), logd=np.full_like(bad['logd'], math.log(300.0))) # tile 5: card 0 is all near ground + pk = export.pack(dict(b, cards=cs)); r, rf = pk['camera']['r_max_m'], pk['camera']['r_max_forward_m']; ppd = ridge.HPX_DEG; worst = worst_f = 0.0; seen = 0 + for t, tile in enumerate(cs): + for i, card in enumerate(tile): + d = _nearest_solid(card) + if d is None: assert (t, i) == (5, 0), ('a tile has no solid terrain but was not made all near ground', t, i); d = ridge.NEAR_CLIP_M + seen += 1; assert export.fit_px(d, r, ppd) <= export.FIT_PX_MAX + 1e-6 and export.fit_px(d, rf, ppd, 1) <= export.FIT_PX_MAX + 1e-6, ('the nearest terrain of a tile is outside the fit bound', t, i, d, r, rf) + worst, worst_f = max(worst, export.fit_px(d, r + 0.5, ppd)), max(worst_f, export.fit_px(d, rf + 0.5, ppd, 1)) + assert seen == 32 * 3 and worst > export.FIT_PX_MAX and worst_f > export.FIT_PX_MAX, ('the range stops short of the bound of the nearest terrain', worst, worst_f) + assert abs(pk['tiles'][7][0]['distance_m'] - float(np.exp(np.median(np.log(np.linspace(600.0, 2000.0, n)))))) < 1.0, 'the manifest distance is still the median' + assert r < export.solve_r_max([[1200.0 if (t, i) == (7, 0) else None for i in range(3)] for t in range(32)], [[100] * 3 for _ in range(32)], ppd) - 5, 'the range is the median model' + near_free = export.pack(_toy()); assert pk['camera']['r_max_m'] < near_free['camera']['r_max_m'], 'the 600 m pixels do not bind' +def test_the_near_clip_compare_does_not_depend_on_float32_rounding(): + """A card 0 exactly at the near clip is accepted whatever the clip's value: exp of a float32 ln 700 is 699.99994, which a strict compare against a 700 m clip refuses; one 1.5 per mille under the clip is still refused.""" + saved = ridge.NEAR_CLIP_M; d = tempfile.mkdtemp() + try: + for clip in (500.0, 520.0, 700.0): + ridge.NEAR_CLIP_M = clip; b = _toy(dists=(clip, 15000.0, 50000.0), amp=0.0); pk = export.pack(b); assert pk['tiles'][0][0]['distance_m'] != 0 + try: dest = _write(d + f'/ok{clip:g}', b, pk) + except export.Refusal as e: assert 'near clip' not in str(e), ('a card 0 at the near clip was refused', clip, str(e)); raise + assert dest.exists(), ('a card 0 at the near clip was refused', clip) + b = _toy(dists=(698.9, 15000.0, 50000.0), amp=0.0); ridge.NEAR_CLIP_M = 700.0; _refuses(d + '/under', b, export.pack(b), 'a card 0 under the near clip was written') + finally: ridge.NEAR_CLIP_M = saved; shutil.rmtree(d) +def test_set_view_keeps_the_ground_rows_under_the_horizon(): + """A skyline +28 degrees high and +5 low is compressed below 1x so the horizon sits at row 450 or above (GROUND_ROWS_MIN rows under it); one +60 degrees high cannot hold them even at 0.5x and refuses naming sky_deg and the floor; a Vienna-like skyline + (the 10x clamp) and one that fits its anchors above 1x are unchanged to 1e-9; a low skyline never binds the horizon.""" + assert ridge.GROUND_ROWS_MIN == 150 and ridge.E_MIN == 0.5 and ridge.NEAR_CLIP_M == 500.0, 'the authored constants are pinned' + sk = np.full(W, 5.0); sk[100] = 60.0 + try: ridge.set_view(sk) + except export.Refusal as e: + if 'under the horizon' not in str(e): raise # not the refusal: a crash + assert '60.00' in str(e) and '8.89' in str(e) and '0.5x' in str(e), str(e) + else: assert False, 'a skyline that cannot hold the ground rows was accepted' + sk = np.full(W, 5.0); sk[100] = 28.0; v = ridge.set_view(sk) + assert v['horizon_row'] <= H - ridge.GROUND_ROWS_MIN + 1e-6 and v['exaggeration'] < 1 and v['binds'] == 'horizon' and abs(v['horizon_row'] - (H - ridge.GROUND_ROWS_MIN)) < 1e-6 and abs(v['px_per_deg'] - (H - 150 - 0.04 * H) / 28.0) < 1e-9, v + sk = np.full(W, 1.7); sk[7] = 2.0; v = ridge.set_view(sk); assert abs(v['px_per_deg'] - 10 * ridge.HPX_DEG) < 1e-9 and abs(v['horizon_row'] - (2.0 * 10 * ridge.HPX_DEG + 0.04 * H)) < 1e-9 and v['binds'] == 'ceiling', v + sk = np.full(W, 1.0); sk[7] = 3.0; sk[9] = -1.0; v = ridge.set_view(sk); assert abs(v['px_per_deg'] - 0.62 * H / 4.0) < 1e-9 and v['binds'] == 'skyline', v + sk = np.full(W, -30.0); sk[7] = 12.0; v = ridge.set_view(sk); assert abs(v['px_per_deg'] - 0.5 * ridge.HPX_DEG) < 1e-9 and v['binds'] == 'floor', v + sk = np.full(W, -9.0); sk[7] = -2.0; v = ridge.set_view(sk); assert v['horizon_row'] < 0.04 * H and v['binds'] != 'horizon', v +def test_the_near_clip_and_the_ground_rows_are_refused_at_the_writer(): + """The march starts at the authored near clip; write_bake refuses a bake whose card 0 stands nearer than it (nothing nearer is baked as terrain), and validate_manifest, which the writer and the committed bakes go through, refuses a plane with fewer than GROUND_ROWS_MIN rows under the horizon and accepts exactly that many.""" + assert D[0] == ridge.NEAR_CLIP_M == ridge.schedule(True)[0] and (np.diff(D) > 0).all(), 'the march does not start at the near clip' + d = tempfile.mkdtemp() + try: + b = _toy(); pk = export.pack(b); near = export.pack(_toy(dists=(300.0, 15000.0, 50000.0))); assert near['report']['nearest_m'] < ridge.NEAR_CLIP_M + try: _write(d + '/near', b, near) + except export.Refusal as e: assert 'near clip' in str(e), str(e); assert not os.path.exists(d + '/near') + else: assert False, 'a bake whose card 0 stands inside the near clip was written' + _refuses(d + '/short', b, pk, 'a plane with 149 rows under the horizon was written', view=dict(b['view'], horizon_row=451.0)); dest = _write(d + '/ok', b, pk, view=dict(b['view'], horizon_row=450.0)); m = json.load(open(dest / 'manifest.json')); export.validate_manifest(m) + m['view']['horizon_row'] = 450.5 + try: export.validate_manifest(m) + except export.Refusal as e: assert 'GROUND_ROWS_MIN' in str(e), str(e) + else: assert False, 'validate_manifest accepted a short plane' + finally: shutil.rmtree(d) +# ---------------------------------------------------------------------------------------- the near ground: the place's own terrain under the clip, drawn by card 0 inside the clip's silhouette +def _blend(L, ld, arr, x): + """arr (K, n) read at hits of log-distance ld (between the samples of log-distance L), blended by the fraction between the two samples: what ridge.cards does for a normal.""" + kk = np.searchsorted(L, ld, 'left'); kp = np.maximum(kk - 1, 0); t = np.clip((ld - L[kp]) / np.maximum(L[kk] - L[kp], 1e-12), 0, 1); return arr[kp, x] + t * (arr[kk, x] - arr[kp, x]) +def test_near_ground_draws_inside_the_clip_silhouette(): + """Eye 1.6 m over flat ground, a ramp hill at 150-300 m rising to 60 m (its crest stands far above the angle of the clip sample) and a far ridge in half the ring: card 0 composites to the opaque view of the FAR march (the hill above the clip line is not drawn; without the cap it stands above the far ridge), + its rows are near ground, not wall, and their normals are normals(dn, hn) of the near march blended at the hit (the ramp's, not the far sample 0's).""" + saved = ridge.P.get('eye_m'); ridge.P.update(eye_m=1.6) + try: + far = block(36, 359.99, 20000, 21500, 1500); hf = lambda dk, az: np.maximum(np.where((dk >= 150) & (dk < 300), 0.4 * (dk - 150), 0.0), np.asarray(far(dk, az), float)) + A, Hh = rays(hf, eye=1.6); a, h = ridge.prefilter(D, Hh, 0.0); ridge.set_view(a.max(0)); near = near_rays(hf); Dj, Aj, Hj, Nj = ridge.join_near(D, a, h, near); aw, hw, nj = _w(Aj), _w(Hj), tuple(_w(x) for x in Nj) + c = ridge.cards(Dj, aw, hw, np.zeros((0, NW)), nj, material=ALPINE)[0]; comp = _canvas(c); opq = ridge.opaque(_w(a)); err = np.abs(comp - opq).max(); assert err < export.COVER_TOL, ('card 0 draws outside the silhouette of the terrain at the clip', err) + free = ridge.cards(Dj, _w(np.concatenate([near[1], a])), hw, np.zeros((0, NW)), nj, material=ALPINE)[0]; assert np.abs(_canvas(free) - opq).max() > 5 * export.COVER_TOL, 'the fixture cannot tell a hill above the clip line (the cap is not tested)' + x = 300; al, nrr, wl, ld = c['alpha'][:, x], c['near'][:, x], c['wall'], c['logd'][:, x]; sel = (al > 0.99) & nrr; assert sel.sum() > 20 and not wl.any(), ('card 0 has wall rows', int(wl.sum()), int(sel.sum())); assert nrr[al > 0.5].mean() > 0.9, 'the rows under the clip are not flagged near' + L = np.log(Dj); q = ld[sel].astype(np.float64); want = np.stack([_blend(L, q, nj[0], x), _blend(L, q, nj[1], x), _blend(L, q, nj[2], x)]); m = np.sqrt((want ** 2).sum(0)) + assert np.abs(c['n_r'][sel, x] - want[0] / m).max() < 2e-3 and np.abs(c['n_t'][sel, x] - want[1] / m).max() < 2e-3, 'a near row has not its own normal'; assert (np.abs(c['n_r'][sel, x]) > 0.5).sum() > 5, 'the fixture has no ramp rows' + finally: ridge.P.update(eye_m=saved) +def test_near_ground_has_the_material_and_relief_of_its_own_heights(): + """Near heights stepping in blocks of 20 columns across the grass, forest and rock thresholds (100, 1000, 2100 m, the forest block a 45 degree hill) while the far march stands at 1000 m everywhere: every near row carries albedo(its own height, its own n_up), so the blocks differ where the ground does, and the hill face is steep (n_up < 0.93) and rock.""" + dn = ridge.near_schedule(); K, Kn = len(D), len(dn); a = np.tile(np.linspace(5.0, 12.0, K)[:, None], (1, W)); h = np.full((K, W), 1000.0); blk = (np.arange(W) // 20) % 3; base = np.array([100.0, 1000.0, 2100.0])[blk] + hn = np.broadcast_to(base[None, :], (Kn, W)).copy(); hn[:, blk == 1] += dn[:, None]; an = np.tile(np.linspace(-8.0, 5.0, Kn)[:, None], (1, W)); ridge.P.update(eye_m=EYE); ridge.set_view(a.max(0)) + Dj, Aj, Hj, Nj = ridge.join_near(D, a, h, (dn, an, hn)); assert all(np.array_equal(u[Kn:], w) for u, w in zip(Nj, ridge.normals(D, h))), 'the far normals are not those of the far march alone' + c = ridge.cards(Dj, _w(Aj), _w(Hj), np.zeros((0, NW)), tuple(_w(x) for x in Nj), material=ALPINE)[0]; up = np.sqrt(np.clip(1 - c['n_r'] ** 2 - c['n_t'] ** 2, 0, 1)); got = {} + for x in range(NW): + if not 3 <= x % 20 <= 16: continue + sel = (c['alpha'][:, x] > 0.99) & c['near'][:, x] & (c['logd'][:, x] < math.log(ridge.NEAR_CLIP_M) - 1e-6); assert sel.sum() > 50, ('no near rows', x) # the crest row that meets the clip sample itself is not under the clip + if blk[x] == 1: assert up[sel, x].max() < 0.93 and np.abs(c['albedo'][sel, x] - np.asarray(ALPINE['steep']['colour'])).max() < 1e-4, ('the hill face is not steep rock', x, float(up[sel, x].max())) + else: assert np.abs(c['albedo'][sel, x] - ridge.albedo(np.full(int(sel.sum()), base[x]), up[sel, x], ALPINE)).max() < 1e-5, ('a near row has not the material of its own height', x) + got[blk[x]] = c['albedo'][sel, x].mean(0) + assert np.abs(got[0] - got[1]).max() > 0.05 and np.abs(got[1] - got[2]).max() > 0.05 and np.abs(got[0] - got[2]).max() > 0.05, ('the blocks do not differ where the ground does', got) +def test_near_pixels_bind_at_the_clip_wherever_they_are(): + """Near pixels are drawn at the clip, so each tile's near pixels count in the r_max fit as terrain at the clip alongside its solid pixels, and never in distance_m. Card 0, every other tile 3000 m away: (a) a tile whose lower third is near ground at 150 m keeps its distance_m but binds at 500 m, and without those pixels binds nothing; + (b) a tile of near ground only has distance_m == NEAR_CLIP_M, binds exactly like terrain at 500 m, and write_bake accepts it; (c) a tile of near ground with a few stray solid pixels at 3000 m binds the same, whatever the stray count (no threshold).""" + b = _toy(); base = export.pack(b); cs = [[dict(c) for c in tile] for tile in b['cards']]; c = cs[3][0]; n = c['alpha'].shape[0]; near = np.zeros_like(c['near']); near[n * 2 // 3:] = True; ppd = ridge.HPX_DEG + dists = lambda pk: [[e and e['distance_m'] for e in row] for row in pk['tiles']]; at_clip = lambda src: dict(src, logd=np.full_like(src['logd'], math.log(ridge.NEAR_CLIP_M))) + cs[3][0] = dict(c, near=near, logd=np.where(near, math.log(150.0), c['logd']).astype(np.float32)); a = export.pack(dict(b, cards=cs)) + cs[3][0] = dict(c, alpha=np.where(near, 0.0, c['alpha']).astype(np.float32)); cut = export.pack(dict(b, cards=cs)); cs[3][0] = at_clip(c); clip = export.pack(dict(b, cards=cs)) + assert dists(a) == dists(cut) == dists(base) and cut['camera'] == base['camera'], ('near pixels were measured in distance_m', dists(a)[3], dists(base)[3]) + assert a['camera'] == clip['camera'] and a['camera']['r_max_m'] < base['camera']['r_max_m'] - 5 and a['camera']['r_max_forward_m'] < base['camera']['r_max_forward_m'] - 5, ('near pixels in a tile of terrain do not bind at the clip', a['camera'], base['camera']) + cs[3][0] = c; only = dict(cs[9][0]); cs[9][0] = dict(only, near=np.ones_like(only['near']), logd=np.full_like(only['logd'], math.log(300.0))); ob = dict(b, cards=cs); pk = export.pack(ob); d = tempfile.mkdtemp() + try: + assert pk['tiles'][9][0]['distance_m'] == ridge.NEAR_CLIP_M and pk['tiles'][8][0]['distance_m'] == base['tiles'][8][0]['distance_m'], ('a near-only tile', pk['tiles'][9][0]['distance_m']) + r, rf = pk['camera']['r_max_m'], pk['camera']['r_max_forward_m']; assert r < base['camera']['r_max_m'] - 5 and rf < base['camera']['r_max_forward_m'] - 5, ('a near-only tile does not bind', pk['camera'], base['camera']) + assert export.fit_px(ridge.NEAR_CLIP_M, r, ppd) <= export.FIT_PX_MAX + 1e-6 and export.fit_px(ridge.NEAR_CLIP_M, rf, ppd, 1) <= export.FIT_PX_MAX + 1e-6 and export.fit_px(ridge.NEAR_CLIP_M, r + 0.5, ppd) > export.FIT_PX_MAX, ('the near-only tile is not bound at the clip distance it is slid at', r, rf) + cs[9][0] = at_clip(only); assert export.pack(dict(b, cards=cs))['camera'] == pk['camera'], 'a near-only tile does not bind exactly like terrain at the clip' + assert _write(d + '/ok', ob, pk).exists(), 'a bake with a near-only tile was refused' + for stray in (1, 6, 40): # solid pixels at 3000 m among the near ground of a tile: it binds at the clip all the same + st = np.zeros_like(only['near']); st[:1, 10:10 + stray] = True; cs[9][0] = dict(only, near=~st, logd=np.where(st, only['logd'], math.log(300.0)).astype(np.float32)); sp = export.pack(dict(b, cards=cs)) + assert sp['camera'] == pk['camera'], ('stray solid pixels unbound a tile of near ground', stray, sp['camera'], pk['camera']) + finally: shutil.rmtree(d) +def test_cards_refuses_a_march_without_the_near_ground(): + """ridge.cards on a march whose first sample is the near clip (not joined to the near march) raises, naming join_near: card 0 can never extrude the clip sample again.""" + A, Hh = rays(THREE); ridge.P.update(eye_m=EYE); ridge.set_view(A.max(0)) + try: ridge.cards(D, _w(A), _w(Hh), np.zeros((0, NW)), material=ALPINE) + except export.Refusal as e: assert 'join_near' in str(e), str(e) + else: assert False, 'cards drew a march that starts at the near clip' +def test_near_march_starts_at_your_feet(): + """The near march starts at NEAR_START_M = 1 m, strictly increasing in steps of max(1 m, 0.02 d) up to 10 m, its last sample under the clip; over flat ground with a 1.6 m eye and a frame bottom below -8 degrees (the ray of the frame bottom meets the ground 11 m out) card 0 has no wall row and draws the ground to the bottom row.""" + dn = ridge.near_schedule(); st = np.diff(dn); assert dn[0] == ridge.NEAR_START_M == 1.0 and (st > 0).all() and dn[-1] < ridge.NEAR_CLIP_M and dn[-1] + 10.0 >= ridge.NEAR_CLIP_M and 150 < len(dn) < 190, (dn[0], len(dn)) + assert np.allclose(st, np.clip(0.02 * dn[:-1], 1.0, 10.0)), 'the steps are not max(1 m, 0.02 d) capped at 10 m' + saved = ridge.P.get('eye_m'); ridge.P.update(eye_m=1.6) + try: + hf = lambda dk, az: np.zeros_like(az); A, Hh = rays(hf, eye=1.6); a, h = ridge.prefilter(D, Hh, 0.0); sk = np.full(W, -5.0); sk[::2] = 2.0; ridge.set_view(sk); assert ridge.BOTTOM_DEG < -8.0, ridge.BOTTOM_DEG + Dj, Aj, Hj, Nj = ridge.join_near(D, a, h, near_rays(hf)); c = ridge.cards(Dj, _w(Aj), _w(Hj), np.zeros((0, NW)), tuple(_w(x) for x in Nj), material=ALPINE)[0] + assert not c['wall'].any() and c['near'].any(), ('card 0 has wall under the frame bottom', int(c['wall'].sum())); assert _canvas(c)[H - 1, 300] > 0.99 and c['near'][H - 1 - c['top'], 300], 'the bottom row is not near ground' + finally: ridge.P.update(eye_m=saved) +def test_near_march_is_float64_and_prefiltered(): + """near_march over an injected 64 x 64 mosaic: a plane tilted 5% at 3000 m gives adjacent-column near normals within 1e-3 of each other (heights in float32 would jump by 0.1 at a metre's distance); 30 m roof blocks under sigma 100 leave near heights within 2 m of each other, and without the prefilter they do not.""" + saved = (ridge.P, ridge.PXDEG_V); lat, lon = 47.0, 11.0; n = 64; ridge.P = dict(id='nearmos', lat=lat, lon=lon, rmax_km=1, eye_m=3001.6); key = (ridge.P['id'], ridge.mosaic_key(ridge.P)); ridge.PXDEG_V = 100.0 + x = np.arange(n)[None, :] * (111320.0 * math.cos(math.radians(lat)) / 3600.0); y = np.arange(n)[:, None] + try: + ridge._mos[key] = ((3000.0 + 0.05 * x + 0 * y).astype(np.float32), lat + 32 / 3600.0, lon - 32 / 3600.0); dn, an, hn = ridge.near_march(0.0); nn = ridge.normals(dn, hn) + assert hn.dtype == np.float64 and an.dtype == np.float64 and hn.shape == (len(ridge.near_schedule()), W) and (dn == ridge.near_schedule()).all(), (hn.dtype, hn.shape) + assert max(np.abs(np.diff(nn[0], axis=1)).max(), np.abs(np.diff(nn[1], axis=1)).max()) < 1e-3, ('the near normals jump between adjacent columns', float(np.abs(np.diff(nn[1], axis=1)).max())) + ridge._mos[key] = ((3000.0 + 30.0 * ((np.arange(n)[None, :] + y) % 2)).astype(np.float32), lat + 32 / 3600.0, lon - 32 / 3600.0); raw = np.ptp(ridge.near_march(0.0)[2]); flat = np.ptp(ridge.near_march(100.0)[2]) + assert raw > 20.0 and flat < 2.0, ('sigma is not applied to the near heights', raw, flat) + finally: ridge.P, ridge.PXDEG_V = saved; ridge._mos.pop(key, None) +# ---------------------------------------------------------------------------------------- rules that no other test touched +def test_seams_keep_their_separation(): + """Two authored targets closer than SEAM_SEP (6 and 7 km, 0.15 nat): the seams still sit at least 0.4 nat apart in every column.""" + s = _bake(THREE, [6, 7])['seams']; assert (np.log(s[1]) - np.log(s[0]) >= 0.4 - 1e-9).all(), float((np.log(s[1]) - np.log(s[0])).min()) +def test_elev_is_the_curved_refracted_angle(): + """elev(h, d) = atan2(h - eye - d^2 / 2R x (1 - k), d): at 80 km a 3000 m summit stands 0.3 deg lower than the flat angle, and curvature False gives the flat one.""" + ridge.P.update(eye_m=EYE); d = 80000.0; want = math.degrees(math.atan2(3000.0 - EYE - d * d / (2 * ridge.R_EARTH) * (1 - ridge.KREF), d)); flat = math.degrees(math.atan2(3000.0 - EYE, d)) + assert abs(float(ridge.elev(3000.0, d)) - want) < 1e-9 and abs(float(ridge.elev(3000.0, d, curvature=False)) - flat) < 1e-9 and flat - want > 0.25, (want, flat) + assert ridge.elev(np.array([[1000.0, 1200.0]]), np.array([[d], [d / 2]])).shape == (2, 2) +def test_coverage_counts_every_visible_row_including_the_foreground(): + """Per column the coverage sums to the visible rows of the opaque view: (min(skyline, top) - bottom) x px per degree, the rows below the first sample included once, not twice (a ground just under the eye shows below the first sample).""" + for i, hf in enumerate((terrain(block(0, 359.99, 0, 20000, 91), block(0, 359.99, 20000, 21500, 600)), THREE)): + A, Hh = rays(hf); ridge.P.update(eye_m=EYE); ridge.set_view(A.max(0)); aw = _w(A); cov = ridge.coverage(D, aw); want = np.clip(np.minimum(aw.max(0), ridge.TOP_DEG) - ridge.BOTTOM_DEG, 0, None) * ridge.PXDEG_V + assert np.abs(cov.sum(0) - want).max() < 1e-6, np.abs(cov.sum(0) - want).max(); assert cov.shape == (ridge.COV_BINS, NW) + if i == 0: assert (cov[0] > 100).all(), ('no foreground rows in the first bin', float(cov[0].min())) +def test_cards_interpolate_between_samples_and_renormalise(): + """On a ramp face every card pixel sits between two samples: its log-distance lies strictly between theirs (not on the nearer sample), and its normal is the normalised blend of theirs by that same fraction (the samples carry alternating normals, so a blend + that is not renormalised, or a hit that is not interpolated, differs).""" + hf = terrain(lambda dk, az: np.where(dk >= 4000, GROUND + 0.5 * (dk - 4000), 0.0) + 0 * az); A, Hh = rays(hf); ridge.P.update(eye_m=EYE); ridge.set_view(A.max(0)); Dj, aw, hw, _ = _join(hf, A, Hh); k = np.arange(len(Dj))[:, None] + nr = np.broadcast_to(np.where(k % 2 == 0, -0.8, 0.8), aw.shape).astype(float); nt = np.broadcast_to(np.where(k % 3 == 0, 0.3, -0.3), aw.shape).astype(float); nu = np.sqrt(1 - nr ** 2 - nt ** 2) * 0 + 0.5 + c = ridge.cards(Dj, aw, hw, np.zeros((0, NW)), nrm=(nr, nt, nu), material=ALPINE)[0]; x = 300; sel = np.flatnonzero(c['alpha'][:, x] > 0.999); ld = c['logd'][sel, x].astype(np.float64); L = np.log(Dj); kk = np.searchsorted(L, ld, 'left'); kp = kk - 1; ok = kp >= 0 + t = (ld - L[np.maximum(kp, 0)]) / (L[kk] - L[np.maximum(kp, 0)]); inner = ok & (t > 0.02) & (t < 0.98); assert inner.sum() > 0.3 * len(sel), ('hits sit on samples, not between them', int(inner.sum()), len(sel)) + mix = lambda arr: arr[np.maximum(kp, 0), x] + t * (arr[kk, x] - arr[np.maximum(kp, 0), x]); m = np.sqrt(mix(nr) ** 2 + mix(nt) ** 2 + mix(nu) ** 2); er = np.abs(c['n_r'][sel, x] - mix(nr) / m)[inner]; et = np.abs(c['n_t'][sel, x] - mix(nt) / m)[inner] + assert er.max() < 1e-3 and et.max() < 1e-3, ('the normal is not the normalised blend of the two samples', er.max(), et.max()) + +def _old_albedo(h, n_up): + """The oracle: ridge.albedo as it stood before materials, constants and all (copied here, the only place they live now).""" + GRASS, FOREST, ROCK, SNOW = (0.36, 0.44, 0.26), (0.22, 0.31, 0.20), (0.47, 0.44, 0.41), (0.93, 0.95, 0.97) + t = lambda a, b: np.clip((h - a) / (b - a), 0, 1)[..., None]; c = np.asarray(GRASS) + (np.asarray(FOREST) - GRASS) * t(150, 900); c = c + (np.asarray(ROCK) - c) * t(1300, 2000) + c = c + (np.asarray(ROCK) - c) * np.clip((0.93 - n_up) / 0.25, 0, 1)[..., None]; return c + (np.asarray(SNOW) - c) * (t(1900, 2300) * np.clip((n_up - 0.55) / 0.3, 0, 1)[..., None]) +def test_alpine_material_is_exactly_the_old_albedo(): + """places.json's alpine material evaluates to the old hard-coded formula bit for bit on a grid of heights 0-3000 m and n_up 0-1 (the four unrebaked places keep their bake ids because of it), and the canyon material differs from it where it should: the river floor is not grass.""" + hh, nn = np.meshgrid(np.linspace(0.0, 3000.0, 301), np.linspace(0.0, 1.0, 101), indexing='ij') + assert np.array_equal(ridge.albedo(hh, nn, ALPINE), _old_albedo(hh, nn)), 'alpine is not the old formula' + assert np.abs(ridge.albedo(np.array([800.0]), np.array([1.0]), ridge.load_material('canyon')) - _old_albedo(np.array([800.0]), np.array([1.0]))).max() > 0.1 +def test_canyon_material_has_strata_and_holds_on_cliffs(): + """The canyon (steep null, snow null): a cliff face has the colour of its height, not a rock grey (a flat and a steep face at one height agree), and the bands are distinct colours over height.""" + cy = ridge.load_material('canyon'); hs = np.linspace(800.0, 2500.0, 200); flat = ridge.albedo(hs, np.ones_like(hs), cy); steep = ridge.albedo(hs, np.full_like(hs, 0.3), cy) + assert np.array_equal(flat, steep), 'a steep face changes the canyon colour'; assert np.abs(np.diff(flat, axis=0)).sum() > 1.0 and len(np.unique(np.rint(flat * 255), axis=0)) > 20, 'the canyon has no strata' +def test_an_unknown_material_name_is_refused(): + """A place naming a material that places.json does not hold is a Refusal from the baker's own loader, not the alpine fallback; a malformed material is refused too.""" + with tempfile.TemporaryDirectory() as d: + p = os.path.join(d, 'm.json'); json.dump(dict(materials=dict(alpine=ALPINE, bad=dict(ALPINE, base=[2, 0, 0]))), open(p, 'w')) + assert ridge.load_material('alpine', p) == ALPINE + for name in ('canyon', '', 'Alpine'): + try: ridge.load_material(name, p) + except export.Refusal as ex: assert repr(name) in str(ex), ex + else: assert False, ('an unknown material was accepted', name) + try: ridge.load_material('bad', p) + except export.Refusal: pass + else: assert False, 'a malformed material was accepted' + json.dump(dict(presets=[]), open(p, 'w')) + try: ridge.load_material('alpine', p) + except export.Refusal: pass + else: assert False, 'a file without materials gave a material' + +def test_the_ring_cut_paints_with_the_material_it_is_given(): + """export.cut_ring hands its material to every card: the same terrain cut with the canyon material has a different albedo in tile 0 than with the alpine one, and the same alpha.""" + b = _ring('wide3', WIDE3, [20, 55]); A, Hh = rays(WIDE3); ridge.P.update(eye_m=EYE); a, h = ridge.prefilter(D, Hh, 0.0); ridge.set_view(a.max(0)) + c = export.cut_ring(D, a, h, [20, 55], near_rays(WIDE3), ridge.load_material('canyon'))['cards'][0] + assert any(not np.array_equal(x['albedo'], y['albedo']) and np.array_equal(x['alpha'], y['alpha']) for x, y in zip(c, b['cards'][0])), 'the ring cut ignores its material' + +TESTS = [v for k, v in sorted(globals().items()) if k.startswith("test_")] +if __name__ == '__main__': + fails = 0 + for t in TESTS: + try: t(); print("PASS", t.__name__) + except Exception as e: fails += 1; print("FAIL", t.__name__, "|", type(e).__name__, "|", traceback.extract_tb(e.__traceback__)[-1].filename, "|", repr(e)[:300]) # name | class | file of the innermost frame | repr: mutate.py kills only on an AssertionError raised in this directory + print("failures:", fails); sys.exit(1 if fails else 0) diff --git a/scripts/ridge-sky/build-night-sky.py b/scripts/ridge-sky/build-night-sky.py new file mode 100644 index 00000000..984548fd --- /dev/null +++ b/scripts/ridge-sky/build-night-sky.py @@ -0,0 +1,121 @@ +"""Pack the night sky's data into src/app/features/scene/ridge/nightSkyData.ts. + +Usage (parse downloads with isolated mode): + python -I scripts/ridge-sky/build-night-sky.py BSC5.DAT.GZ CONSTELLATIONS.LINES.JSON OUT.ts [MAX_MAG] + +Inputs, each in its own directory, never run from inside it: + bsc5.dat.gz Yale Bright Star Catalogue, 5th revised ed. (Hoffleit & Warren 1991), public domain; CDS/VizieR V/50. + CDS was unreachable on 2026-11-20, so the file is the SAO Telescope Data Center's copy of the same + catalogue: http://tdc-www.harvard.edu/catalogs/bsc5.dat.gz (fixed-width, CDS V/50 `catalog` layout). + constellations.lines.json d3-celestial (Olaf Frohn), BSD-3-Clause: + https://github.com/ofrohn/d3-celestial/blob/master/data/constellations.lines.json + GeoJSON MultiLineStrings of [RA, Dec] degrees, J2000. + +Stars (stars cut to Vmag <= MAX_MAG, default 5.5), 6 bytes each: RA uint16 (360 deg / 65536), Dec uint16 ((dec + 90) / 180 * 65535), +Vmag uint8 ((V + 2) * 20), B-V uint8 ((B-V + 0.5) * 50; missing B-V stored as 0.65). Little endian, base64. +Lines: per chain a uint8 vertex count then that many (RA uint16, Dec uint16) pairs, same scaling; chains concatenated; base64. +""" +import base64 +import gzip +import hashlib +import json +import struct +import sys + + +def sha256(path): + h = hashlib.sha256() + with open(path, "rb") as f: + h.update(f.read()) + return h.hexdigest() + + +def ra16(deg): + return int(round((deg % 360.0) / 360.0 * 65536.0)) % 65536 + + +def dec16(deg): + return int(round((deg + 90.0) / 180.0 * 65535.0)) + + +def stars(path, max_mag): + out = [] + for line in gzip.open(path, "rt", encoding="latin-1"): + if len(line) < 114 or not line[75:77].strip(): + continue # entries struck from the catalogue carry no position + try: + ra = (int(line[75:77]) + int(line[77:79]) / 60.0 + float(line[79:83]) / 3600.0) * 15.0 + dec = int(line[84:86]) + int(line[86:88]) / 60.0 + int(line[88:90]) / 3600.0 + dec = -dec if line[83] == "-" else dec + v = float(line[102:107]) + except ValueError: + continue + if v > max_mag: + continue + bv_text = line[109:114].strip() + bv = float(bv_text) if bv_text else 0.65 + out.append((ra, dec, v, bv)) + out.sort(key=lambda s: s[2]) # brightest first: a prefix is the brighter stars + return out + + +def pack_stars(rows): + buf = bytearray() + for ra, dec, v, bv in rows: + vq = min(255, max(0, int(round((v + 2.0) * 20.0)))) + bq = min(255, max(0, int(round((bv + 0.5) * 50.0)))) + buf += struct.pack(" 4 else 5.5 + rows = stars(bsc, max_mag) + star_bytes = pack_stars(rows) + line_bytes, chains = pack_lines(lines) + text = f"""/* eslint-disable */ +// GENERATED by scripts/ridge-sky/build-night-sky.py: do not edit. The night sky's data, J2000. +// Stars: Yale Bright Star Catalogue, 5th revised ed. (Hoffleit & Warren 1991; public domain), Vmag <= {max_mag}, {len(rows)} stars. +// source http://tdc-www.harvard.edu/catalogs/bsc5.dat.gz (copy of CDS/VizieR V/50), sha256 {sha256(bsc)} +// Constellation lines: d3-celestial constellations.lines.json (Olaf Frohn, BSD-3-Clause), {chains} chains. +// source https://github.com/ofrohn/d3-celestial/blob/master/data/constellations.lines.json, sha256 {sha256(lines)} +// Layout: see the generator's docstring. Stars are sorted brightest first. + +export const STAR_COUNT = {len(rows)}; +export const STARS_B64 = ` +{wrap(base64.b64encode(star_bytes).decode())} +`; + +export const LINE_CHAINS = {chains}; +export const LINES_B64 = ` +{wrap(base64.b64encode(line_bytes).decode())} +`; +""" + with open(out, "w", encoding="utf-8", newline="\n") as f: + f.write(text) + print(f"{len(rows)} stars, {chains} chains, {len(star_bytes)} + {len(line_bytes)} bytes") + + +main() diff --git a/src/app/components/nav/styles.css.ts b/src/app/components/nav/styles.css.ts index 5156ed41..a3845e90 100644 --- a/src/app/components/nav/styles.css.ts +++ b/src/app/components/nav/styles.css.ts @@ -133,7 +133,7 @@ const NavItemBase = style({ backgroundColor: ContainerHover, }, // While the background scene runs the shell is clear (sceneShell.css.ts); a row is a faint - // wash of the theme's own surface: the terrain stays visible, the text stays readable. + // wash of the theme's own surface: the scene stays visible, the text stays readable. // Hover, the selected row and a press each strengthen it a step. ':root[data-scene] &': { backgroundColor: `color-mix(in srgb, ${surfaceInk} ${SCRIM_ROW}, transparent)`, diff --git a/src/app/features/estate/EstateNavigator.tsx b/src/app/features/estate/EstateNavigator.tsx index b560e08c..ba4246cb 100644 --- a/src/app/features/estate/EstateNavigator.tsx +++ b/src/app/features/estate/EstateNavigator.tsx @@ -37,7 +37,7 @@ import { searchModalAtom } from '../../state/searchModal'; import { getCanonicalAliasOrRoomId } from '../../utils/matrix'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { MINDS } from '../../components/message/pose/poses'; -import { MediaLink, MediaNote, useMindMedia } from './MediaRow'; +import { MediaLink, MediaNote, useCommons, useMindMedia } from './MediaRow'; import { MediaRow as MediaRowState } from './mediaRoom'; import { useSelectedRoom } from '../../hooks/router/useSelectedRoom'; import { useCallEmbed } from '../../hooks/useCallEmbed'; @@ -55,7 +55,7 @@ import { activateEstateRoom, awaitMyJoin } from './joinEstateRoom'; import { useEstate, useEstateRootId } from './useEstate'; import * as css from './EstateNavigator.css'; import { DeskEntry } from '../desk'; -import { SkyStateControl } from '../scene/SkyStateControl'; +import { SceneViewEntry } from '../scene/SceneViewEntry'; type IconSrc = ComponentProps['src']; @@ -194,6 +194,15 @@ function MindMedia({ media }: { media: MediaRowState }) { return ; } +/** The shared Commons room above the tiers: a link when joined, a join row otherwise, nothing when there is none. */ +function CommonsEntry() { + const mx = useMatrixClient(); + const room = useCommons(); + if (!room) return null; + if (room.state === 'joined') return ; + return ; +} + function GroupSection({ tierId, group }: { tierId: string; group: EstateGroup }) { const media = useMindMedia(group.mind, group.rooms); const hasMedia = MINDS.includes(group.mind); @@ -345,6 +354,7 @@ function EstateTiers({ rootId }: { rootId: string }) { return ( <> + {tiers.map((tier) => ( ))} @@ -379,7 +389,7 @@ export function EstateNavigator() { {title} - + { expect(text(html)).toBe('Media'); expect(html).toContain('href="/home/%23void-files%3Agamecult.org/"'); }); + + it('the Commons link reads "Commons" and opens the room', () => { + const html = renderToStaticMarkup( + + + + ); + expect(text(html)).toBe('Commons'); + expect(html).toContain('href="/home/%23commons%3Agamecult.org/"'); + }); }); diff --git a/src/app/features/estate/MediaRow.tsx b/src/app/features/estate/MediaRow.tsx index 6277f09c..7d64497a 100644 --- a/src/app/features/estate/MediaRow.tsx +++ b/src/app/features/estate/MediaRow.tsx @@ -15,7 +15,10 @@ import { useEstateRootId } from './useEstate'; import { STEWARDSHIPS_KEY, MediaRow as MediaRowState, + commonsAlias, + commonsRow, lookupMediaRoom, + lookupZoneRoom, mediaRoomIdFromStewardships, mediaRow, typedMediaRoom, @@ -44,7 +47,7 @@ export function MediaNote({ note, title }: { note: string; title?: string }) { } /** The joined Media row: opens the room, which shows its album view. */ -export function MediaLink({ to }: { to: string }) { +export function MediaLink({ to, label = 'Media' }: { to: string; label?: string }) { return ( @@ -52,7 +55,7 @@ export function MediaLink({ to }: { to: string }) { {mediaIcon} - Media + {label} @@ -105,3 +108,23 @@ export const useMindMedia = (mind: string, rooms: readonly EstateRoom[]): MediaR if (typed) return { kind: 'room', room: { ...typed, name: 'Media' } }; return mediaRow(lookup.data, membership); }; + +/** The shared Commons room as the navigator sees it right now: undefined means no row. Dark unless fileZoneShare.enabled. */ +export const useCommons = (): EstateRoom | undefined => { + const mx = useMatrixClient(); + const joined = useAtomValue(allRoomsAtom); + const invited = useAtomValue(allInvitesAtom); + const enabled = !!useClientConfig().fileZoneShare?.enabled; + const server = mx.getDomain() ?? ''; + // Provisioning records no id for the Commons (only per-Mind zones under @rooms.file_zones): the alias is the one way in. + const lookup = useQuery({ + queryKey: ['commons-room', server], + queryFn: () => lookupZoneRoom(mx, commonsAlias(server), server), + staleTime: 60_000, + enabled, + }); + const membership = new Map(); + invited.forEach((id) => membership.set(id, 'invite')); + joined.forEach((id) => membership.set(id, 'join')); + return commonsRow(enabled, lookup.data, membership); +}; diff --git a/src/app/features/estate/mediaRoom.test.ts b/src/app/features/estate/mediaRoom.test.ts index 934caaae..45e912e0 100644 --- a/src/app/features/estate/mediaRoom.test.ts +++ b/src/app/features/estate/mediaRoom.test.ts @@ -1,9 +1,13 @@ import { describe, expect, it } from 'vitest'; import { + commonsAlias, + commonsRow, lookupMediaRoom, + lookupZoneRoom, mediaAlias, mediaRoomIdFromStewardships, mediaRow, + MediaLookup, typedMediaRoom, } from './mediaRoom'; @@ -132,3 +136,51 @@ describe('the Media row of a Mind', () => { expect(typedMediaRoom(rooms, () => false)).toBeUndefined(); }); }); + +describe('the Commons row', () => { + const none = new Map(); + + it('is found by the alias #commons:', async () => { + const { mx, asked } = clientFor(async () => ({ room_id: '!c:gamecult.org' })); + const lookup = await lookupZoneRoom(mx, commonsAlias('gamecult.org'), 'gamecult.org'); + expect(asked).toEqual(['#commons:gamecult.org']); + expect(commonsRow(true, lookup, new Map([['!c:gamecult.org', 'join']]))).toMatchObject({ + roomId: '!c:gamecult.org', + name: 'Commons', + state: 'joined', + }); + }); + + it('shows no row when the room is absent, the lookup failed or is still out', async () => { + const missing = await lookupZoneRoom( + clientFor(async () => { + throw notFound; + }).mx, + commonsAlias('gamecult.org'), + 'gamecult.org' + ); + const failed = await lookupZoneRoom( + clientFor(async () => { + throw new Error('down'); + }).mx, + commonsAlias('gamecult.org'), + 'gamecult.org' + ); + expect(commonsRow(true, missing, none)).toBeUndefined(); + expect(commonsRow(true, failed, none)).toBeUndefined(); + expect(commonsRow(true, undefined, none)).toBeUndefined(); + }); + + it('shows no row with the flag off, even for a found room', () => { + const found: MediaLookup = { found: true, roomId: '!c:gamecult.org', via: ['gamecult.org'] }; + expect(commonsRow(false, found, new Map([['!c:gamecult.org', 'join']]))).toBeUndefined(); + }); + + it('offers a join to a viewer who has not joined, and an accept to an invited one', () => { + const found: MediaLookup = { found: true, roomId: '!c:gamecult.org', via: ['gamecult.org'] }; + expect(commonsRow(true, found, none)?.state).toBe('joinable'); + expect(commonsRow(true, found, new Map([['!c:gamecult.org', 'invite']]))?.state).toBe( + 'invited' + ); + }); +}); diff --git a/src/app/features/estate/mediaRoom.ts b/src/app/features/estate/mediaRoom.ts index 5d1503b6..2e60fe3a 100644 --- a/src/app/features/estate/mediaRoom.ts +++ b/src/app/features/estate/mediaRoom.ts @@ -13,6 +13,9 @@ export const ROOMS_KEY = '@rooms'; export const mediaAlias = (mind: string, server: string): string => `#${mind}-files:${server}`; +/** The shared Commons room's alias (gamecult-ops synapse-accounts-hand-managed.py COMMONS_ALIAS). */ +export const commonsAlias = (server: string): string => `#commons:${server}`; + /** * The room id the stewardships state names for a Mind's media room, under `@rooms.file_zones[]`. * The state's mind-to-repos lists are not read here. @@ -46,16 +49,16 @@ export type MediaLookup = | { found: true; roomId: string; via: string[] } | { found: false; reason: 'unset' | 'error'; message?: string }; -/** Resolve a Mind's media room: a carried id if there is one, else the alias. A 404 means it is not set up. */ -export const lookupMediaRoom = async ( +/** Resolve a file-zone room (a Mind's media room, or Commons): a carried id if there is one, else the alias. A 404 means it is not set up. */ +export const lookupZoneRoom = async ( mx: MediaClient, - mind: string, + alias: string, server: string, carriedId?: string ): Promise => { if (carriedId) return { found: true, roomId: carriedId, via: [server] }; try { - const r = await mx.getRoomIdForAlias(mediaAlias(mind, server)); + const r = await mx.getRoomIdForAlias(alias); return { found: true, roomId: r.room_id, via: r.servers?.length ? r.servers : [server] }; } catch (e) { const err = e as { @@ -75,6 +78,14 @@ export const lookupMediaRoom = async ( } }; +/** Resolve a Mind's media room. */ +export const lookupMediaRoom = ( + mx: MediaClient, + mind: string, + server: string, + carriedId?: string +): Promise => lookupZoneRoom(mx, mediaAlias(mind, server), server, carriedId); + export type MediaRow = | { kind: 'checking' } | { kind: 'unset' } @@ -86,7 +97,8 @@ const MEMBERSHIP_STATE = { join: 'joined', invite: 'invited', none: 'joinable' } /** What the Media row shows: the lookup result joined to the user's own membership. */ export const mediaRow = ( lookup: MediaLookup | undefined, - membership: ReadonlyMap + membership: ReadonlyMap, + name = 'Media' ): MediaRow => { if (!lookup) return { kind: 'checking' }; if (!lookup.found) { @@ -99,7 +111,7 @@ export const mediaRow = ( kind: 'room', room: { roomId: lookup.roomId, - name: 'Media', + name, state: MEMBERSHIP_STATE[m ?? 'none'], via: lookup.via, parentId: null, @@ -107,3 +119,18 @@ export const mediaRow = ( }, }; }; + +/** + * The Commons row: the shared room, or nothing. Off with the share flag; not set up, still looking and a failed lookup + * show no row (the room is shared furniture, not a per-Mind promise like Media). A found room is joined, invited or + * joinable, as for Media. + */ +export const commonsRow = ( + enabled: boolean, + lookup: MediaLookup | undefined, + membership: ReadonlyMap +): EstateRoom | undefined => { + if (!enabled) return undefined; + const row = mediaRow(lookup, membership, 'Commons'); + return row.kind === 'room' ? row.room : undefined; +}; diff --git a/src/app/features/scene/BackgroundScene.tsx b/src/app/features/scene/BackgroundScene.tsx index c447b4f0..54d48f08 100644 --- a/src/app/features/scene/BackgroundScene.tsx +++ b/src/app/features/scene/BackgroundScene.tsx @@ -1,55 +1,59 @@ -import React, { useEffect, useMemo, useRef } from 'react'; +import React, { useEffect, useRef } from 'react'; import { useClientConfig } from '../../hooks/useClientConfig'; import { getFallbackSession } from '../../state/sessions'; import { mountBackgroundScene } from './host'; +import { setSceneDrawn } from './sceneDrawn'; +import { SceneViewHost } from './SceneViewHost'; import { readCapabilities, resolveTier } from './tier'; -import { getSceneStyleOverride } from './sceneStyle'; import './sceneShell.css'; import './sceneButtons.css'; -/** Set on while a scene runs, so signed-out screens can let it show through. */ -export const SCENE_ACTIVE_ATTRIBUTE = 'data-scene'; - /** * The one host for the background scene, mounted once at the app root. Fixed behind everything * (z-index -1 sits above the body's background and below all normal content; the signed-out * screens and the signed-in shell, see sceneShell.css.ts, are clear so the scene shows through). The ridge scene * draws its layers into this wrapper beside the canvas, so the wrapper is the positioned box. - * Tier 'off' renders nothing and loads nothing. + * Tier 'off' renders no scene and loads none; the scene view's host is here too, since the view is an overlay over this scene. */ export function BackgroundScene() { - const configured = useClientConfig().backgroundScene; - const config = useMemo(() => { - const style = getSceneStyleOverride(); - return configured && style ? { ...configured, style } : configured; - }, [configured]); + const config = useClientConfig().backgroundScene; const enabled = resolveTier(config, readCapabilities(navigator)) !== 'off'; const canvasRef = useRef(null); useEffect(() => { const canvas = canvasRef.current; if (!enabled || !canvas) return undefined; - const root = document.documentElement; const dispose = mountBackgroundScene(config, readCapabilities(navigator), canvas, { loggedIn: !!getFallbackSession(), - onActive: () => root.setAttribute(SCENE_ACTIVE_ATTRIBUTE, ''), - onInactive: () => root.removeAttribute(SCENE_ACTIVE_ATTRIBUTE), + onActive: (sky) => setSceneDrawn(true, sky), + onInactive: () => setSceneDrawn(false), // eslint-disable-next-line no-console onFail: (e) => console.warn('Background scene unavailable:', e), }); return () => { dispose(); - root.removeAttribute(SCENE_ACTIVE_ATTRIBUTE); + setSceneDrawn(false); }; }, [config, enabled]); - if (!enabled) return null; return ( -
- -
+ <> + {enabled && ( + + )} + + ); } diff --git a/src/app/features/scene/README.md b/src/app/features/scene/README.md index 45fec5cd..549510b4 100644 --- a/src/app/features/scene/README.md +++ b/src/app/features/scene/README.md @@ -1,40 +1,49 @@ # Background scene -**Default: the ridge scene** (`ridge/`), no WebGL. `startBackgroundScene` runs it unless the client +**Default: the ridge scene** (`ridge/`): no per-frame WebGL (the baked cards are lit once per scene build, in a WebGL2 context that is released after). `startBackgroundScene` runs it unless the client config says `backgroundScene.style: 'raymarch'`; the tier flag still defaults to `off`, and null still means "keep the CSS ground". Everything below this section describes the opt-in ray-march scene. -- `ridge/Ridge.ts` `createRidgeScene({ canvas, tier, probe?, onProbe?, onBake?, sky? })` returns `{ login, dispose }` or - null (tier `off`, no 2D context). Each of four ridge layers is a function of world-x (`ridge/ridgeWorld.ts` `profile`: - ridged multifractal value noise, each octave folded at its crest and weighted by the previous one, domain-warped; one - function, a parameter row per layer; nothing repeats). World-x is baked in chunks (1.2 viewport widths, integer pixels) - onto plain 2D canvases over a baked sky gradient on the host canvas. Per layer a track holds three chunk canvases: two - the window can reach and one ahead. The first view bakes only the first chunk of each layer; the others are baked in - tasks of about 6 ms (`setTimeout`; a chunk is baked, put on a canvas with its in-scatter, and blurred in column bands, each sized from the last band's time). Per frame the only motion is the - compositor sliding the track with a CSS transform (a Web Animation of `translate3d`, one chunk long, `fill: forwards`, - 150-420 s per viewport width, farther is slower); when it finishes the chunks move one slot left and the track restarts - at 0 in the same task (no jump), and the canvas that left is baked with the next stretch of world. A second animation - sways the whole rig (up to 5% of the width sideways, 3% of the height down, 150 s loop): the slow yaw and pitch. - No script runs per frame. The host canvas and the layers' parent must be positioned and the canvas should fill the parent. -- `ridge/ridgeBake.ts` is the pixel function (pure, no DOM): per column the crest's slope gives a normal, lit against the - sun (`sunDirection`: x = 0.9 sin(2 pi \* `sunAzimuth`), so the sun is toward +x for azimuth 0 to 0.5, strongest at 0.25, toward -x for 0.5 to 1; with no `sunAzimuth` the face lighting falls back to 0.3 and the in-scatter is off); the face under it has a light-to-haze gradient, erosion - streaks (a folded noise at gully width, darker with steepness) and a lit rim on the crest. Contrast scales with - `transmittance`; the base colour, haze and blur are the aerial perspective below, not redone. -- Paused when the tab is hidden; under `prefers-reduced-motion` the layers are painted but never played. - `tier: 'still'` flattens sky and layers into the host canvas at once and leaves no extra elements. +- `ridge/Ridge.ts` `createRidgeScene({ canvas, tier, probe?, onProbe?, sky?, backdrop? })` returns `{ login, dispose }` or + null (tier `off`, no 2D context). It paints the sky (`ridge/physicalSky.ts`, from the `SkyColours` the host passes) into a sky plate (`ridge/skyTurn.ts`): one element over the host + canvas, the viewport's width plus its slack of sky each side (20 degrees, more as the turn speeds up: the margin of the speed in force over a tick and 2 s of lateness, and 14 degrees of travel), centred on the heading `heading.ts` owns, holding the sky with the real stars, the moon and the lines baked into it and a + twinkle canvas for the swinging stars (`ridge/stars.ts`) over it. The sky is at infinity, so one animation slides the plate by the heading's turn at the cards' px per degree, on the + same keyframes as the cards; a residency tick or a reissue paints a new plate about the heading once it is within that margin of the plate's edge (or the speed asks for more slack) and swaps it in the same tick, + keyed from the clock after the paint (the same sky at the same screen place, so nothing moves; the twinkle schedule runs over the catalogue, so a swap keeps which stars swing; the plate's backing store is capped at 3 Mpx, the pixel ratio lowering before the plate shrinks). Then come the lit ridge + cards (below) and, when it rains, tiled rain streaks slid down on the compositor (`ridge/rain.ts`). A sky with no physical model is a gradient in the host canvas. + With no cards (the load failed) the scene shows the sky, stars and weather only, the plate facing the place's rest azimuth and staying. No script runs per frame except the twinkle, at most every 50 ms, and, only inside the scene view while a pointer is down, the pointer events that turn the heading (below). + The host canvas and its parent must be positioned and the parent must clip (the plate is wider than the viewport); the canvas should fill the parent. A resize rebuilds it; so does a sky change + (`index.ts`). +- Paused when the tab is hidden; under `prefers-reduced-motion` the rain is paused and the stars stay at base brightness. + `tier: 'still'` paints the sky (facing the heading its pose froze at) and stars into the host canvas and adds no plate, no rain and no loop. - Cadence guard: for the first 2 s after start (after 5 warm-up frames) rAF intervals are sampled; if their p95 is over - 33 ms the scene flattens to a still image (`ridge/probe.ts`) and stops. `?probe=1` (or `probe: true`) keeps sampling + 33 ms the scene settles to a still image (`ridge/probe.ts`) and stops. `?probe=1` (or `probe: true`) keeps sampling and shows `n / median / p95` in a corner readout. -- `ridge/skyColour.ts` `skyColours()` is the one place sky colours come from: a fixed dusk placeholder until Void's - `src/sky/sun.js` `light()` lands (PR #20); replace its body, keep the signature. -- Aerial perspective (`ridge/ridgeWorld.ts` `AERIAL`, `transmittance`, `layerColour`, `edgeBlur`, `scatterAlpha`) is applied - once while the layers are baked, from the `SkyColours` the one seam returns (`sunAzimuth` optional: omit it for no - in-scatter). Layer distance d = 1 - depth; transmittance T = exp(-1.6 d) (0.24 / 0.37 / 0.58 / 1.00 far to near); colour is - `T * ground + (1 - T) * haze`, then chroma drops by `0.5 (1 - T)`; the edge is blurred up to 2 px (canvas pixels at DPR 1, - via the 2D `filter`, skipped where unsupported, e.g. Safari); a faint warm in-scatter (at most 0.16 alpha) peaks at the - sun's azimuth in world-x (two incommensurate cosines, so not periodic). Nothing runs per frame. The in-scatter lobe is - painted into each chunk, so it drifts with the layer rather than staying fixed under the sun; that is a known - approximation until the sun is a real, fixed light. +- `ridge/skyColour.ts` `skyColours()` is the fallback three-stop palette (top, mid, horizon) a scene gets with no `sky` option; the host + passes `ridgeSkyFor` (skyForState.ts) instead. +- Ridge cards: `ridge/manifest.ts` `loadManifest` reads `${BASE_URL}public/ridge/index.json` (`skyPlace.ts` `resolvePlaceId` picks the entry: the viewer's choice if the index lists it, else config `backgroundScene.place` if listed, else + the index default), then the place's `manifest.json` (schema 3, written by `scripts/ridge-bake/export.py`; it is the one JSON + the backdrop reads): the whole 360 degree ring, K G-buffer cards nearest first, each cut into azimuth tiles (32 of 11.25 degrees) of a colour WebP (albedo, + straight alpha) and a geometry WebP (the normal as 'rt8', the log-distance, and the wall code R = G = 255 for the extruded face under a ridge), each tile + with the card's distance there; `camera.r_max_m` bounds the parallax offset over every angle of the camera on its circle and `camera.r_max_forward_m` with the camera on its heading alone. Schema 2 is refused with a message naming the stale deploy. `index.ts` + `prepare()` loads the manifest, anchors the heading (`ridge/heading.ts`) and, with the scene chunk, `ridge/Backdrop.ts` `createBackdrop`: `ensure(arc)` + asks for the files of the tiles of an arc of azimuth it does not hold a few at a time (6 requests, each with a timeout) and decodes them one tile at a time (no premultiply, no colour management), and `ridge/lightCards.ts` + `createLighter` lights each card of a tile in WebGL2 for the sky of this build (sun and ambient from the atmosphere in absolute azimuth, aerial perspective from the + geometry's distance, ink on occluding edges and creases, the sky's own display so terrain and sky share an exposure) into a 2D canvas of the tile's interior and one + overlap column each side. The backdrop holds the arc ahead and two tiles beyond and lets go of the rest; a tile that fails is absent and asked for again by the backdrop itself after a pause that doubles to a minute, for as long as the arc last asked for wants it (a still has no timer of its own), and a file the server answers 404 is not asked for again (the tile is drawn with the cards that came). A sky change is a + rebuild, so it makes a new lighter; nothing is lit per frame, and the host canvas is only ever asked for 2d. + `createRidgeScene({ backdrop })` stays synchronous (`prepare()` awaits the first arc), and a rebuild keeps the old scene up until the new one holds tiles, then swaps (a build a newer one supersedes is given up at once, its requests aborted; a rebuild has no failure end: with no tile it stays pending beside the scene that is up, its loader asking again, and replaces it the moment it holds one; only a build with no ridge up behind it, a first load or a rebuild over the sky alone, that ends with no tile is the sky alone). The page theme and ink follow the sky of the scene that is up (`sceneDrawn.ts` holds it, set by the door's `onActive`), never the band announced; the + pose survives it. The rig is one div of K boxes, one per card (farthest first; DOM order is paint order; no z-index, no fixed position, nothing outside the scene's + parent), each holding that card's resident tiles at their unwrapped azimuth. A card's pose (scale and shift) is derived by `view.ts` `cardPose` from its distance at + the heading (`ring.ts`), the viewer's offset and the camera's angle on its circle, as a camera on a circle round the bake centre sees it (ruling ridge-camera-on-circle; + the offset is signed and clamped by `offsetRange`, the one clamp, by the mode: the forward bound with the camera on its heading, the worst-case bound where it circles; the speed by `maxSpeed`, + what the baked resident count sustains, applied to the stored choice). `cameraState.ts` is the one owner of the viewer's mode, speed and offset in `ratatoskr.camera`; `heading.ts` owns the view's pose, the direction, the camera's angle over it and its offset, as one segment (module + state: the pose at a clock, the mode and speed in force and the ease to the pose the choices owe; any change of a choice, a hold, a bound or reduced motion starts a new segment from the pose it has at that clock, `poseAt(t)` is a pure function of it, and a mode pick eases the angle and the offset one after the other, 300 ms each, in the order that keeps every pose inside the bound; `cameraState.ts` hands it each change synchronously before its listeners and keeps no log; `view.ts` `offsetRange`, given to it by the scene, is the one clamp; angles are normalized into [0, 360) before each stretch so nothing grows with uptime; a manual `hold` sets the mode to still, so a rebuild or a reload keeps it). The motion is one `Element.animate` per card (transform only, a + keyframe each second for 30 s and every 50 ms while an ease runs, reissued at 80% and on any change; paused when the tab is hidden or motion is reduced, then constant); a 500 ms timer asks the backdrop for + the arc every pose of the next 30 s passes over (`view.ts` `sweepArc`, sampled four times a second, not its two ends) and mounts the tiles it has made. A still draws the sky and the tiles of the arc into the host canvas at the heading now. A failure + anywhere (404, a manifest that is not schema 3, no tile that will decode, no WebGL2, a lighting pass that throws) is the sky-only scene on `FALLBACK_VIEW`, + told to the host by the live scene alone, through `onPlanesFail` when the live scene has no cards and `onPlanesOk` when a later one has them (never from a stale + or disposed build); it is never `onCompileFail`. `vite.config.js` copies `public/ridge` into `dist/public/`. - `harness/scene/bundle.cjs ridge` builds a standalone page (`?tier=`, `?probe=1`). - Not yet measured on a phone: see the PR description. @@ -48,51 +57,42 @@ Integration (a canvas under the app, `startBackgroundScene`, `login()` when the are later cuts. This PR is the render core plus the contract the host needs: flag, tier, failure callbacks and the creature sizing rule. Nothing has drawn a creature. -## Terrain scene (`style: 'terrain'`): the baked sky +## Ridge scene: Vienna and the weather -`terrain/` draws a Phacelle-displaced grid under a sky read from Void's bake (`src/sky/baked.ts`, layout in -`src/sky/README.md`); nothing is vendored. `terrainSky.ts` reads each moment's `sun.{elevation_deg, azimuth_deg, -color_linear}`, `ambient_linear` and `horizon_hex`; `terrainScatter.ts` decodes `baked.scatter` and uploads `sky_view` as an -RGB16F 3D texture (the transmittance table stays on the CPU, for the sun's colour at an elevation the bake does not hold). -Both fragment shaders sample it: `SKY_FRAG` for the sky, `GRID_FRAG` for the haze, which is the sky's colour at the horizon in the -fragment's azimuth, so far ground fades into the sky behind it at dusk too. +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). -Page URL: `?sky=midnight|noonday` picks a bake; `?sun=&az=` puts the sun anywhere between them -(`skyAtSun`: baked transmittance for the sun's colour, ambient and horizon blended from the midnight bake to the noonday one as -the sun climbs from -8 to 25 degrees). `?sun=` wins over `?sky=`. +### The sky choice -Without WebGL2 (`createTerrainScene` returns null) the door mounts `terrain/TerrainSky2D.ts` on the same canvas: the sky alone, painted once on a -96 px wide 2D canvas from `skyColour` (the CPU twin of `SKY_FRAG`, same `?sky=` `?sun=` `?az=` choice via `chooseSky`), the star layer on -top when the sky is dark, nothing moving, no sun disc. Below the horizon the image continues in the horizon's colour. A canvas that already -holds a GL context gives no 2D one, so a GL failure after context creation (compile, framebuffer) still ends in the CSS ground. +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. -- Sky: `1 - exp(-SKY_EXPOSURE * radiance)` plus a night glow (the midnight horizon colour, `nightness` 1 below -4 degrees, 0 above 4), a - sun disc from the sun's colour, and a +-0.5/255 dither on the 8-bit output. The table is single scattering only (no ground bounce, - no multiple scattering), so the noon horizon is pale yellow-green and a sun just under the horizon colours the whole sky orange, - where the real one keeps a blue-violet zenith. Within `HORIZON_FLOOR` (1.5 degrees) of the horizon the sky takes one flat colour, - because the table dips toward the ground there and would draw a seam against the haze. -- Stars: faded by the sun's elevation, `starGain` 1 below -12 degrees (where the table goes dark), 0 above -6, smooth between; - the field is placed against the midnight gradient and no longer gated on the sky being dark. At a baked sky that is the same as - before (midnight shows, noonday does not). -- Changed numbers: haze colour (was the gradient's horizon stop; now the scattered sky), ambient (was the gradient's zenith stop - x `AMBIENT_GAIN` 0.25 x `NIGHT_LIFT` up to 4; now `ambient_linear` as baked, so midnight's fill is about 2.5 to 3.5 times darker than - the lifted one). `HAZE_K` (0.0004 per metre) is unchanged. - -## Ridge scene: Vienna, the real horizon 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 -(`ridge/vienna.ts`). Its farthest layer is the real horizon of that viewpoint, standing still under the sun: `ridge/viennaHorizon.json`, -baked by `scripts/bake-horizon.py` from Copernicus DEM GLO-30 (nine 1 degree tiles, about 380 MB, kept out of the repo). The file carries its -own `source` block with the dataset, tiles, licence and the attribution the licence requires. Its elevation range is 2.1 degrees, so the -layer draws the shape of the ring stretched to a fixed relief, not its scale. +`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 place `resolvePlaceId` names, the viewer's pick (`placeState.ts`, localStorage `ratatoskr.skyPlace`, per viewer) before the config's place before the index default (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, no tile that will 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 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 -"Datenquelle: GeoSphere Austria - https://data.hub.geosphere.at". Shape: `{fetched_at, observed_at, station, precip_mm_10min, humidity_pct, -glow_wm2, sunshine_s_10min, attribution}`, null for a missing measurement. A file fetched more than 30 minutes ago, or holding an observation more than 40 minutes old, or from another station, is a 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 at Vienna (Wien Hohe Warte), credit +"Datenquelle: GeoSphere Austria - https://data.hub.geosphere.at". Weather is per place: `ridge/weatherFeed.ts` `WEATHER_FEEDS` is the table of places that have an observation source (station, credit, dataset; today only `vienna`), and `loadWeather` draws a place without a row with a clear sky and does not fetch the file. A new place gets weather by adding its row there and a source in the refresher: no other edit; its credit follows from the row. Shape: `{fetched_at, observed_at, station, precip_mm_10min, humidity_pct, +glow_wm2, sunshine_s_10min, attribution}`, null for a missing measurement. A file fetched more than 30 minutes ago, or holding an observation more than 40 minutes old, or from another station than the place's feed's, is a clear sky. Rain is the gauge; cloud is an estimate from the global radiation against Haurwitz's clear-sky value, cross-checked by the sunshine duration, with the humidity as the fallback when the sun is low (`ridge/weatherFeed.ts`). The weather draws a cloud deck in the sky -(`ridge/clouds.ts`), thickens the layers' valley mist, and lays tiled rain streaks over everything (`ridge/rain.ts`, compositor-driven, none in a still). +(`ridge/clouds.ts`) and lays tiled rain streaks over the sky (`ridge/rain.ts`, compositor-driven, none in a still). + +## The scene view + +`sceneView.ts` owns whether the fullscreen view is open and which submenu is up (main-chunk safe). The entry is `SceneViewEntry` (`SceneViewEntry.tsx`), the icon button in the navigator and sign-in headers; it preloads the view's chunk on hover or focus. Opening pushes one history entry (so the browser Back button, Escape and Return are the same close), sets `html[data-scene-view]` and makes `#root` inert and hidden while it stays mounted, so the chat keeps its scroll and composer. `SceneViewHost.tsx` (mounted by `BackgroundScene.tsx`) loads `view/SceneView.tsx` as a chunk of its own and mounts it in `#portalContainer`; until it has loaded it stands Return and Escape there, a failed load closes the view, and once the view is gone it gives the focus back to the entry (`restoreEntryFocus`). + +The view is a full-viewport turning surface and, top left, a toolbar rail (Return, View, Time, Sky, Place; every icon `PhoneHit`) beside one panel at a time. View (`view/ViewSubmenu.tsx`): rotation mode, speed (bounded by `view.ts` `maxSpeed` for the mode) and the signed parallax offset (`offsetRange`), each written to `cameraState.ts` on release. Time (`view/TimeSubmenu.tsx`): the sky menu's moments and free moment, unchanged, to `skyState.ts` `setSkyChoice`. Sky (`view/SkySubmenu.tsx`): the constellation lines (`setConstellationLines`, the one setter). Place (`view/PlaceSubmenu.tsx`): a carousel of the baked places (`manifest.ts` `listPlaces`: the index's list, each named by its manifest; a card is the name and the place-local time of the moment the sky draws there, `skyMoment.ts` `momentFor` (the clock under Auto, ticking each minute; the picked moment otherwise); swipe, arrows or a tap pick, through `placeState.ts` `setPlaceChoice`; absent while the index lists one place) and every data credit (terrain, stars, lines, and the weather only for a place with a feed; ruling ridge-view-credits-home). A pick makes `index.ts` rebuild the scene, which re-resolves the place; the sky's place in the store (`skyState.ts` `getSkyPlace`, what the carousel, credits and ink read) is written only when that scene is made (`skyPlace.ts` `drawnView`), so a place whose tiles do not come stays pending while the canvas, the carousel and the store keep the place that is up (the loader's own backoff asks again), and a pick of it again gives the pending build up for a fresh one. Return calls `setCamera` with the chosen mode, which ends a hold. + +Manual turning (`view/turning.ts`) happens only inside the view: a one-finger or mouse horizontal drag turns the heading one for one with the far sky (`dh = -dx / (pxPerDegH x plane.scale)`), the arrows 5 degrees (Shift 15), a horizontal wheel or swipe one for one; each event calls `heading.hold`, which re-issues the rig, and the rotation stays held until a mode is picked or Return is pressed. Pitch is never turned. While a pointer is down the panel and rail fade. ## Entry points diff --git a/src/app/features/scene/SceneViewEntry.test.tsx b/src/app/features/scene/SceneViewEntry.test.tsx new file mode 100644 index 00000000..a7a4a9d6 --- /dev/null +++ b/src/app/features/scene/SceneViewEntry.test.tsx @@ -0,0 +1,18 @@ +import { describe, expect, it, vi } from 'vitest'; +import { SceneViewEntry } from './SceneViewEntry'; + +const offered = vi.hoisted(() => ({ value: true })); +vi.mock('../../hooks/useSceneView', () => ({ useSceneViewOffered: () => offered.value })); + +describe('the scene view entry', () => { + it('is offered with the scene on', () => { + offered.value = true; + expect((SceneViewEntry() as { props: Record }).props['aria-label']).toBe( + 'Scene view' + ); + }); + it('is not offered when the scene tier is off', () => { + offered.value = false; + expect(SceneViewEntry()).toBeNull(); + }); +}); diff --git a/src/app/features/scene/SceneViewEntry.tsx b/src/app/features/scene/SceneViewEntry.tsx new file mode 100644 index 00000000..941b01b3 --- /dev/null +++ b/src/app/features/scene/SceneViewEntry.tsx @@ -0,0 +1,31 @@ +import React from 'react'; +import { Icon, IconButton, Icons } from 'folds'; +import { PhoneHit } from '../../styles/PhoneHit.css'; +import { useSceneViewOffered } from '../../hooks/useSceneView'; +import { loadSceneView, openSceneView } from './sceneView'; + +/** + * The title-bar button that opens the scene view, the fullscreen view of the background scene with its own controls (sceneView.ts). A single button, not a + * row, so the bar still fits a 320 px phone beside the search button. The view's code loads when the button is hovered or focused. Not offered when the + * scene tier is off: there is no scene to look at. + */ +export function SceneViewEntry() { + const offered = useSceneViewOffered(); + if (!offered) return null; + const preload = () => { + loadSceneView().catch(() => undefined); // a failed chunk is asked for again when the view opens (SceneViewHost) + }; + return ( + + + + ); +} diff --git a/src/app/features/scene/SceneViewHost.test.tsx b/src/app/features/scene/SceneViewHost.test.tsx new file mode 100644 index 00000000..a322b01e --- /dev/null +++ b/src/app/features/scene/SceneViewHost.test.tsx @@ -0,0 +1,156 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { PhoneHit } from '../../styles/PhoneHit.css'; +import { SceneViewHost, SceneViewLoading } from './SceneViewHost'; + +// The hooks are held still (view/SceneView.test.tsx): the element tree is read, effects are kept and run by the test. +const held = vi.hoisted(() => ({ + effects: [] as Array<() => unknown>, + open: true, + offered: true, + view: undefined as unknown, + closed: 0, + restored: 0, + sets: [] as unknown[], + loads: [] as Array<(m: unknown) => void>, +})); +vi.mock('react', async (importOriginal) => { + const actual = await importOriginal(); + const useState = () => [held.view, (v: unknown) => held.sets.push(v)]; + const useEffect = (fn: () => unknown) => { + held.effects.push(fn); + }; + return { ...actual, default: { ...actual, useState, useEffect }, useState, useEffect }; +}); +vi.mock('react-dom', () => ({ createPortal: (node: unknown) => node })); +vi.mock('../../hooks/useSceneView', () => ({ + useSceneViewState: () => ({ open: held.open, submenu: undefined }), + useSceneViewOffered: () => held.offered, +})); +vi.mock('./sceneView', () => ({ + closeSceneView: () => { + held.closed += 1; + }, + restoreEntryFocus: () => { + held.restored += 1; + }, + loadSceneViewOrClose: () => new Promise((res) => held.loads.push(res)), +})); + +type El = { type?: unknown; props?: Record }; +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 []; +}; + +beforeEach(() => { + held.effects.length = 0; + held.open = true; + held.offered = true; + held.view = undefined; + held.closed = 0; + held.restored = 0; + held.sets.length = 0; + held.loads.length = 0; + vi.stubGlobal('document', { getElementById: () => ({}) }); +}); +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('the view while its code loads', () => { + it('shows a Return that closes the view, with the phone tap target', () => { + const ret = walk(SceneViewLoading()).find((e) => e.props?.['aria-label'] === 'Return'); + expect(String(ret?.props?.className)).toContain(PhoneHit); + (ret?.props?.onClick as () => void)(); + expect(held.closed).toBe(1); + }); + + it('closes on Escape, and takes its listener off', () => { + const on: Record void> = {}; + let off = 0; + vi.stubGlobal('window', { + addEventListener: (t: string, cb: (e: unknown) => void) => { + on[t] = cb; + }, + removeEventListener: () => { + off += 1; + }, + }); + SceneViewLoading(); + const cleanup = held.effects[0]() as () => void; + on.keydown({ key: 'a', stopPropagation: () => undefined }); + expect(held.closed).toBe(0); + on.keydown({ key: 'Escape', stopPropagation: () => undefined }); + expect(held.closed).toBe(1); + cleanup(); + expect(off).toBe(1); + }); + + it('the open host stands Return in the portal until the view is loaded', () => { + expect((SceneViewHost() as unknown as El).type).toBe(SceneViewLoading); + }); + + it('asks for the code when the view opens, and the failed load (which closes the view) is the loader, not the host', () => { + SceneViewHost(); + held.effects.forEach((run) => run()); + expect(held.loads).toHaveLength(1); + }); +}); + +describe('the host and the focus', () => { + it('gives the entry its focus once the view is closed, and never while it is open', () => { + SceneViewHost(); + held.effects.forEach((run) => run()); + expect(held.restored).toBe(0); + held.effects.length = 0; + held.open = false; + SceneViewHost(); + held.effects.forEach((run) => run()); + expect(held.restored).toBe(1); + }); +}); + +describe('the view code arriving', () => { + const run = () => { + SceneViewHost(); + return held.effects.map((e) => e()).filter((c): c is () => void => typeof c === 'function'); + }; + it('is mounted when it arrives while the view is open', async () => { + const View = () => null; + run(); + held.loads[0]({ default: View }); + await Promise.resolve(); + await Promise.resolve(); + expect(held.sets).toEqual([{ View }]); + }); + it('is dropped when it arrives after the view closed again', async () => { + const cleanups = run(); + cleanups.forEach((c) => c()); + held.loads[0]({ default: () => null }); + await Promise.resolve(); + await Promise.resolve(); + expect(held.sets).toEqual([]); + }); +}); + +describe('the host', () => { + it('renders nothing and loads nothing while the view is closed', () => { + held.open = false; + expect(SceneViewHost()).toBeNull(); + held.effects.forEach((run) => run()); + expect(held.loads).toHaveLength(0); + expect(held.closed).toBe(0); + }); + + it('with the scene tier off an open view closes, shows nothing and loads nothing', () => { + held.offered = false; + expect(SceneViewHost()).toBeNull(); + held.effects.forEach((run) => run()); + expect(held.closed).toBe(1); + expect(held.loads).toHaveLength(0); + }); +}); diff --git a/src/app/features/scene/SceneViewHost.tsx b/src/app/features/scene/SceneViewHost.tsx new file mode 100644 index 00000000..ba299a25 --- /dev/null +++ b/src/app/features/scene/SceneViewHost.tsx @@ -0,0 +1,72 @@ +import React, { ComponentType, useEffect, useState } from 'react'; +import { createPortal } from 'react-dom'; +import { Icon, IconButton, Icons } from 'folds'; +import { PhoneHit } from '../../styles/PhoneHit.css'; +import { useSceneViewOffered, useSceneViewState } from '../../hooks/useSceneView'; +import { closeSceneView, loadSceneViewOrClose, restoreEntryFocus } from './sceneView'; +import * as css from './sceneShell.css'; + +/** + * What stands in the portal while the view's code loads: Return and Escape, so the view can be left before the rest of it is there. The app behind is hidden + * and inert already, so without this the screen is blank. + */ +export function SceneViewLoading() { + useEffect(() => { + const onKey = (evt: KeyboardEvent) => { + if (evt.key === 'Escape') { + evt.stopPropagation(); + closeSceneView(); + } + }; + window.addEventListener('keydown', onKey); + return () => window.removeEventListener('keydown', onKey); + }, []); + return ( + + + + ); +} + +/** + * The scene view (sceneView.ts) in the portal layer while it is open: over the scene, outside the app it hides. Its code is a chunk of its own: until it has + * loaded, `SceneViewLoading` is what is shown, and a failed load closes the view (`loadSceneViewOrClose`). The view is not offered with the scene tier off, so an + * open view that finds the tier off closes. + */ +export function SceneViewHost() { + const { open } = useSceneViewState(); + const offered = useSceneViewOffered(); + const [view, setView] = useState<{ View: ComponentType } | undefined>(); + const shown = open && offered; + + // The view is gone from the page (its focus trap with it) once `open` is false: only now can the entry take the focus and keep it. + useEffect(() => { + if (!open) restoreEntryFocus(); + }, [open]); + + useEffect(() => { + if (open && !offered) closeSceneView(); + }, [open, offered]); + + useEffect(() => { + if (!shown) return undefined; + let live = true; + loadSceneViewOrClose().then((m) => { + if (live && m) setView({ View: m.default }); + }); + return () => { + live = false; + }; + }, [shown]); + + const portal = document.getElementById('portalContainer'); + if (!shown || !portal) return null; + return createPortal(view ? : , portal); +} diff --git a/src/app/features/scene/SkyStateControl.tsx b/src/app/features/scene/SkyStateControl.tsx deleted file mode 100644 index ee973822..00000000 --- a/src/app/features/scene/SkyStateControl.tsx +++ /dev/null @@ -1,165 +0,0 @@ -import React, { MouseEventHandler, useState } from 'react'; -import { - Box, - config, - Icon, - IconButton, - Icons, - Menu, - MenuItem, - PopOut, - RectCords, - Text, -} from 'folds'; -import FocusTrap from 'focus-trap-react'; -import { stopPropagation } from '../../utils/keyboard'; -import { useSkyState } from '../../hooks/useSkyState'; -import { SKY_STATES, setSkyState, type SkyState } from './skyState'; -import { - HORIZON_CREDIT, - WEATHER_CREDIT, - WEATHER_CREDIT_URL, - WEATHER_DATASET, -} from './ridge/credits'; -import { useClientConfig } from '../../hooks/useClientConfig'; -import { - getSceneStyleOverride, - SERVED_SCENE_STYLES, - setSceneStyle, - type ServedSceneStyle, -} from './sceneStyle'; -import { PhoneHit } from '../../styles/PhoneHit.css'; - -const STYLE_LABEL: Record = { terrain: 'Terrain', ridge: 'Ridges' }; - -const LABEL: Record = { - auto: 'Auto', - day: 'Day', - dusk: 'Dusk', - night: 'Night', -}; - -/** - * One title-bar button that opens the four sky states. A single button, not a row, so the bar - * still fits a 320 px phone beside the search button; the menu items carry the state names. - */ -export function SkyStateControl() { - const state = useSkyState(); - const [cords, setCords] = useState(); - const backgroundScene = useClientConfig().backgroundScene; - const configuredStyle = backgroundScene?.style; - const sceneStyle: ServedSceneStyle = - getSceneStyleOverride() ?? (configuredStyle === 'terrain' ? 'terrain' : 'ridge'); - - const open: MouseEventHandler = (evt) => { - setCords(evt.currentTarget.getBoundingClientRect()); - }; - - return ( - setCords(undefined), - clickOutsideDeactivates: true, - isKeyForward: (evt: KeyboardEvent) => evt.key === 'ArrowDown', - isKeyBackward: (evt: KeyboardEvent) => evt.key === 'ArrowUp', - escapeDeactivates: stopPropagation, - }} - > - - - {SKY_STATES.map((s) => ( - { - setSkyState(s); - setCords(undefined); - }} - after={state === s ? : undefined} - > - - {LABEL[s]} - - - ))} - {backgroundScene && ( - <> - - Background - - {SERVED_SCENE_STYLES.map((st) => ( - { - setCords(undefined); - if (st !== sceneStyle) setSceneStyle(st); - }} - after={sceneStyle === st ? : undefined} - > - - {STYLE_LABEL[st]} - - - ))} - - )} - {backgroundScene && sceneStyle === 'ridge' && ( - - - Data - - - Datenquelle: GeoSphere Austria -{' '} - - {WEATHER_CREDIT_URL} - - . {WEATHER_DATASET}. - - - {HORIZON_CREDIT} - - - )} - - - - } - > - - - - - ); -} diff --git a/src/app/features/scene/cameraState.test.ts b/src/app/features/scene/cameraState.test.ts new file mode 100644 index 00000000..6bbb9f02 --- /dev/null +++ b/src/app/features/scene/cameraState.test.ts @@ -0,0 +1,154 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import * as camera from './cameraState'; +import { + bindOwner, + CAMERA_KEY, + DEFAULT_CAMERA, + effectiveMode, + getCamera, + holdCamera, + isHeld, + parseCamera, + resetCamera, + setCamera, + subscribe, +} from './cameraState'; + +const store = new Map(); +const reduced = { matches: false }; + +beforeEach(() => { + store.clear(); + reduced.matches = false; + resetCamera(); + vi.stubGlobal('localStorage', { + getItem: (k: string) => store.get(k) ?? null, + setItem: (k: string, v: string) => void store.set(k, v), + }); + vi.stubGlobal('window', { matchMedia: () => reduced }); +}); +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('the viewer camera', () => { + it('starts at the defaults: both, a turn in ten minutes, 200 m forward', () => { + expect(getCamera()).toEqual({ mode: 'both', speedDegPerS: 0.6, offsetM: 200 }); + expect(DEFAULT_CAMERA).toEqual(getCamera()); + }); + + it('starts still under reduced motion, and a stored choice outranks that', () => { + reduced.matches = true; + expect(getCamera().mode).toBe('still'); + resetCamera(); + store.set(CAMERA_KEY, JSON.stringify({ mode: 'offset', speedDegPerS: 1, offsetM: -30 })); + expect(getCamera()).toEqual({ mode: 'offset', speedDegPerS: 1, offsetM: -30 }); + }); + + it('a reduced-motion visit starts still with the default speed and offset kept, which apply once a moving mode is chosen (ruling ridge-reduced-motion-starts-still)', () => { + reduced.matches = true; + expect(getCamera()).toEqual({ mode: 'still', speedDegPerS: 0.6, offsetM: 200 }); + expect(effectiveMode()).toBe('still'); + setCamera({ mode: 'both' }); + expect(getCamera()).toEqual({ mode: 'both', speedDegPerS: 0.6, offsetM: 200 }); + expect(effectiveMode()).toBe('both'); + }); + + it('keeps each change per viewer, and tells listeners only of a change', () => { + const cb = vi.fn(); + subscribe(cb); + setCamera({ offsetM: 50 }); + expect(JSON.parse(store.get(CAMERA_KEY) as string)).toEqual({ ...DEFAULT_CAMERA, offsetM: 50 }); + setCamera({ offsetM: 50 }); + setCamera({ mode: 'both' }); + expect(cb).toHaveBeenCalledTimes(1); + setCamera({ mode: 'offset', speedDegPerS: 2 }); + expect(cb).toHaveBeenCalledTimes(2); + expect(getCamera()).toEqual({ mode: 'offset', speedDegPerS: 2, offsetM: 50 }); + }); + + it('tells listeners what the choice was and the clock it changed at, so the kinematics can be taken to that moment', () => { + const cb = vi.fn(); + subscribe(cb); + setCamera({ mode: 'offset' }, 1234); + expect(cb).toHaveBeenCalledWith({ ...DEFAULT_CAMERA, mode: 'offset' }, DEFAULT_CAMERA, 1234, false); + }); + + it('hands a change to the owner before any listener, at its clock, whenever the listeners registered, and keeps no log of it', () => { + const order: string[] = []; + subscribe(() => order.push('early')); + bindOwner((at) => order.push(`owner ${at}`)); + subscribe(() => order.push('late')); + setCamera({ offsetM: 5 }, 42); + holdCamera(43); + setCamera({ mode: 'both' }, 44); // picking a mode ends the hold + setCamera({ offsetM: 5 }, 45); // nothing changed + expect(order).toEqual(['owner 42', 'early', 'late', 'owner 43', 'early', 'late', 'owner 44', 'early', 'late']); + resetCamera(); // a reload of the choice does not unbind the owner: it outlives the scenes + setCamera({ offsetM: 9 }, 50); + expect(order.at(-1)).toBe('owner 50'); + expect(Object.keys(camera)).not.toContain('takeChanges'); + bindOwner(undefined); + }); + + it('a hold is session state: the mode in effect is still, the chosen mode is untouched and stored as chosen, and a reload does not hold', () => { + setCamera({ mode: 'offset', speedDegPerS: 2 }); + const cb = vi.fn(); + subscribe(cb); + holdCamera(5); + expect(isHeld()).toBe(true); + expect(effectiveMode()).toBe('still'); + expect(getCamera().mode).toBe('offset'); + expect(JSON.parse(store.get(CAMERA_KEY) as string).mode).toBe('offset'); + expect(cb).toHaveBeenCalledTimes(1); + holdCamera(6); // already held + expect(cb).toHaveBeenCalledTimes(1); + setCamera({ offsetM: 10 }); // a slider does not end a hold + expect(isHeld()).toBe(true); + resetCamera(); // a reload + expect(isHeld()).toBe(false); + expect(effectiveMode()).toBe('offset'); + }); + + it('picking a mode ends a hold, the one already chosen included, and is heard as a change though nothing stored moved', () => { + setCamera({ mode: 'both' }); + holdCamera(1); + const cb = vi.fn(); + subscribe(cb); + setCamera({ mode: 'both' }, 9); + expect(isHeld()).toBe(false); + expect(effectiveMode()).toBe('both'); + expect(cb).toHaveBeenCalledTimes(1); + expect(cb.mock.calls[0][2]).toBe(9); + expect(cb.mock.calls[0][3]).toBe(true); // it was held until this change + setCamera({ mode: 'both' }, 10); // nothing held, nothing changed + expect(cb).toHaveBeenCalledTimes(1); + }); + + it('ignores a stored value that is not a choice, and a change that is not one', () => { + store.set(CAMERA_KEY, '{"mode":"spin","speedDegPerS":1,"offsetM":0}'); + expect(getCamera()).toEqual(DEFAULT_CAMERA); + store.set(CAMERA_KEY, 'not json'); + resetCamera(); + expect(getCamera()).toEqual(DEFAULT_CAMERA); + setCamera({ speedDegPerS: Number.NaN }); + setCamera({ mode: 'spin' as never }); + expect(getCamera()).toEqual(DEFAULT_CAMERA); + expect(parseCamera({ mode: 'still', speedDegPerS: Infinity, offsetM: 0 })).toBeUndefined(); + }); + + it('holds the choice for the page load when storage refuses', () => { + vi.stubGlobal('localStorage', { + getItem: () => { + throw new Error('blocked'); + }, + setItem: () => { + throw new Error('blocked'); + }, + }); + resetCamera(); + expect(getCamera()).toEqual(DEFAULT_CAMERA); + setCamera({ offsetM: -10 }); + expect(getCamera().offsetM).toBe(-10); + }); +}); diff --git a/src/app/features/scene/cameraState.ts b/src/app/features/scene/cameraState.ts new file mode 100644 index 00000000..8d09216b --- /dev/null +++ b/src/app/features/scene/cameraState.ts @@ -0,0 +1,130 @@ +// How the viewer wants the ridge camera to move: the rotation mode, the speed and the parallax offset, per viewer in localStorage. The one owner of the +// chosen mode, speed and offset (persisted, never rewritten by anything but the viewer: the clamp on the offset, `ridge/view.ts` `offsetRange`, and the bound +// on the speed, `maxSpeed`, are derived from them at read for the mode and the bake in force) and of the hold: a manual turn (`ridge/heading.ts` `hold`) makes the +// mode in effect 'still' until the viewer picks a mode, the one already chosen included. The hold is session state: a rebuild keeps it, a reload does not +// (a reload is a Return). `ridge/heading.ts` integrates the view direction over the mode in effect. Main-chunk safe (no ridge code is imported at runtime), as placeState and skyState are. +import type { RotationMode } from './ridge/heading'; + +export const CAMERA_KEY = 'ratatoskr.camera'; + +export interface CameraChoice { + mode: RotationMode; + /** Degrees per second the view (or the camera on its circle) turns at. */ + speedDegPerS: number; + /** The camera's offset from the bake centre in metres, forward positive; a scene clamps it to the place's range. */ + offsetM: number; +} + +/** + * What a first visit sees (question ridge-view-defaults, provisional): a turn in ten minutes with the camera 200 m forward, view direction and camera + * together (ruling ridge-scene-view-fullscreen). A visit that asks for reduced motion starts with nothing turning. + */ +export const DEFAULT_CAMERA: CameraChoice = { mode: 'both', speedDegPerS: 0.6, offsetM: 200 }; + +const MODES: readonly RotationMode[] = ['still', 'offset', 'both']; + +/** A stored value as a choice, or undefined when it is not one (an unknown mode, a speed or offset that is not a finite number). */ +export function parseCamera(raw: unknown): CameraChoice | undefined { + if (typeof raw !== 'object' || raw === null) return undefined; + const c = raw as Record; + if ( + !MODES.includes(c.mode as RotationMode) || + typeof c.speedDegPerS !== 'number' || + !Number.isFinite(c.speedDegPerS) || + typeof c.offsetM !== 'number' || + !Number.isFinite(c.offsetM) + ) { + return undefined; + } + return { mode: c.mode as RotationMode, speedDegPerS: c.speedDegPerS, offsetM: c.offsetM }; +} + +const reducedMotion = (): boolean => { + try { + return window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches === true; + } catch { + return false; + } +}; + +let current: CameraChoice | undefined; +/** Hears a change of the choice or of the hold: the choice now, what it was, the clock, and whether the view was held before. */ +type Listener = (next: CameraChoice, prev: CameraChoice, at: number, wasHeld: boolean) => void; +let held = false; +const listeners = new Set(); +/** + * The one reader that must have taken a change before anyone else hears of it: the heading owner (`ridge/heading.ts`), which starts a new segment of the view's + * motion at the clock `at`. Called synchronously by the change, before every listener, so no order of registration can put a listener ahead of it, and nothing is + * queued. Cleared by nothing: the owner outlives the scenes and the choice. + */ +let owner: ((at: number) => void) | undefined; +export const bindOwner = (cb: ((at: number) => void) | undefined): void => { + owner = cb; +}; +const clock = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now()); + +function load(): CameraChoice { + try { + const stored = localStorage.getItem(CAMERA_KEY); + const parsed = stored === null ? undefined : parseCamera(JSON.parse(stored)); + if (parsed) return parsed; + } catch { + // Storage is unreadable (private mode, bad JSON): the defaults hold for this page load. + } + return reducedMotion() ? { ...DEFAULT_CAMERA, mode: 'still' } : { ...DEFAULT_CAMERA }; +} + +export const getCamera = (): CameraChoice => { + current ??= load(); + return current; +}; + +/** Change any of the three, at the clock `at` (ms, `performance.now()` by default); listeners hear it, with what it was and `at`, only when something moved. */ +export function setCamera(change: Partial, at: number = clock()): void { + const next = parseCamera({ ...getCamera(), ...change }); + if (!next) return; + const prev = getCamera(); + const wasHeld = held; + // Picking a mode, the one already chosen included, ends a hold: it is a change whenever a hold is on. + const resumes = wasHeld && change.mode !== undefined; + const same = next.mode === prev.mode && next.speedDegPerS === prev.speedDegPerS && next.offsetM === prev.offsetM; + if (same && !resumes) return; + current = next; + if (resumes) held = false; + if (!same) { + try { + localStorage.setItem(CAMERA_KEY, JSON.stringify(next)); + } catch { + // Storage is refused: the choice holds for this page load only. + } + } + owner?.(at); + [...listeners].forEach((cb) => cb(next, prev, at, wasHeld)); +} + +/** A manual turn is on: the mode in effect is 'still' whatever the viewer chose. Not stored. */ +export const isHeld = (): boolean => held; + +/** The mode in effect: the viewer's choice, 'still' while the view is held. */ +export const effectiveMode = (): RotationMode => (held ? 'still' : getCamera().mode); + +/** Take the view by hand: hold it. Listeners hear it only when it was not held already. */ +export function holdCamera(at: number = clock()): void { + if (held) return; + held = true; + const cam = getCamera(); + owner?.(at); + [...listeners].forEach((cb) => cb(cam, cam, at, false)); +} + +export function subscribe(cb: Listener): () => void { + listeners.add(cb); + return () => listeners.delete(cb); +} + +/** For tests: forget what was read, so the next read starts from storage again. */ +export function resetCamera(): void { + current = undefined; + held = false; + listeners.clear(); +} diff --git a/src/app/features/scene/host.test.ts b/src/app/features/scene/host.test.ts index b987d0cc..d5514d52 100644 --- a/src/app/features/scene/host.test.ts +++ b/src/app/features/scene/host.test.ts @@ -44,6 +44,14 @@ describe('mountBackgroundScene', () => { expect(scene.login).not.toHaveBeenCalled(); }); + it('tells onActive the sky the started scene draws', async () => { + startBackgroundScene.mockResolvedValue({ ...fakeScene(), drawnSky: 'dusk' }); + const onActive = vi.fn(); + mountBackgroundScene(config, caps, canvas, { loggedIn: false, onActive }); + await flush(); + expect(onActive).toHaveBeenCalledWith('dusk'); + }); + it('disposes the scene on unmount, once', async () => { const scene = fakeScene(); startBackgroundScene.mockResolvedValue(scene); diff --git a/src/app/features/scene/host.ts b/src/app/features/scene/host.ts index 9a31c812..fccba78f 100644 --- a/src/app/features/scene/host.ts +++ b/src/app/features/scene/host.ts @@ -1,12 +1,13 @@ import { startBackgroundScene } from './index'; -import type { Scene } from './index'; +import type { StartedScene } from './index'; +import type { FixedSkyState } from './ridge/skyMoment'; import type { BackgroundSceneConfig, Capabilities } from './tier'; export type HostOptions = { /** A Matrix session already exists, so the scene starts past its login moment. */ loggedIn: boolean; - /** The scene is running: the host may now let it show through. Not called when there is none. */ - onActive?: () => void; + /** The scene is running: the host may now let it show through, over the sky it draws. Not called when there is none. */ + onActive?: (sky?: FixedSkyState) => void; /** The scene stopped because its GL context was lost: put the CSS ground back until it restores. */ onInactive?: () => void; /** A shader failed to compile, the chunk failed to load, or starting threw. The CSS ground stays. */ @@ -30,7 +31,7 @@ export function mountBackgroundScene( { loggedIn, onActive, onInactive, onFail }: HostOptions ): () => void { let cancelled = false; - let scene: Scene | null = null; + let scene: StartedScene | null = null; let generation = 0; const start = () => { @@ -57,7 +58,7 @@ export function mountBackgroundScene( } scene = started; if (!scene) return; - onActive?.(); + onActive?.(scene.drawnSky); if (loggedIn) scene.login(); }, (e) => { diff --git a/src/app/features/scene/index.test.ts b/src/app/features/scene/index.test.ts index c89fa3b0..cffadc0d 100644 --- a/src/app/features/scene/index.test.ts +++ b/src/app/features/scene/index.test.ts @@ -1,15 +1,29 @@ 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 { startBackgroundScene } from './index'; -import { setSkyClock, setSkyState } from './skyState'; +import { PREPARE_DEADLINE_MS, startBackgroundScene } from './index'; +import { getResolvedSkyState, getSkyPlace, setConstellationLines, setSkyChoice, setSkyClock, setSkyPlace, subscribe } from './skyState'; +import { skyBand } from './ridge/skyMoment'; +import type { SkyChoice } from './ridge/skyMoment'; import { ridgeSkyFor } from './skyForState'; +import { forgetManifests } from './ridge/manifest'; +import { wireIndex, wireManifest } from './ridge/manifest.fixture'; +import { FALLBACK_VIEW, HFOV_MAX_DEG, maxSpeed } from './ridge/view'; +import { forgetPlaceChoice, setPlaceChoice } from './placeState'; +import { hold, poseAt, resetHeading } from './ridge/heading'; +import { resetCamera, setCamera } from './cameraState'; +import { sunAt } from './ridge/sunAt'; +import { ridgeWeather } from './ridge/weather'; +import { creditLine, parseWeatherFile, WEATHER_FEEDS, weatherFromFile } from './ridge/weatherFeed'; -const { createRidgeScene, createScene } = vi.hoisted(() => ({ +const { createRidgeScene, createScene, createBackdrop } = vi.hoisted(() => ({ createRidgeScene: vi.fn(), createScene: vi.fn(), + createBackdrop: vi.fn(), })); vi.mock('./ridge/Ridge', () => ({ createRidgeScene })); +// Decoding and lighting are the cards' own tests' (Backdrop.test.ts, lightCards.test.ts); here the door sees a backdrop whose first arc it can hold, fail and count. +vi.mock('./ridge/Backdrop', () => ({ createBackdrop })); vi.mock('./Scene', () => ({ createScene })); // The physical sky is baked per call (tens of ms: atmosphere LUTs) and the clock here is fixed, so a state always // draws the same sky. Baking once per state keeps the 21-offset sweep under the default timeout when the machine is @@ -20,13 +34,20 @@ vi.mock('./skyForState', async (importOriginal) => { return { ...actual, ridgeSkyFor: (...args: Parameters) => { - if (args.length !== 1) return actual.ridgeSkyFor(...args); - if (!baked.has(args[0])) baked.set(args[0], actual.ridgeSkyFor(args[0])); - return baked.get(args[0]) as ReturnType; + const [state, view] = args; + // 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 = `${JSON.stringify(state)}@${JSON.stringify(view.place)}`; + if (!baked.has(key)) baked.set(key, actual.ridgeSkyFor(...args)); + return baked.get(key) as ReturnType; }, }; }); +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 config = { tier: 'low' as const }; const caps = { hardwareConcurrency: 8 }; @@ -40,20 +61,77 @@ const microtasks = (n: number) => (p) => p.then(() => undefined), Promise.resolve() ); +/** A `createBackdrop` whose first `ensure` waits on `ctl.hold` (queueing its settle in `ctl.pending`), then makes tiles or, with `ctl.fail` as it stood when asked, none. `ctl.calls` is the sky each backdrop was lit for; `ctl.made` the backdrops. */ +const loader = () => { + const ctl = { + pending: [] as Array<() => void>, + hold: false, + fail: false, + calls: [] as any[], + made: [] as any[], + /** The loader's retry succeeds: every backdrop that was asked while `fail` was set now holds a tile, and tells whoever listens. */ + arrive: () => undefined as void, + }; + const heard = new Set<() => void>(); + ctl.arrive = () => { + arrived = true; + [...heard].forEach((cb) => cb()); + }; + let arrived = false; + createBackdrop.mockImplementation((manifest: unknown, physical: unknown) => { + const fails = ctl.fail; // the outcome belongs to the request, whenever it settles + let made = false; + const bd = { + manifest, + dispose: vi.fn(), + litTiles: () => (made && (!fails || arrived) ? [{ tile: 0, card: 0, canvas: {} }] : []), + onTile: vi.fn((cb: () => void) => (heard.add(cb), () => void heard.delete(cb))), + ensure: vi.fn( + () => + new Promise((resolve) => { + const settle = () => { + made = true; + ctl.calls.push(physical); + resolve(); + }; + if (ctl.hold) ctl.pending.push(settle); + else settle(); + }) + ), + }; + ctl.made.push(bd); + return bd; + }); + return { + ctl, + release: async () => { + ctl.hold = false; + ctl.pending.splice(0).forEach((s) => s()); + await flush(); + }, + }; +}; const fakeScene = () => ({ login: vi.fn(), dispose: vi.fn() }); const hex = (c: readonly number[]) => `#${c.map((v) => v.toString(16).padStart(2, '0')).join('')}`; beforeEach(() => { - vi.stubGlobal('localStorage', { getItem: () => null, setItem: () => undefined }); + vi.stubGlobal('localStorage', { + getItem: () => null, + setItem: () => undefined, + removeItem: () => undefined, + }); // Local midnight: 'auto' resolves to night. - setSkyClock(() => atStandardTime(0, 0)); - setSkyState('auto'); + setSkyClock(() => atSolarTime(0, 0)); + setSkyChoice(AUTO); + setSkyPlace(FALLBACK_VIEW.place); createRidgeScene.mockReset(); createScene.mockReset(); + createBackdrop.mockReset(); + forgetPlaceChoice(); }); afterEach(() => { setSkyClock(); - setSkyState('auto'); + setSkyChoice(AUTO); vi.unstubAllGlobals(); }); @@ -62,26 +140,33 @@ describe('startBackgroundScene follows the sky state', () => { createRidgeScene.mockReturnValue(fakeScene()); const scene = await startBackgroundScene(config, caps, { canvas }); expect(createRidgeScene).toHaveBeenCalledOnce(); - expect(hex(createRidgeScene.mock.calls[0][0].sky.top)).toBe(hex(ridgeSkyFor('night').top)); + expect(hex(createRidgeScene.mock.calls[0][0].sky.top)).toBe( + hex(ridgeSkyFor(AUTO, FALLBACK_VIEW).top) + ); scene?.dispose(); }); - it('does not rebuild when auto is replaced by the explicit state it already resolves to', async () => { - const a = fakeScene(); - createRidgeScene.mockReturnValueOnce(a); + 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, b] = [fakeScene(), fakeScene()]; + createRidgeScene.mockReturnValueOnce(a).mockReturnValueOnce(b); const scene = await startBackgroundScene(config, caps, { canvas }); - setSkyState('night'); + setSkyChoice(NIGHT); await flush(); - expect(a.dispose).not.toHaveBeenCalled(); - expect(createRidgeScene).toHaveBeenCalledOnce(); + expect(a.dispose).toHaveBeenCalledOnce(); + expect(createRidgeScene).toHaveBeenCalledTimes(2); + setSkyChoice(NIGHT); + await flush(); + expect(createRidgeScene).toHaveBeenCalledTimes(2); scene?.dispose(); }); it('starts on the stored state', async () => { - setSkyState('night'); + setSkyChoice(NIGHT); createRidgeScene.mockReturnValue(fakeScene()); const scene = await startBackgroundScene(config, caps, { canvas }); - expect(hex(createRidgeScene.mock.calls[0][0].sky.top)).toBe(hex(ridgeSkyFor('night').top)); + expect(hex(createRidgeScene.mock.calls[0][0].sky.top)).toBe( + hex(ridgeSkyFor(NIGHT, FALLBACK_VIEW).top) + ); scene?.dispose(); }); @@ -90,10 +175,12 @@ describe('startBackgroundScene follows the sky state', () => { const second = fakeScene(); createRidgeScene.mockReturnValueOnce(first).mockReturnValueOnce(second); const scene = await startBackgroundScene(config, caps, { canvas }); - setSkyState('day'); + setSkyChoice(NOON); await flush(); expect(first.dispose).toHaveBeenCalledOnce(); - expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe(hex(ridgeSkyFor('day').top)); + expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe( + hex(ridgeSkyFor(NOON, FALLBACK_VIEW).top) + ); scene?.dispose(); expect(second.dispose).toHaveBeenCalledOnce(); }); @@ -102,11 +189,13 @@ describe('startBackgroundScene follows the sky state', () => { const [a, b] = [fakeScene(), fakeScene()]; createRidgeScene.mockReturnValueOnce(a).mockReturnValueOnce(b); const started = startBackgroundScene(config, caps, { canvas }); - setSkyState('day'); + setSkyChoice(NOON); const scene = await started; await flush(); expect(createRidgeScene).toHaveBeenCalledTimes(2); - expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe(hex(ridgeSkyFor('day').top)); + expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe( + hex(ridgeSkyFor(NOON, FALLBACK_VIEW).top) + ); expect(a.dispose).toHaveBeenCalledOnce(); scene?.dispose(); expect(b.dispose).toHaveBeenCalledOnce(); @@ -116,12 +205,12 @@ describe('startBackgroundScene follows the sky state', () => { const [a, b, c] = [fakeScene(), fakeScene(), fakeScene()]; createRidgeScene.mockReturnValueOnce(a).mockReturnValueOnce(b).mockReturnValueOnce(c); const scene = await startBackgroundScene(config, caps, { canvas }); - setSkyState('day'); + setSkyChoice(NOON); await flush(); expect(b.login).not.toHaveBeenCalled(); scene?.login(); expect(b.login).toHaveBeenCalledOnce(); - setSkyState('dusk'); + setSkyChoice(DUSK); await flush(); expect(c.login).toHaveBeenCalledOnce(); scene?.dispose(); @@ -134,11 +223,11 @@ describe('startBackgroundScene follows the sky state', () => { const onActive = vi.fn(); const scene = await startBackgroundScene(config, caps, { canvas, onInactive, onActive }); expect(onInactive).not.toHaveBeenCalled(); - setSkyState('day'); + setSkyChoice(NOON); await flush(); expect(onInactive).toHaveBeenCalledOnce(); expect(onActive).not.toHaveBeenCalled(); - setSkyState('dusk'); + setSkyChoice(DUSK); await flush(); expect(onActive).toHaveBeenCalledOnce(); expect(onInactive).toHaveBeenCalledOnce(); @@ -149,7 +238,7 @@ describe('startBackgroundScene follows the sky state', () => { createRidgeScene.mockReturnValueOnce(fakeScene()).mockReturnValueOnce(null); const onInactive = vi.fn(); const scene = await startBackgroundScene(config, caps, { canvas, onInactive }); - setSkyState('day'); + setSkyChoice(NOON); scene?.dispose(); await flush(); expect(onInactive).not.toHaveBeenCalled(); @@ -161,7 +250,7 @@ describe('startBackgroundScene follows the sky state', () => { const scene = await startBackgroundScene(config, caps, { canvas }); scene?.dispose(); scene?.dispose(); - setSkyState('day'); + setSkyChoice(NOON); await flush(); expect(createRidgeScene).toHaveBeenCalledOnce(); expect(first.dispose).toHaveBeenCalledOnce(); @@ -170,7 +259,7 @@ describe('startBackgroundScene follows the sky state', () => { it('builds nothing for a rebuild that is disposed before it starts', async () => { createRidgeScene.mockReturnValueOnce(fakeScene()).mockReturnValueOnce(fakeScene()); const scene = await startBackgroundScene(config, caps, { canvas }); - setSkyState('day'); + setSkyChoice(NOON); scene?.dispose(); await flush(); expect(createRidgeScene).toHaveBeenCalledOnce(); @@ -180,13 +269,13 @@ describe('startBackgroundScene follows the sky state', () => { const scenes = [fakeScene(), fakeScene(), fakeScene()]; scenes.forEach((s) => createRidgeScene.mockReturnValueOnce(s)); const scene = await startBackgroundScene(config, caps, { canvas }); - setSkyState('day'); - setSkyState('dusk'); + setSkyChoice(NOON); + setSkyChoice(DUSK); await flush(); // 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; expect(hex(createRidgeScene.mock.calls[built - 1][0].sky.top)).toBe( - hex(ridgeSkyFor('dusk').top) + hex(ridgeSkyFor(DUSK, FALLBACK_VIEW).top) ); const live = scenes[built - 1]; scene?.login(); @@ -204,32 +293,34 @@ describe('startBackgroundScene follows the sky state', () => { createRidgeScene.mockReturnValueOnce(fakeScene()).mockReturnValueOnce(fakeScene()); createRidgeScene.mockReturnValue(fakeScene()); const scene = await startBackgroundScene(config, caps, { canvas }); - setSkyState('day'); - setSkyState('dusk'); + setSkyChoice(NOON); + setSkyChoice(DUSK); await flush(); // The initial build and one rebuild, for dusk; day's rebuild stood down before building anything. expect(createRidgeScene).toHaveBeenCalledTimes(2); - expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe(hex(ridgeSkyFor('dusk').top)); + expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe( + hex(ridgeSkyFor(DUSK, FALLBACK_VIEW).top) + ); scene?.dispose(); }); // A second sky change `ticks` microtasks after the first. True when it landed mid-build: the build for the first - // change finished, was found stale and dropped (never shown), 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) => { createRidgeScene.mockReset(); - setSkyState('auto'); + setSkyChoice(AUTO); const [a, b, c] = [fakeScene(), fakeScene(), fakeScene()]; createRidgeScene.mockReturnValueOnce(a).mockReturnValueOnce(b).mockReturnValueOnce(c); const onActive = vi.fn(); const scene = await startBackgroundScene(config, caps, { canvas, onActive }); - setSkyState('day'); + setSkyChoice(NOON); await microtasks(ticks); - setSkyState('dusk'); + setSkyChoice(DUSK); await flush(); const at = `at ${ticks} microtasks`; const built = createRidgeScene.mock.calls.length; expect(hex(createRidgeScene.mock.calls[built - 1][0].sky.top), at).toBe( - hex(ridgeSkyFor('dusk').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. const live = [a, b, c][built - 1]; @@ -241,7 +332,7 @@ describe('startBackgroundScene follows the sky state', () => { }); scene?.dispose(); expect(live.dispose, at).toHaveBeenCalledOnce(); - return built === 3 && onActive.mock.calls.length === 1; + return built === 2 && onActive.mock.calls.length === 1; }; it('a sky change at any point of a build leaves only the newer build live; the stale one is disposed', async () => { @@ -255,14 +346,14 @@ describe('startBackgroundScene follows the sky state', () => { // This can fail after a correct refactor that changes the await count in create/skyKey and moves every offset // off the build. Then widen the range of offsets until some land again; do not weaken the assertion. expect(landed.length, 'at least one offset must land mid-build').toBeGreaterThan(0); - }); + }, 30000); it('leaves the ray-march scene alone: it has one fixed dusk', async () => { const inner = fakeScene() as unknown as Scene; createScene.mockReturnValue(inner); const scene = await startBackgroundScene({ ...config, style: 'raymarch' }, caps, { canvas }); expect(scene).toBe(inner); - setSkyState('day'); + setSkyChoice(NOON); await flush(); expect(createScene).toHaveBeenCalledOnce(); }); @@ -282,3 +373,823 @@ describe('startBackgroundScene follows the sky state', () => { expect(onCompileFail).toHaveBeenCalledWith(boom); }); }); + +describe('the ridge planes', () => { + const served = (over: Record = {}) => { + const files: Record = { + '/public/ridge/index.json': wireIndex, + '/public/ridge/vienna-abc123abc123/manifest.json': wireManifest(), + '/public/ridge/graz-def456def456/manifest.json': wireManifest({ + place: { ...(wireManifest() as any).place, id: 'graz', name: 'Graz' }, + }), + ...over, + }; + vi.stubGlobal( + 'fetch', + vi.fn(async (url: string) => + url in files + ? { ok: true, status: 200, json: async () => files[url] } + : { ok: false, status: 404, json: async () => ({}) } + ) + ); + }; + beforeEach(() => forgetManifests()); + + it('hands the scene the lit cards of its manifest, lit once for the sky it was given, over the manifest view', async () => { + served(); + const { ctl } = loader(); + createRidgeScene.mockReturnValue(fakeScene()); + const scene = await startBackgroundScene(config, caps, { canvas }); + const opts = createRidgeScene.mock.calls[0][0]; + expect(opts.backdrop.manifest.view.place.id).toBe('vienna'); + expect(opts.sky.physical.view).toBe(opts.backdrop.manifest.view); + expect(ctl.calls).toHaveLength(1); + expect(ctl.calls[0]).toBe(opts.sky.physical); // the sky the cards were lit for is the sky the scene paints + expect(ctl.calls[0].state).toBe('night'); // midnight by the clock + scene?.dispose(); + }); + + it("draws the place the viewer picks: one rebuild over that place's manifest; an id the index does not list decides nothing", async () => { + served(); + loader(); + createRidgeScene.mockReturnValue(fakeScene()); + const scene = await startBackgroundScene(config, caps, { canvas }); + const placeOf = (n: number) => createRidgeScene.mock.calls[n][0].backdrop.manifest.view.place.id; + expect(placeOf(0)).toBe('vienna'); + setPlaceChoice('graz'); + await flush(); + expect(createRidgeScene).toHaveBeenCalledTimes(2); + expect(placeOf(1)).toBe('graz'); + expect(getSkyPlace()?.id).toBe('graz'); + setPlaceChoice('atlantis'); // not in the index: the choice is ignored, so the default is drawn + await flush(); + expect(placeOf(2)).toBe('vienna'); + expect(createRidgeScene).toHaveBeenCalledTimes(3); + scene?.dispose(); + setPlaceChoice('graz'); + await flush(); + expect(createRidgeScene).toHaveBeenCalledTimes(3); // disposed: the door no longer listens to the choice + }); + + it('a picked place whose tiles do not come is not the drawn place: the store stays on the scene that is up, nothing loops, and a later pick of it builds afresh', async () => { + served(); + const d = loader(); + const [vienna, graz] = [fakeScene(), fakeScene()]; + createRidgeScene.mockReturnValueOnce(vienna).mockReturnValueOnce(graz); + const scene = await startBackgroundScene(config, caps, { canvas }); + expect(getSkyPlace()?.id).toBe('vienna'); + d.ctl.fail = true; // graz's tiles answer 503 + setPlaceChoice('graz'); + for (let i = 0; i < 5; i += 1) await flush(); + expect(d.ctl.made).toHaveLength(2); // one backdrop for the pick, asked once: the loader's own backoff retries it, the door builds nothing more + expect(d.ctl.made[1].manifest.view.place.id).toBe('graz'); + expect(createRidgeScene).toHaveBeenCalledOnce(); + expect(getSkyPlace()?.id).toBe('vienna'); // the canvas draws vienna, and so does the store + expect(vienna.dispose).not.toHaveBeenCalled(); + setPlaceChoice('graz'); // a tap on the same place asks again: the pending build is given up for a fresh one + for (let i = 0; i < 5; i += 1) await flush(); + expect(d.ctl.made).toHaveLength(3); + expect(d.ctl.made[1].dispose).toHaveBeenCalledOnce(); + expect(getSkyPlace()?.id).toBe('vienna'); + setPlaceChoice('vienna'); // back to the place that is up: nothing to build, the pending graz is left to its pick + for (let i = 0; i < 5; i += 1) await flush(); + expect(createRidgeScene).toHaveBeenCalledOnce(); + setPlaceChoice('graz'); + for (let i = 0; i < 5; i += 1) await flush(); + d.ctl.arrive(); // the tiles come + await flush(); + expect(createRidgeScene).toHaveBeenCalledTimes(2); + expect(getSkyPlace()?.id).toBe('graz'); + expect(vienna.dispose).toHaveBeenCalledOnce(); + scene?.dispose(); + }); + + it('awaits the first arc of tiles round the heading before the scene is made, and anchors a new place at its rest azimuth', async () => { + served(); + resetHeading(); + const d = loader(); + createRidgeScene.mockReturnValue(fakeScene()); + d.ctl.hold = true; + const started = startBackgroundScene(config, caps, { canvas }); + await flush(); + expect(createRidgeScene).not.toHaveBeenCalled(); // the tiles are not made yet + expect(d.ctl.made).toHaveLength(1); + const arc = d.ctl.made[0].ensure.mock.calls[0][0]; + expect((arc.fromDeg + arc.toDeg) / 2).toBeCloseTo(214, 0); // the Vienna rest azimuth, nothing having turned the view + expect(arc.toDeg - arc.fromDeg).toBeCloseTo(HFOV_MAX_DEG, 6); + await d.release(); + (await started)?.dispose(); + expect(createRidgeScene).toHaveBeenCalledOnce(); + // A rebuild for a new sky keeps the heading the view has turned to. + hold(100, performance.now()); + forgetManifests(); + (await startBackgroundScene(config, caps, { canvas }))?.dispose(); + const second = d.ctl.made[1].ensure.mock.calls[0][0]; + expect((second.fromDeg + second.toDeg) / 2).toBeCloseTo(100, 0); + }); + + it('bounds the speed from the anchor: while the first tiles load the view turns no faster than the place sustains, whatever speed is stored', async () => { + served({ '/public/ridge/vienna-abc123abc123/manifest.json': wireManifest({ camera: { r_max_m: 98.2, r_max_forward_m: 205.4 } }, 3, 32) }); // a ring whose gate holds fewer than all its tiles + resetHeading(); + resetCamera(); + setCamera({ mode: 'both', speedDegPerS: 12 }, 0); + const clock = vi.spyOn(performance, 'now').mockReturnValue(1_000); + const d = loader(); + let seen = NaN; + createRidgeScene.mockImplementation(() => { + seen = poseAt(performance.now()).h; + return fakeScene(); + }); + d.ctl.hold = true; + const started = startBackgroundScene(config, caps, { canvas }); + await flush(); + clock.mockReturnValue(6_000); // the tiles took five seconds + await d.release(); + (await started)?.dispose(); + const slow = maxSpeed(d.ctl.made[0].manifest, 'both'); + expect(slow).toBeLessThan(12); + expect(seen).toBeCloseTo(214 + 5 * slow, 6); // not 214 + 60 + clock.mockRestore(); + resetCamera(); + }); + + describe('a scene start with a deadline', () => { + /** A backdrop whose first arc never settles, holding `tiles` tiles. */ + const silent = (tiles: number) => { + const made: any[] = []; + createBackdrop.mockImplementation((manifest: unknown) => { + const bd = { + manifest, + dispose: vi.fn(), + litTiles: () => Array.from({ length: tiles }, (_, tile) => ({ tile, card: 0, canvas: {} })), + ensure: vi.fn(() => new Promise(() => undefined)), + }; + made.push(bd); + return bd; + }); + return made; + }; + const real = () => new Promise((r) => setImmediate(r)); + afterEach(() => { + vi.useRealTimers(); + }); + + it('draws with the tiles it has when the server is slow, and the rest fill in: the backdrop is the scene, not a finished load', async () => { + served(); + resetHeading(); + const made = silent(2); + createRidgeScene.mockReturnValue(fakeScene()); + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + const started = startBackgroundScene(config, caps, { canvas }); + for (let i = 0; i < 20; i += 1) await real(); + expect(made).toHaveLength(1); + expect(createRidgeScene).not.toHaveBeenCalled(); // the first arc is still out + await vi.advanceTimersByTimeAsync(PREPARE_DEADLINE_MS - 1); + for (let i = 0; i < 5; i += 1) await real(); + expect(createRidgeScene).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(1); + const scene = await started; + expect(createRidgeScene).toHaveBeenCalledOnce(); + expect(createRidgeScene.mock.calls[0][0].backdrop).toBe(made[0]); // the scene holds it, and goes on asking it for the arcs ahead + expect(made[0].dispose).not.toHaveBeenCalled(); + scene?.dispose(); + }); + + it('a rebuild has no deadline: the scene it replaces stays up, planes are not told to fail, and the new scene is swapped in when its tiles arrive', async () => { + served(); + resetHeading(); + const scenes: any[] = []; + createRidgeScene.mockImplementation(() => { + const s = fakeScene(); + scenes.push(s); + return s; + }); + const onPlanesFail = vi.fn(); + loader(); + const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail }); + expect(scenes).toHaveLength(1); + let held = 0; + let arrive = () => undefined as void; + const made: any[] = []; + createBackdrop.mockImplementation((manifest: unknown) => { + const bd = { + manifest, + dispose: vi.fn(), + litTiles: () => Array.from({ length: held }, (_, tile) => ({ tile, card: 0, canvas: {} })), + ensure: vi.fn( + () => + new Promise((resolve) => { + arrive = () => { + held = 1; + resolve(); + }; + }) + ), + }; + made.push(bd); + return bd; + }); + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + setSkyChoice(NOON); + for (let i = 0; i < 20; i += 1) await real(); + expect(made).toHaveLength(1); + await vi.advanceTimersByTimeAsync(10 * PREPARE_DEADLINE_MS); + for (let i = 0; i < 5; i += 1) await real(); + expect(createRidgeScene).toHaveBeenCalledOnce(); // still the first scene + expect(scenes[0].dispose).not.toHaveBeenCalled(); + expect(made[0].dispose).not.toHaveBeenCalled(); + expect(onPlanesFail).not.toHaveBeenCalled(); + arrive(); + for (let i = 0; i < 20; i += 1) await real(); + expect(createRidgeScene).toHaveBeenCalledTimes(2); + expect(createRidgeScene.mock.calls[1][0].backdrop).toBe(made[0]); + expect(scenes[0].dispose).toHaveBeenCalledOnce(); + expect(onPlanesFail).not.toHaveBeenCalled(); + scene?.dispose(); + }); + + it('is the sky alone, told once, when the deadline passes with no tile held, and lets go of the backdrop and its requests', async () => { + served(); + resetHeading(); + const made = silent(0); + createRidgeScene.mockReturnValue(fakeScene()); + const onPlanesFail = vi.fn(); + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + const started = startBackgroundScene(config, caps, { canvas, onPlanesFail }); + for (let i = 0; i < 20; i += 1) await real(); + await vi.advanceTimersByTimeAsync(PREPARE_DEADLINE_MS); + const scene = await started; + expect(createRidgeScene).toHaveBeenCalledOnce(); + expect(createRidgeScene.mock.calls[0][0].backdrop).toBeUndefined(); + expect(made[0].dispose).toHaveBeenCalledOnce(); + expect(onPlanesFail).toHaveBeenCalledOnce(); + scene?.dispose(); + }); + }); + + it('a build that goes stale disposes the backdrop it made, and a scene that fails to be made does too', async () => { + served(); + const d = loader(); + createRidgeScene.mockReturnValue(fakeScene()); + const scene = await startBackgroundScene(config, caps, { canvas }); + d.ctl.hold = true; + setSkyChoice(NOON); // stale once the next choice lands + await flush(); + const day = d.ctl.pending.splice(0); + setSkyChoice(DUSK); + await flush(); + const dusk = d.ctl.pending.splice(0); + dusk.forEach((s) => s()); + await flush(); + day.forEach((s) => s()); + await flush(); + const [, dayBackdrop, duskBackdrop] = d.ctl.made; + expect(dayBackdrop.dispose).toHaveBeenCalledOnce(); + expect(duskBackdrop.dispose).not.toHaveBeenCalled(); // it is the live scene's + scene?.dispose(); + createRidgeScene.mockImplementationOnce(() => { + throw new Error('boom'); + }); + d.ctl.hold = false; + const onCompileFail = vi.fn(); + forgetManifests(); + await startBackgroundScene(config, caps, { canvas, onCompileFail }); + expect(onCompileFail).toHaveBeenCalled(); + expect(d.ctl.made[d.ctl.made.length - 1].dispose).toHaveBeenCalledOnce(); + }); + + it('config place picks the index entry; an unknown id falls back to the default', async () => { + served(); + loader(); + createRidgeScene.mockReturnValue(fakeScene()); + (await startBackgroundScene({ ...config, place: 'graz' }, caps, { canvas }))?.dispose(); + expect(createRidgeScene.mock.calls[0][0].backdrop.manifest.view.place.id).toBe('graz'); + forgetManifests(); + (await startBackgroundScene({ ...config, place: 'nowhere' }, caps, { canvas }))?.dispose(); + 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()) => { + createRidgeScene.mockReturnValue(fakeScene()); + const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onCompileFail }); + const opts = createRidgeScene.mock.calls[0][0]; + expect(scene).not.toBeNull(); + expect(opts.backdrop).toBeUndefined(); + expect(opts.sky.physical.view).toBe(FALLBACK_VIEW); + expect(onPlanesFail).toHaveBeenCalledOnce(); + expect(onCompileFail).not.toHaveBeenCalled(); + scene?.dispose(); + }; + + it('a 404 manifest gives the sky-only scene with the fallback view, one onPlanesFail and no onCompileFail', async () => { + served({ '/public/ridge/index.json': undefined }); + vi.stubGlobal( + 'fetch', + vi.fn(async () => ({ ok: false, status: 404, json: async () => ({}) })) + ); + loader(); + await skyOnly(); + }); +}); + +describe('the ridge cards failing', () => { + it('a card that will not load gives the same sky-only scene, and a rebuild does not report again', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async (url: string) => ({ + ok: true, + status: 200, + json: async () => (url.endsWith('index.json') ? wireIndex : wireManifest()), + })) + ); + loader().ctl.fail = true; + forgetManifests(); + createRidgeScene.mockReturnValue(fakeScene()); + const onPlanesFail = vi.fn(); + const onCompileFail = vi.fn(); + const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onCompileFail }); + expect(createRidgeScene.mock.calls[0][0].backdrop).toBeUndefined(); + setSkyChoice(NOON); + await flush(); + expect(createRidgeScene).toHaveBeenCalledTimes(2); + expect(onPlanesFail).toHaveBeenCalledOnce(); + expect(onCompileFail).not.toHaveBeenCalled(); + scene?.dispose(); + }); +}); + +describe('the ridge cards and the live scene', () => { + const serve = (manifest: Record = wireManifest()) => + vi.stubGlobal( + 'fetch', + vi.fn(async (url: string) => ({ + ok: true, + status: 200, + json: async () => (url.endsWith('index.json') ? wireIndex : manifest), + })) + ); + beforeEach(() => forgetManifests()); + + it('says nothing about cards when they load', async () => { + serve(); + loader(); + createRidgeScene.mockReturnValue(fakeScene()); + const onPlanesFail = vi.fn(); + const onPlanesOk = vi.fn(); + const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onPlanesOk }); + setSkyChoice(NOON); + await flush(); + expect(createRidgeScene).toHaveBeenCalledTimes(2); + expect(createRidgeScene.mock.calls.every((c) => c[0].backdrop)).toBe(true); + expect(onPlanesFail).not.toHaveBeenCalled(); + expect(onPlanesOk).not.toHaveBeenCalled(); + scene?.dispose(); + }); + + it('lights the cards again for the new sky on a sky-change rebuild, never otherwise', async () => { + serve(); + const { ctl } = loader(); + createRidgeScene.mockReturnValue(fakeScene()); + const scene = await startBackgroundScene(config, caps, { canvas }); + expect(ctl.calls.map((s) => s.state)).toEqual(['night']); + setSkyChoice(NOON); + await flush(); + 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].backdrop.manifest.view.place.id).toBe('vienna'); + scene?.dispose(); + }); + + it('rebuilds the scene with the constellation lines when they are switched on, and again to take them off', async () => { + serve(); + loader(); + createRidgeScene.mockReturnValue(fakeScene()); + const scene = await startBackgroundScene(config, caps, { canvas }); + expect(createRidgeScene.mock.calls[0][0].lines).toBe(false); + setSkyChoice(NIGHT); // from Auto: a choice, a frozen sky + await flush(); + expect(createRidgeScene).toHaveBeenCalledTimes(2); + expect(createRidgeScene.mock.calls[1][0].lines).toBe(false); + setConstellationLines(true); + await flush(); + expect(createRidgeScene).toHaveBeenCalledTimes(3); + expect(createRidgeScene.mock.calls[2][0].lines).toBe(true); + setConstellationLines(false); + await flush(); + expect(createRidgeScene.mock.calls[3][0].lines).toBe(false); + scene?.dispose(); + }); + + it('a lighting pass that throws (no WebGL2) is the sky alone, one onPlanesFail and never onCompileFail', async () => { + serve(); + createBackdrop.mockImplementation(() => { + throw new Error('ridge: no WebGL2'); + }); + createRidgeScene.mockReturnValue(fakeScene()); + const onPlanesFail = vi.fn(); + const onCompileFail = vi.fn(); + const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onCompileFail }); + expect(createRidgeScene.mock.calls[0][0].backdrop).toBeUndefined(); + expect(createRidgeScene.mock.calls[0][0].sky.physical.view).toBe(FALLBACK_VIEW); + expect(onPlanesFail).toHaveBeenCalledOnce(); + expect(onPlanesFail.mock.calls[0][0].message).toMatch(/WebGL2/); + expect(onCompileFail).not.toHaveBeenCalled(); + scene?.dispose(); + }); + + it("keys a rebuild by the manifest's place: the same sky over a rebaked place rebuilds", async () => { + serve(); + loader(); + const [a, b] = [fakeScene(), fakeScene()]; + createRidgeScene.mockReturnValueOnce(a).mockReturnValueOnce(b); + const w = wireManifest() as any; + setSkyChoice(NIGHT); + const scene = await startBackgroundScene(config, caps, { canvas }); + // The same choice, told again while the place is the one drawn: no rebuild. + setSkyPlace(undefined); + await flush(); + expect(createRidgeScene).toHaveBeenCalledOnce(); + forgetManifests(); + serve({ ...w, place: { ...w.place, id: 'graz' } }); + setSkyPlace(FALLBACK_VIEW.place); // the store only moves on a made scene, so the test moves it to wake the door once more + await flush(); + expect(createRidgeScene).toHaveBeenCalledTimes(2); + expect(createRidgeScene.mock.calls[1][0].backdrop.manifest.view.place.id).toBe('graz'); + scene?.dispose(); + }); + + it("reads the weather against the manifest place's sun, not the fallback place's", async () => { + const w = wireManifest() as any; + const place = { ...w.place, id: 'vienna', lat: -33, lon: -163.65, tz_h: -11 }; + const now = new Date('2026-11-11T10:50:00Z'); + const wx = { + fetched_at: '2026-11-11T10:45:00Z', + observed_at: '2026-11-11T10:40:00Z', + station: 11035, + precip_mm_10min: 0, + humidity_pct: 60, + sunshine_s_10min: null, + glow_wm2: 100, + attribution: creditLine(WEATHER_FEEDS.vienna), + }; + vi.stubGlobal( + 'fetch', + vi.fn(async (url: string) => ({ + ok: true, + status: 200, + json: async () => + url.endsWith('weather.json') + ? wx + : url.endsWith('index.json') + ? wireIndex + : { ...w, place }, + })) + ); + loader(); + setSkyClock(() => now); + createRidgeScene.mockReturnValue(fakeScene()); + (await startBackgroundScene(config, caps, { canvas }))?.dispose(); + const file = parseWeatherFile(wx, WEATHER_FEEDS.vienna)!; + const at = (p: { lat: number; lon: number }) => + weatherFromFile( + file, + sunAt({ id: 'x', altitudeKm: 0, tz: 'UTC', ...p }, new Date(Date.parse(wx.observed_at) - 5 * 60_000)) + .elevation + ); + expect(at(FALLBACK_VIEW.place)).not.toBe(at(place)); + expect(ridgeWeather()).toBe(at(place)); + }); + + it('a failed load is the sky alone on the fallback view, never the manifest place', async () => { + serve(); + const { ctl } = loader(); + ctl.fail = true; + createRidgeScene.mockReturnValue(fakeScene()); + const scene = await startBackgroundScene(config, caps, { canvas }); + const opts = createRidgeScene.mock.calls[0][0]; + expect(opts.backdrop).toBeUndefined(); + expect(opts.sky.physical.view).toBe(FALLBACK_VIEW); + scene?.dispose(); + }); + + it('a rebuild keeps the old scene until the new planes have loaded, then swaps', async () => { + serve(); + const d = loader(); + const first = fakeScene(); + const second = fakeScene(); + createRidgeScene.mockReturnValueOnce(first).mockReturnValueOnce(second); + const onActive = vi.fn(); + const scene = await startBackgroundScene(config, caps, { canvas, onActive }); + d.ctl.hold = true; + setSkyChoice(NOON); + await flush(); + expect(d.ctl.pending.length).toBeGreaterThan(0); + expect(first.dispose).not.toHaveBeenCalled(); + expect(createRidgeScene).toHaveBeenCalledOnce(); + scene?.login(); + expect(first.login).toHaveBeenCalledOnce(); + await d.release(); + expect(createRidgeScene).toHaveBeenCalledTimes(2); + expect(first.dispose).toHaveBeenCalledOnce(); + expect(second.dispose).not.toHaveBeenCalled(); + expect(onActive).toHaveBeenCalledOnce(); + expect(second.login).toHaveBeenCalledOnce(); // replayed onto the swapped-in scene + scene?.dispose(); + expect(second.dispose).toHaveBeenCalledOnce(); + }); + + it('a build that fails after the scene is disposed makes nothing and says nothing', async () => { + serve(); + const d = loader(); + createRidgeScene.mockReturnValue(fakeScene()); + const onPlanesFail = vi.fn(); + const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail }); + d.ctl.hold = true; + d.ctl.fail = true; + setSkyChoice(NOON); + await flush(); + scene?.dispose(); + await d.release(); + expect(createRidgeScene).toHaveBeenCalledOnce(); + expect(onPlanesFail).not.toHaveBeenCalled(); + }); + + it('a superseded build that fails does not speak for the live scene, which has planes', async () => { + serve(); + const d = loader(); + createRidgeScene.mockReturnValue(fakeScene()); + const onPlanesFail = vi.fn(); + const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail }); + d.ctl.hold = true; + d.ctl.fail = true; + setSkyChoice(NOON); // stale: its decodes will reject + await flush(); + d.ctl.fail = false; + setSkyChoice(DUSK); // the live one: its decodes will succeed + await flush(); + const stale = d.ctl.pending.splice(0, 1); + d.ctl.pending.length = 0; + d.ctl.hold = false; + stale.forEach((s) => s()); // the first six are day's, settled in order + await flush(); + expect(onPlanesFail).not.toHaveBeenCalled(); + scene?.dispose(); + }); + + it('a superseded build that finishes after the newer one touches nothing of the live scene', async () => { + serve(); + const d = loader(); + const [first, second, third] = [fakeScene(), fakeScene(), fakeScene()]; + createRidgeScene + .mockReturnValueOnce(first) + .mockReturnValueOnce(second) + .mockReturnValueOnce(third); + const onActive = vi.fn(); + const scene = await startBackgroundScene(config, caps, { canvas, onActive }); + d.ctl.hold = true; + setSkyChoice(NOON); // stale: its decodes are held until after the newer build is live + await flush(); + const dayDecodes = d.ctl.pending.splice(0); + setSkyChoice(DUSK); + await flush(); + const duskDecodes = d.ctl.pending.splice(0); + expect(dayDecodes.length).toBeGreaterThan(0); + expect(duskDecodes.length).toBeGreaterThan(0); + duskDecodes.forEach((s) => s()); + await flush(); + expect(createRidgeScene).toHaveBeenCalledTimes(2); + expect(first.dispose).toHaveBeenCalledOnce(); + expect(onActive).toHaveBeenCalledOnce(); + dayDecodes.forEach((s) => s()); // the stale build finishes last + await flush(); + expect(createRidgeScene).toHaveBeenCalledTimes(2); + expect(second.dispose).not.toHaveBeenCalled(); // the live scene is not disposed by a build that lost + expect(onActive).toHaveBeenCalledOnce(); + scene?.login(); + expect(second.login).toHaveBeenCalledOnce(); + scene?.dispose(); + expect(second.dispose).toHaveBeenCalledOnce(); + expect(third.dispose).not.toHaveBeenCalled(); + }); + + it('a build that finishes after dispose makes nothing, shows nothing and disposes nothing twice', async () => { + serve(); + const d = loader(); + const first = fakeScene(); + createRidgeScene.mockReturnValueOnce(first).mockReturnValueOnce(fakeScene()); + const onActive = vi.fn(); + const scene = await startBackgroundScene(config, caps, { canvas, onActive }); + d.ctl.hold = true; + setSkyChoice(NOON); + await flush(); + scene?.dispose(); + await d.release(); + expect(createRidgeScene).toHaveBeenCalledOnce(); + expect(first.dispose).toHaveBeenCalledOnce(); + expect(onActive).not.toHaveBeenCalled(); + }); + + it('a rebuild whose scene cannot be made says nothing about planes and leaves the host inactive', async () => { + serve(); + loader(); + createRidgeScene.mockReturnValueOnce(fakeScene()).mockReturnValueOnce(null); + const onPlanesFail = vi.fn(); + const onInactive = vi.fn(); + const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onInactive }); + setSkyChoice(NOON); + await flush(); + expect(onInactive).toHaveBeenCalledOnce(); + expect(onPlanesFail).not.toHaveBeenCalled(); + scene?.dispose(); + }); + + it('a rebuild has no failure end: with no tile it stays pending beside the scene that is up (its loader asking again), replaces it the moment a tile is held, and the ink follows the sky drawn throughout', async () => { + serve(); + const d = loader(); + const [first, second] = [fakeScene(), fakeScene()]; + createRidgeScene.mockReturnValueOnce(first).mockReturnValueOnce(second); + const [onPlanesFail, onInactive, onActive] = [vi.fn(), vi.fn(), vi.fn()]; + setSkyChoice(NOON); + const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onInactive, onActive }); + expect(scene?.drawnSky).toBe('day'); + d.ctl.fail = true; // the link blinks for the whole pass of the rebuild + setSkyChoice(NIGHT); + await flush(); + await flush(); + expect(createRidgeScene).toHaveBeenCalledOnce(); + expect(first.dispose).not.toHaveBeenCalled(); // the ridge that was fine is still up + expect(d.ctl.made[1].dispose).not.toHaveBeenCalled(); // and the build for the new sky is alive, not given up + expect(getResolvedSkyState()).toBe('night'); // the sky is announced as night + expect(scene?.drawnSky).toBe('day'); // the scene up draws day, and that is what the ink follows + expect([onPlanesFail, onInactive, onActive].map((f) => f.mock.calls.length)).toEqual([0, 0, 0]); + d.ctl.arrive(); // the loader's retry got a tile through + await flush(); + expect(createRidgeScene).toHaveBeenCalledTimes(2); + expect(first.dispose).toHaveBeenCalledOnce(); + expect(onActive).toHaveBeenCalledOnce(); + expect(onActive).toHaveBeenCalledWith('night'); + expect(scene?.drawnSky).toBe('night'); + expect(onPlanesFail).not.toHaveBeenCalled(); + scene?.dispose(); + }); + + it('a pending rebuild is superseded by a newer one, which is given up at once; the newest replaces the scene', async () => { + serve(); + const d = loader(); + const [first, second] = [fakeScene(), fakeScene()]; + createRidgeScene.mockReturnValueOnce(first).mockReturnValueOnce(second); + const onActive = vi.fn(); + setSkyChoice(NOON); + const scene = await startBackgroundScene(config, caps, { canvas, onActive }); + d.ctl.fail = true; + setSkyChoice(NIGHT); + await flush(); + setSkyChoice(DUSK); + await flush(); + expect(d.ctl.made[1].dispose).toHaveBeenCalledOnce(); + expect(d.ctl.made[2].dispose).not.toHaveBeenCalled(); + d.ctl.arrive(); + await flush(); + expect(createRidgeScene).toHaveBeenCalledTimes(2); + expect(onActive).toHaveBeenCalledOnce(); + expect(onActive).toHaveBeenCalledWith('dusk'); + scene?.dispose(); + }); + + it('a build a newer one supersedes is given up at once: its backdrop is disposed when the newer begins, not when its own pass ends', async () => { + serve(); + const d = loader(); + createRidgeScene.mockReturnValue(fakeScene()); + const scene = await startBackgroundScene(config, caps, { canvas }); + d.ctl.hold = true; // a slow link: no pass ends + for (const choice of [NOON, DUSK, NIGHT, NOON, DUSK]) { + setSkyChoice(choice); + await flush(); + } + const [live, ...builds] = d.ctl.made; + expect(builds).toHaveLength(5); + builds.slice(0, 4).forEach((b) => expect(b.dispose).toHaveBeenCalledOnce()); // all but the newest, while their requests are still out + expect(builds[4].dispose).not.toHaveBeenCalled(); + expect(live.dispose).not.toHaveBeenCalled(); // the scene that is up is not theirs to give up + scene?.dispose(); + expect(builds[4].dispose).toHaveBeenCalledOnce(); // and disposing the door gives up the one in flight + await d.release(); + expect(createRidgeScene).toHaveBeenCalledOnce(); + }); + + it('tells the host when the live scene loses its planes and when it gets them back', async () => { + serve(); + const d = loader(); + d.ctl.fail = true; + createRidgeScene.mockReturnValue(fakeScene()); + const onPlanesFail = vi.fn(); + const onPlanesOk = vi.fn(); + const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onPlanesOk }); + expect(onPlanesFail).toHaveBeenCalledOnce(); + setSkyChoice(NOON); // still failing: the host is not told twice + await flush(); + expect(onPlanesFail).toHaveBeenCalledOnce(); + expect(onPlanesOk).not.toHaveBeenCalled(); + d.ctl.fail = false; + setSkyChoice(DUSK); + await flush(); + expect(onPlanesOk).toHaveBeenCalledOnce(); + expect(createRidgeScene.mock.calls[2][0].backdrop).toBeDefined(); + d.ctl.fail = true; // a rebuild with no tile does not take the planes from the scene that has them: it waits + setSkyChoice(NIGHT); + await flush(); + expect(onPlanesFail).toHaveBeenCalledOnce(); + expect(createRidgeScene).toHaveBeenCalledTimes(3); + d.ctl.arrive(); + await flush(); + expect(createRidgeScene).toHaveBeenCalledTimes(4); + expect(onPlanesFail).toHaveBeenCalledOnce(); + scene?.dispose(); + }); +}); diff --git a/src/app/features/scene/index.ts b/src/app/features/scene/index.ts index 36010b40..0e3509cb 100644 --- a/src/app/features/scene/index.ts +++ b/src/app/features/scene/index.ts @@ -1,65 +1,190 @@ import type { Scene, SceneOptions } from './Scene'; import { BackgroundSceneConfig, Capabilities, SceneTier, resolveTier } from './tier'; import { debugOverlaysAllowed } from './debugOverlays'; -import { getSkyState, subscribe } from './skyState'; -import type { SkyState } from './skyState'; +import { getConstellationLines, getSkyChoice, skyBandAt, subscribe } from './skyState'; +import type { FixedSkyState, SkyChoice } from './ridge/skyMoment'; +import { drawnView, ensureSkyPlace, resetSkyPlanes } from './skyPlace'; +import { subscribePlaceChoice } from './placeState'; +import type { SkyColours } from './ridge/skyColour'; +import type { Backdrop } from './ridge/Backdrop'; +import { FALLBACK_VIEW, HFOV_MAX_DEG, maxSpeed } from './ridge/view'; export type { Scene, SceneStats } from './Scene'; + +/** The scene the door returns: it also says which sky it draws now (the band of the scene that is up, not of the sky announced). */ +export interface StartedScene extends Scene { + readonly drawnSky: FixedSkyState | undefined; +} export type { SceneStyle, SceneTier } from './tier'; export type StartOptions = Omit & { /** A shader failed to compile, or the scene chunk failed to load. The host keeps its ground. */ 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; - /** A rebuild made a scene again: the host lets it show. */ - onActive?: () => void; + /** A rebuild made a scene again: the host lets it show, over the sky that scene draws (what the page ink follows). */ + onActive?: (sky?: FixedSkyState) => void; + /** The live scene is the sky alone because the baked ridge cards did not load (no manifest, a missing or undecodable card, no WebGL2 to light them). The host may fill the ground. Told when the live scene changes to that state, never for a build that did not win. */ + onPlanesFail?: (e: Error) => void; + /** The live scene has its planes after `onPlanesFail` said it had none: the host lets go of the ground it filled. */ + onPlanesOk?: () => void; }; /** 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`; -async function create( +/** 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 { + make: () => Scene | null; + /** Let go of what was made for a scene that will never be made (a build that went stale): the backdrop's lighting context. */ + discard: () => void; + /** Why this scene is the sky alone, when the baked planes did not load; null when it has planes or none are asked for. */ + planesFail: Error | null; + /** The band of the sky this scene is made with: what it draws once made. */ + sky: FixedSkyState | undefined; +} + +/** How long the first scene start waits for the first tiles, ms: past it the scene draws with the tiles it has and the rest arrive into it; with none, it is the sky alone. A rebuild over a scene with a ridge has no deadline and no failure end: the scene it replaces stays up until the new one holds tiles. */ +export const PREPARE_DEADLINE_MS = 6_000; + +/** Resolves when `backdrop` holds a tile (its loader retries a failed one on its own backoff) or `stop` aborts. */ +const holdsATile = (backdrop: Backdrop, stop: AbortSignal): Promise => + new Promise((done) => { + if (backdrop.litTiles().length > 0 || stop.aborted) { + done(); + return; + } + const off = backdrop.onTile(() => { + off(); + done(); + }); + stop.addEventListener( + 'abort', + () => { + off(); + done(); + }, + { once: true } + ); + }); + +async function prepare( config: BackgroundSceneConfig | undefined, options: StartOptions & { tier: SceneTier; debug?: boolean }, - state: SkyState -): Promise { + choice: SkyChoice, + /** Nothing with a ridge is up to wait behind: the page's first scene, or a rebuild over a scene that is the sky alone. It waits against the deadline and, with no tile, is the sky alone. */ + first: boolean, + superseded: AbortSignal +): Promise { + // Whatever throws in making the scene is a compile failure, as whatever throws in loading it. + let backdrop: Backdrop | null = null; + /** Give up the backdrop this build made, once: when a newer build supersedes it, or when it is not the scene's. */ + const release = () => { + backdrop?.dispose(); + backdrop = null; + }; + superseded.addEventListener('abort', release, { once: true }); + let band: FixedSkyState | undefined; + /** `commit` runs when the scene is made, never before: only then is its place the drawn one (`drawnView`). */ + const guarded = (make: () => Scene | null, commit?: () => void): Prepared => ({ + planesFail: null, + sky: band, + discard: release, + make: () => { + try { + const scene = make(); + if (scene) commit?.(); + return scene; + } catch (e) { + release(); + options.onCompileFail?.(e instanceof Error ? e : new Error(String(e))); + return null; + } + }, + }); try { - // Loaded here, with the scenes, so the main chunk does not carry the terrain sky or the baked tables. - const { loadWeather, ridgeSkyFor, terrainSkyFor } = await import('./skyForState'); - if (config?.style === 'raymarch') return (await import('./Scene')).createScene(options); - if (config?.style === 'terrain') { - const { createTerrainScene } = await import('./terrain/Terrain'); - const sky = terrainSkyFor(state); - const scene = createTerrainScene({ ...options, ...sky }); - // No WebGL2 (or no usable GL): the terrain's sky alone on the same canvas, not bare ground. - if (scene) return scene; - const { createTerrainSkyScene } = await import('./terrain/TerrainSky2D'); - return createTerrainSkyScene({ ...options, ...sky }); + // Loaded here, with the scenes, so the main chunk does not carry the ridge sky or the baked tables. + const { loadWeather, ridgeSkyFor } = await import('./skyForState'); + if (config?.style === 'raymarch') { + const { createScene } = await import('./Scene'); + return guarded(() => createScene(options)); } const { createRidgeScene } = await import('./ridge/Ridge'); - await loadWeather(weatherUrl()); - return createRidgeScene({ ...options, sky: ridgeSkyFor(state) }); + const { manifest, fail } = await ensureSkyPlace(config); + await loadWeather(weatherUrl(), (manifest?.view ?? FALLBACK_VIEW).place); + // The tiles around the heading load with the scene chunk and the weather, and are lit here for this sky (a sky change comes through a rebuild), so + // createRidgeScene stays synchronous and the scene's first frame has its ridge; it asks for the tiles ahead as the view turns. Any failure, a missing + // WebGL2 included, is the sky alone, over the view the store is told of. + let lit: SkyColours | undefined; + let planesFail: Error | null = fail; + if (manifest) { + try { + const manifestSky = ridgeSkyFor(choice, manifest.view); + const { createBackdrop } = await import('./ridge/Backdrop'); + const heading = await import('./ridge/heading'); + backdrop = createBackdrop(manifest, manifestSky.physical as NonNullable); + // A place not shown before faces its rest azimuth; a rebuild for a sky keeps the heading the view has turned to. The speed is bounded from here on, not + // from the scene's first frame: the view does not turn further than the place sustains while the tiles load. + const now = performance.now(); + heading.anchor(manifest.view.place.id, manifest.view.lookAzDeg, now, (mode) => maxSpeed(manifest, mode)); + const { h } = heading.poseAt(now); + // The first arc. The first scene of a page has nothing to show meanwhile, so it waits against a deadline (a slow or silent server must not hold it back): + // what is held by then is drawn and the rest fills in. A rebuild has the old scene up and has no end: it waits for a tile as long as that takes, its loader asking again. + let timer: ReturnType | undefined; + try { + await Promise.race([ + backdrop.ensure({ fromDeg: h - HFOV_MAX_DEG / 2, toDeg: h + HFOV_MAX_DEG / 2 }), + new Promise((late) => { + if (first) timer = setTimeout(late, PREPARE_DEADLINE_MS); + }), + ]); + } finally { + clearTimeout(timer); + } + if (!first) await holdsATile(backdrop, superseded); + if (superseded.aborted) throw new Error('ridge: superseded'); + if (backdrop.litTiles().length === 0) throw new Error('ridge cards did not load'); + lit = manifestSky; + } catch (e) { + release(); + planesFail = e instanceof Error ? e : new Error(String(e)); + } + } + // What this build draws. The store's place is told when the scene is made (`commit`), so a build that is still loading, or that is given up, names nothing. + const view = backdrop && manifest ? manifest.view : FALLBACK_VIEW; + if (!lit) await loadWeather(weatherUrl(), view.place); + const sky = lit ?? ridgeSkyFor(choice, view); + band = skyBandAt(choice, view.place); + const made = guarded( + () => + createRidgeScene({ + ...options, + sky, + backdrop: backdrop ?? undefined, + lines: getConstellationLines(), + }), + () => drawnView(backdrop ? manifest : null) + ); + return { ...made, planesFail }; } catch (e) { options.onCompileFail?.(e instanceof Error ? e : new Error(String(e))); - return null; + return { make: () => null, discard: () => undefined, planesFail: null, sky: undefined }; } } /** * 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; the page URL steers - * only 'auto' (`terrainSkyFor`), so there the two differ and the key says so. + * (Auto picked as a named moment it already is drawing) is not a rebuild. */ async function skyKey( config: BackgroundSceneConfig | undefined, - state: SkyState + choice: SkyChoice ): Promise { try { - const { loadWeather, ridgeSkyKey, terrainSkyFor } = await import('./skyForState'); - if (config?.style === 'terrain') return JSON.stringify(terrainSkyFor(state)); - await loadWeather(weatherUrl()); - return ridgeSkyKey(state); + const { loadWeather, ridgeSkyKey } = await import('./skyForState'); + const { view } = await ensureSkyPlace(config); + await loadWeather(weatherUrl(), view.place); + return ridgeSkyKey(choice, view); } catch { // The chunk failed to load: no key, so every change rebuilds (and `create` reports the failure). return null; @@ -69,12 +194,11 @@ async function skyKey( /** * The client's one door to the scene. When the tier resolves to 'off' nothing is imported and no * canvas context is requested; otherwise the scene code loads on demand, so it stays out of the - * main chunk. `config.style` picks the scene: the ridges unless it says 'raymarch' or 'terrain' (which falls back to its - * sky alone, `terrain/TerrainSky2D.ts`, where WebGL2 is missing). Null means + * main chunk. `config.style` picks the scene: the ridges unless it says 'raymarch' (any other value, an old 'terrain' included, is the ridges). Null means * "keep the CSS ground", including when that chunk fails to load (offline, stale deploy): the * failure goes to onCompileFail and nothing throws. * - * The ridge and terrain scenes bake their sky once, so they follow 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 * 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. @@ -83,49 +207,94 @@ export async function startBackgroundScene( config: BackgroundSceneConfig | undefined, capabilities: Capabilities, options: StartOptions -): Promise { +): Promise { const tier = resolveTier(config, capabilities); if (tier === 'off') return null; const debug = debugOverlaysAllowed(config); - const build = (state: SkyState) => create(config, { ...options, tier, debug }, state); - const state = getSkyState(); - const key0 = config?.style === 'raymarch' ? null : await skyKey(config, state); - const first = await build(state); - if (!first || config?.style === 'raymarch') return first; + // What the host was last told of the planes: only the live scene speaks, and only when its state changes. + let planesFailed = false; + const announce = (planesFail: Error | null) => { + if (planesFail && !planesFailed) options.onPlanesFail?.(planesFail); + if (!planesFail && planesFailed) options.onPlanesOk?.(); + planesFailed = planesFail !== null; + }; + const prepared = (choice: SkyChoice, first: boolean, stop: AbortSignal) => prepare(config, { ...options, tier, debug }, choice, first, stop); + resetSkyPlanes(); + const choice = getSkyChoice(); + const key0 = config?.style === 'raymarch' ? null : await skyKey(config, choice); + const firstReady = await prepared(choice, true, new AbortController().signal); + const first = firstReady.make(); + if (!first) return null; + // The ray-march scene has one fixed dusk. + if (config?.style === 'raymarch') return Object.assign(first, { drawnSky: 'dusk' as const }); + announce(firstReady.planesFail); let inner: Scene | null = first; let built = key0; + let shown = key0; // the sky key of the scene that is up + let drawnSky = firstReady.sky; // the band of the scene that is up let loggedIn = false; let disposed = false; let generation = 0; - // A rebuild is for a different sky ('auto' crossing a boundary, a new choice), not for a repeat of the one drawn. + let building: AbortController | undefined; + // A rebuild is for a different sky ('auto' crossing a boundary, a new choice), not for a repeat of the one drawn. What replaces the scene that is up: a new backdrop, + // the moment it holds tiles (its loader asks again on its own until it does; a rebuild has no failure end); a build a newer one supersedes is given up at once (its + // requests aborted). A rebuild never swaps a ridge for the sky alone; only a build with no ridge up behind it (the first load, or a rebuild over the sky alone) that ends with no tile is the sky alone. const rebuild = async () => { // 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); - if (getSkyState() !== next) return; + if (getSkyChoice() !== next) return; if ((key !== null && key === built) || disposed) return; generation += 1; const mine = generation; built = key; - inner?.dispose(); - inner = null; - const scene = await build(next); + building?.abort(); + const mineAborts = new AbortController(); + building = mineAborts; + // The old scene stays up while the next one loads; a build that is stale or after dispose is never made, so it never speaks. + const ready = await prepared(next, planesFailed, mineAborts.signal); // over a sky-only scene there is no ridge to protect: the new sky is drawn at once if (disposed || mine !== generation) { - scene?.dispose(); + ready.discard(); return; } + building = undefined; + if (ready.planesFail && !planesFailed) { + ready.discard(); + built = shown; + return; + } + inner?.dispose(); + inner = null; + const scene = ready.make(); inner = scene; + shown = key; + drawnSky = ready.sky; + if (scene) announce(ready.planesFail); if (!scene) options.onInactive?.(); else { - options.onActive?.(); + options.onActive?.(ready.sky); if (loggedIn) scene.login(); } }; - const off = subscribe(rebuild); + // A place picked in the Place submenu is a rebuild: `skyKey` re-resolves the pick (skyPlace.ts) into the place to build, and so the key's; the store's place stays the + // drawn one until that scene is made. A pick is also a request to try again: what stands pending (a place whose tiles do not come) is given up for a fresh build, and + // a pick of the place already up is the key of the scene shown, so it builds nothing. + const offSky = subscribe(rebuild); + const offPlace = subscribePlaceChoice(() => { + built = shown; + rebuild(); + }); + const off = () => { + offSky(); + offPlace(); + }; // A change that landed while the first build was awaited was missed by the subscription. rebuild(); return { + get drawnSky() { + return drawnSky; + }, login() { loggedIn = true; inner?.login(); @@ -134,6 +303,7 @@ export async function startBackgroundScene( if (disposed) return; disposed = true; off(); + building?.abort(); inner?.dispose(); inner = null; }, diff --git a/src/app/features/scene/placeState.test.ts b/src/app/features/scene/placeState.test.ts new file mode 100644 index 00000000..193f4d94 --- /dev/null +++ b/src/app/features/scene/placeState.test.ts @@ -0,0 +1,77 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const KEY = 'ratatoskr.skyPlace'; +const store = (initial: Record = {}) => { + const data = new Map(Object.entries(initial)); + const set = vi.fn((k: string, v: string) => void data.set(k, v)); + vi.stubGlobal('localStorage', { getItem: (k: string) => data.get(k) ?? null, setItem: set }); + return { data, set }; +}; +const fresh = async () => { + vi.resetModules(); + return import('./placeState'); +}; + +beforeEach(() => { + store(); +}); +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('the viewer place choice', () => { + it('is none until picked, then persists per viewer under ratatoskr.skyPlace', async () => { + const { data } = store(); + const a = await fresh(); + expect(a.getPlaceChoice()).toBeUndefined(); + a.setPlaceChoice('fuji'); + expect(a.getPlaceChoice()).toBe('fuji'); + expect(data.get(KEY)).toBe('fuji'); + store({ [KEY]: 'fuji' }); + expect((await fresh()).getPlaceChoice()).toBe('fuji'); + }); + + it('reads garbage as no choice', async () => { + for (const bad of ['', ' ', '{"id":"fuji"}', 'Fuji!', '../x', 'a'.repeat(65)]) { + store({ [KEY]: bad }); + expect((await fresh()).getPlaceChoice()).toBeUndefined(); + } + }); + + it('holds for the page load when storage refuses, reading and writing', async () => { + vi.stubGlobal('localStorage', { + getItem: () => { + throw new Error('blocked'); + }, + setItem: () => { + throw new Error('blocked'); + }, + }); + const s = await fresh(); + expect(s.getPlaceChoice()).toBeUndefined(); + s.setPlaceChoice('matterhorn'); + expect(s.getPlaceChoice()).toBe('matterhorn'); + }); + + it('tells listeners of every valid pick, a repeat of the id included (a tap on a place that has not come up asks again), and not of a malformed one', async () => { + const s = await fresh(); + const heard = vi.fn(); + const off = s.subscribePlaceChoice(heard); + s.setPlaceChoice('fuji'); + s.setPlaceChoice('fuji'); + s.setPlaceChoice('NOT AN ID'); + expect(heard).toHaveBeenCalledTimes(2); + s.setPlaceChoice('amadablam'); + expect(heard).toHaveBeenCalledTimes(3); + off(); + s.setPlaceChoice('fuji'); + expect(heard).toHaveBeenCalledTimes(3); + }); + + it('does not write storage for a choice it already holds', async () => { + const { set } = store({ [KEY]: 'fuji' }); + const s = await fresh(); + s.setPlaceChoice('fuji'); + expect(set).not.toHaveBeenCalled(); + }); +}); diff --git a/src/app/features/scene/placeState.ts b/src/app/features/scene/placeState.ts new file mode 100644 index 00000000..a0cc78fb --- /dev/null +++ b/src/app/features/scene/placeState.ts @@ -0,0 +1,54 @@ +// The place the viewer picked in the scene view's Place submenu (ruling ridge-places-dropdown-first-four): an id, per viewer, kept in this browser only and never +// shared. It is a wish, not a place: whether it names a baked place is decided by `skyPlace.ts`, the one resolution, which ignores an id the index does not list. +// Main-chunk safe: no sky, no ridge code. +const KEY = 'ratatoskr.skyPlace'; +/** A place id as the baker writes it; anything else in storage is no choice. */ +const ID = /^[a-z0-9][a-z0-9_-]{0,63}$/; + +let choice: string | undefined; +let read = false; +const listeners = new Set<() => void>(); + +/** The viewer's picked place id, or undefined for none (never picked, refused storage, or garbage in storage). */ +export function getPlaceChoice(): string | undefined { + if (!read) { + read = true; + try { + const v = localStorage.getItem(KEY); + choice = v !== null && ID.test(v) ? v : undefined; + } catch { + choice = undefined; + } + } + return choice; +} + +/** + * Pick a place. Stored when it changed and storage allows (else it holds for this page load). Listeners hear every valid pick, a repeat of the id included: a tap + * on a place that has not come up (its tiles did not load) is a request to try again, and a listener that has nothing to do for it ignores it. + */ +export function setPlaceChoice(id: string): void { + if (!ID.test(id)) return; + if (getPlaceChoice() !== id) { + choice = id; + try { + localStorage.setItem(KEY, id); + } catch { + // Storage is refused (private mode, quota): the choice holds for this page load only. + } + } + [...listeners].forEach((cb) => cb()); +} + +export function subscribePlaceChoice(cb: () => void): () => void { + listeners.add(cb); + return () => { + listeners.delete(cb); + }; +} + +/** For tests: forget the choice held in memory and read storage afresh at the next ask. */ +export const forgetPlaceChoice = (): void => { + choice = undefined; + read = false; +}; diff --git a/src/app/features/scene/ridge/Backdrop.test.ts b/src/app/features/scene/ridge/Backdrop.test.ts new file mode 100644 index 00000000..04ee6185 --- /dev/null +++ b/src/app/features/scene/ridge/Backdrop.test.ts @@ -0,0 +1,478 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import type { Mock } from 'vitest'; +import { + createBackdrop, + FETCH_PARALLEL, + FETCH_TIMEOUT_MS, + NotFound, + RETRY_FIRST_MS, + RETRY_MAX_MS, +} from './Backdrop'; +import type { CardBitmaps, Lighter } from './lightCards'; +import { parseManifest } from './manifest'; +import { wireManifest } from './manifest.fixture'; +import type { PhysicalSky } from './physicalSky'; +import { KEEP_MARGIN_TILES, LOAD_MARGIN_TILES, residentTiles, runTiles } from './ring'; +import { HFOV_MAX_DEG } from './view'; + +const sky = {} as PhysicalSky; +const manifest = parseManifest(wireManifest({}, 3, 32), '/d/'); // the ring as the baker cuts it: 32 tiles of 11.25 degrees, 3 cards +const tileOf = (url: string) => Number(/-t(\d\d)-/.exec(url)?.[1]); + +/** A decoder that keeps count: which bitmaps are open, which tiles are being decoded at once. */ +const rig = (fail: (url: string) => boolean = () => false, missing: (url: string) => boolean = () => false) => { + const fetched: string[] = []; + const bitmaps: { url: string; closed: boolean; close: () => void }[] = []; + let inFlight = new Map(); + let mostTiles = 0; + let clock = 0; + const fetchBlob = vi.fn(async (url: string, _signal?: AbortSignal) => { + fetched.push(url); + if (missing(url)) throw new NotFound('ridge: 404'); + if (fail(url)) throw new Error('ridge: 503'); + return { url } as unknown as Blob; + }); + const decode = vi.fn(async (blob: Blob) => { + const { url } = blob as unknown as { url: string }; + const t = tileOf(url); + inFlight.set(t, (inFlight.get(t) ?? 0) + 1); + mostTiles = Math.max(mostTiles, inFlight.size); + await new Promise((r) => setTimeout(r, 0)); + inFlight.set(t, (inFlight.get(t) ?? 1) - 1); + if (inFlight.get(t) === 0) inFlight.delete(t); + const b = { url, closed: false, close: () => (b.closed = true) }; + bitmaps.push(b); + return b as unknown as ImageBitmap; + }); + const canvases: { tile: number; card: number; width: number; height: number }[] = []; + const lighter = (): Lighter & { light: Mock<[CardBitmaps, number, number], HTMLCanvasElement> } => ({ + lost: false, + release: vi.fn(), + light: vi.fn((_b: CardBitmaps, tile: number, card: number) => { + const c = { tile, card, width: 202, height: 100 }; + canvases.push(c); + return c as unknown as HTMLCanvasElement; + }), + }); + return { + fetched, + bitmaps, + fetchBlob, + decode, + canvases, + lighter, + mostTiles: () => mostTiles, + now: () => clock, + tick: (ms: number) => void (clock += ms), + }; +}; + +const urlsOfTiles = (tiles: number[]) => + tiles.flatMap((t) => + manifest.tiles[t].flatMap((e) => (e ? [`/d/${e.colour}`, `/d/${e.geometry}`] : [])) + ); +const arc72 = (centre: number) => ({ fromDeg: centre - 36, toDeg: centre + 36 }); + +afterEach(() => { + vi.useRealTimers(); +}); + +describe('createBackdrop', () => { + it('fetches nothing until it is asked, and then the files of the tiles of the arc and one tile beyond it, straight, and no others', async () => { + const r = rig(); + const bd = createBackdrop(manifest, sky, { ...r, lighter: r.lighter }); + expect(r.fetchBlob).not.toHaveBeenCalled(); + await bd.ensure(arc72(180)); + const want = residentTiles(manifest.view, 180, 36 + LOAD_MARGIN_TILES * 11.25).map((t) => t.tile); + expect(want).toHaveLength(10); + expect([...r.fetched].sort()).toEqual(urlsOfTiles(want).sort()); + expect(bd.litTiles().map((t) => t.tile).sort((a, b) => a - b)).toEqual( + want.flatMap((t) => manifest.tiles[t].flatMap((e, card) => (e ? [t] : []))).sort((a, b) => a - b) + ); + r.bitmaps.forEach((b) => expect(b.closed).toBe(true)); + }); + + it('lights each card of a tile that holds it, naming the tile and the card, and leaves a card the tile lacks out', async () => { + const r = rig(); + const lighter = r.lighter(); + const bd = createBackdrop(manifest, sky, { ...r, lighter: () => lighter }); + await bd.ensure({ fromDeg: 208, toDeg: 209 }); + const calls = lighter.light.mock.calls.map((c) => [c[1], c[2]]); + // Tile 17 holds three cards; tile 18 (18 % 4 = 2) holds only two: card 2 is absent there. + expect(calls).toContainEqual([17, 2]); + expect(calls).toContainEqual([18, 1]); + expect(calls).not.toContainEqual([18, 2]); + const colourOf = (c: unknown[]) => (c[0] as { colour: { url: string } }).colour.url; + expect(lighter.light.mock.calls.every((c) => colourOf(c).includes(`-t${String(c[1]).padStart(2, '0')}-`))).toBe(true); + }); + + it('decodes with straight alpha and no colour management by default', async () => { + const made: unknown[] = []; + vi.stubGlobal( + 'createImageBitmap', + vi.fn(async (_b: unknown, opts: unknown) => { + made.push(opts); + return { close: () => undefined }; + }) + ); + const r = rig(); + const bd = createBackdrop(manifest, sky, { fetchBlob: r.fetchBlob, lighter: r.lighter }); + await bd.ensure({ fromDeg: 0, toDeg: 1 }); + expect(made.length).toBeGreaterThan(0); + made.forEach((o) => expect(o).toEqual({ premultiplyAlpha: 'none', colorSpaceConversion: 'none' })); + vi.unstubAllGlobals(); + }); + + it('decodes one tile at a time', async () => { + const r = rig(); + const bd = createBackdrop(manifest, sky, { ...r, lighter: r.lighter }); + await bd.ensure(arc72(100)); + expect(r.decode).toHaveBeenCalled(); + expect(r.mostTiles()).toBe(1); + }); + + it('sweeping the heading through 360 degrees fetches each tile once on the way and never holds more than the baker counted', async () => { + const r = rig(); + const bd = createBackdrop(manifest, sky, { ...r, lighter: r.lighter }); + const N = runTiles(manifest.view, HFOV_MAX_DEG, manifest.camera.rMaxM, 1000); + const per = new Map(); + let most = 0; + for (let h = 0; h <= 360; h += 6) { + await bd.ensure(arc72(h)); + most = Math.max(most, new Set(bd.litTiles().map((t) => t.tile)).size); + } + // Card 0 is in every tile: its colour file counts a tile's fetches. + for (const u of r.fetched) { + if (u.includes('card-0-') && u.endsWith('colour.webp')) per.set(tileOf(u), (per.get(tileOf(u)) ?? 0) + 1); + } + expect(per.size).toBe(32); + // The tiles round north are held at the start and wanted again at the end of the turn: those two fetches aside, every tile came once. + const start = new Set(residentTiles(manifest.view, 0, 36 + LOAD_MARGIN_TILES * 11.25).map((t) => t.tile)); + for (const [t, n] of per) expect(n, `tile ${t}`).toBe(start.has(t) ? 2 : 1); + expect(most).toBeLessThanOrEqual(N); + expect(most).toBeLessThanOrEqual( + Math.ceil((72 + 2 * KEEP_MARGIN_TILES * 11.25) / 11.25) + 1 + ); + }); + + it('lets go of the tiles beyond the arc and two tiles of margin, and makes nothing twice that it still holds', async () => { + const r = rig(); + const lighter = r.lighter(); + const bd = createBackdrop(manifest, sky, { ...r, lighter: () => lighter }); + await bd.ensure(arc72(180)); + const first = bd.litTiles(); + const lit = lighter.light.mock.calls.length; + await bd.ensure(arc72(180)); // the same arc again: nothing is made + expect(lighter.light.mock.calls.length).toBe(lit); + await bd.ensure(arc72(0)); // the far side of the ring: everything held before is let go + first.forEach((t) => expect(t.canvas.width).toBe(0)); + const keep = new Set( + residentTiles(manifest.view, 0, 36 + KEEP_MARGIN_TILES * 11.25).map((t) => t.tile) + ); + expect(bd.litTiles().length).toBeGreaterThan(0); + bd.litTiles().forEach((t) => { + expect(keep.has(t.tile)).toBe(true); + expect(t.canvas.width).toBe(202); + }); + }); + + it('a tile that fails is absent, not an error, and is made at the next ensure', async () => { + let broken = true; + const r = rig((u) => broken && tileOf(u) === 16 && u.includes('card-1-')); + const lighter = r.lighter(); + const bd = createBackdrop(manifest, sky, { ...r, lighter: () => lighter }); + await expect(bd.ensure({ fromDeg: 180, toDeg: 181 })).resolves.toBeUndefined(); + expect(bd.litTiles().some((t) => t.tile === 16)).toBe(false); // a tile is lit whole or not at all + expect(bd.litTiles().some((t) => t.tile === 15)).toBe(true); + r.bitmaps.forEach((b) => expect(b.closed).toBe(true)); + broken = false; + r.tick(RETRY_FIRST_MS); // after its pause + await bd.ensure({ fromDeg: 180, toDeg: 181 }); + expect(bd.litTiles().filter((t) => t.tile === 16).map((t) => t.card).sort()).toEqual([0, 1, 2]); + }); + + it('a lighting pass that throws is a failed tile too', async () => { + const r = rig(); + const lighter = r.lighter(); + lighter.light.mockImplementation(() => { + throw new Error('no 2D context'); + }); + const bd = createBackdrop(manifest, sky, { ...r, lighter: () => lighter }); + await expect(bd.ensure({ fromDeg: 0, toDeg: 1 })).resolves.toBeUndefined(); + expect(bd.litTiles()).toEqual([]); + r.bitmaps.forEach((b) => expect(b.closed).toBe(true)); + }); + + it('is made only where the cards can be lit: a lighter that throws is the caller to answer for', () => { + const r = rig(); + expect(() => + createBackdrop(manifest, sky, { + ...r, + lighter: () => { + throw new Error('ridge: no WebGL2'); + }, + }) + ).toThrow(/WebGL2/); + }); + + it('makes another lighter after the context is lost, and releases the spent one', async () => { + const r = rig(); + const first = r.lighter(); + const second = r.lighter(); + const make = vi.fn().mockReturnValueOnce(first).mockReturnValueOnce(second); + const bd = createBackdrop(manifest, sky, { ...r, lighter: make }); + await bd.ensure({ fromDeg: 0, toDeg: 1 }); + expect(first.light).toHaveBeenCalled(); + (first as { lost: boolean }).lost = true; + await bd.ensure({ fromDeg: 180, toDeg: 181 }); + expect(make).toHaveBeenCalledTimes(2); + expect(first.release).toHaveBeenCalled(); + expect(second.light).toHaveBeenCalled(); + }); + + it('takes the newest arc when asked again mid-pass, and answers every caller once everything it could make is made', async () => { + const r = rig(); + const bd = createBackdrop(manifest, sky, { ...r, lighter: r.lighter }); + const a = bd.ensure(arc72(40)); + const b = bd.ensure(arc72(220)); + await Promise.all([a, b]); + const held = new Set(bd.litTiles().map((t) => t.tile)); + residentTiles(manifest.view, 220, 36 + LOAD_MARGIN_TILES * 11.25).forEach((t) => expect(held.has(t.tile)).toBe(true)); + }); + + it('tells a listener of each tile as it is made, not of a tile that failed, and no longer once it stops listening or the backdrop is disposed', async () => { + const r = rig((url) => tileOf(url) === 17); + const bd = createBackdrop(manifest, sky, { ...r, lighter: r.lighter }); + const seen: number[] = []; + const off = bd.onTile(() => seen.push(bd.litTiles().length)); + await bd.ensure({ fromDeg: 180, toDeg: 181 }); // tiles 15 to 17 and the margin: 17 fails + const made = new Set(bd.litTiles().map((t) => t.tile)); + expect(made.has(17)).toBe(false); + expect(seen).toHaveLength(made.size); // one call per tile held, each with its tile already held + seen.forEach((n, i) => expect(n).toBeGreaterThan(i)); + off(); + await bd.ensure({ fromDeg: 0, toDeg: 1 }); + expect(seen).toHaveLength(made.size); + const late = vi.fn(); + bd.onTile(late); + bd.dispose(); + await bd.ensure({ fromDeg: 100, toDeg: 101 }); + expect(late).not.toHaveBeenCalled(); + }); + + it('disposes: the canvases are dropped, the lighting context released, and a later ensure does nothing', async () => { + const r = rig(); + const lighter = r.lighter(); + const bd = createBackdrop(manifest, sky, { ...r, lighter: () => lighter }); + await bd.ensure({ fromDeg: 0, toDeg: 1 }); + const lit = bd.litTiles().map((t) => t.canvas); + expect(lit.length).toBeGreaterThan(0); + bd.dispose(); + bd.dispose(); + expect(lighter.release).toHaveBeenCalledTimes(1); + lit.forEach((c) => expect(c.width).toBe(0)); + expect(bd.litTiles()).toEqual([]); + const n = r.fetched.length; + await bd.ensure({ fromDeg: 100, toDeg: 101 }); + expect(r.fetched).toHaveLength(n); + }); + + it('asks for the tile under the view first and then outward, not outward from the middle of the sweep', async () => { + const r = rig(); + const bd = createBackdrop(manifest, sky, { ...r, lighter: r.lighter }); + // The sweep spans 144 to 216 degrees; the view is at its start, in tile 13 (146.25 to 157.5). + await bd.ensure({ fromDeg: 144, toDeg: 216 }, { fromDeg: 150, toDeg: 152 }); + const order = [...new Set(r.fetched.map(tileOf))]; + expect(order[0]).toBe(13); + const dist = (t: number) => Math.abs(t * 11.25 + 5.625 - 151); + expect(order.map(dist)).toEqual([...order.map(dist)].sort((a, b) => a - b)); + // Without a view it is outward from the middle of the arc, as before. + const r2 = rig(); + const bd2 = createBackdrop(manifest, sky, { ...r2, lighter: r2.lighter }); + await bd2.ensure({ fromDeg: 144, toDeg: 216 }); + expect([15, 16]).toContain(tileOf(r2.fetched[0])); // the two tiles either side of 180 + }); + + it('asks for the files of the tiles of an arc a few at a time, not one after another and not all at once', async () => { + let active = 0; + let most = 0; + const r = rig(); + const fetchBlob = vi.fn(async (url: string) => { + active += 1; + most = Math.max(most, active); + await new Promise((go) => setTimeout(go, 5)); + active -= 1; + return { url } as unknown as Blob; + }); + const bd = createBackdrop(manifest, sky, { ...r, fetchBlob, lighter: r.lighter }); + await bd.ensure(arc72(180)); // ten tiles of up to six files each + expect(most).toBeGreaterThan(1); // the files are not asked for one after another + expect(most).toBe(FETCH_PARALLEL); // and the pipe is kept full while there is more to ask, and no fuller + expect(bd.litTiles().length).toBeGreaterThan(20); + }); + + it('keeps the cap while the arc changes under it: aborted passes hand their slots on, and a pass begun at once takes none of them', async () => { + vi.useFakeTimers(); + let live = 0; + let most = 0; + const r = rig(); + const fetchBlob = vi.fn( + (url: string, signal?: AbortSignal) => + new Promise((resolve, reject) => { + live += 1; + most = Math.max(most, live); + const timer = setTimeout(() => { + live -= 1; + resolve({ url } as unknown as Blob); + }, 300); + signal?.addEventListener('abort', () => { + clearTimeout(timer); + live -= 1; + reject(new Error('aborted')); + }); + }) + ); + const bd = createBackdrop(manifest, sky, { ...r, fetchBlob, lighter: r.lighter }); + for (let i = 0; i < 60; i += 1) { + void bd.ensure({ fromDeg: 100 + i * 2, toDeg: 180 + i * 2 }); // a turning view: a new arc every half second, each one aborting the last + await vi.advanceTimersByTimeAsync(500); + } + expect(fetchBlob.mock.calls.length).toBeGreaterThan(FETCH_PARALLEL * 3); // the loader worked the whole time + expect(most).toBeLessThanOrEqual(FETCH_PARALLEL); + }); + + it('gives up on a request that never answers, draws absence and goes on, and aborts it', async () => { + vi.useFakeTimers(); + const r = rig(); + const signals: AbortSignal[] = []; + const fetchBlob = vi.fn((url: string, signal?: AbortSignal) => { + if (tileOf(url) === 17) { + signals.push(signal as AbortSignal); + return new Promise(() => undefined); // never settles, and ignores its signal + } + return Promise.resolve({ url } as unknown as Blob); + }); + const bd = createBackdrop(manifest, sky, { ...r, fetchBlob, lighter: r.lighter }); + const done = bd.ensure({ fromDeg: 200, toDeg: 201 }); + await vi.advanceTimersByTimeAsync(FETCH_TIMEOUT_MS + 10); + await done; + expect(signals.length).toBeGreaterThan(0); + signals.forEach((s) => expect(s.aborted).toBe(true)); + expect(bd.litTiles().some((t) => t.tile === 17)).toBe(false); + expect(bd.litTiles().some((t) => t.tile === 16 || t.tile === 18)).toBe(true); + }); + + it('does not ask again at once for a tile that failed: the pause doubles to a cap, so a tile that keeps failing is a few requests a minute', async () => { + const r = rig((u) => tileOf(u) === 19); + const bd = createBackdrop(manifest, sky, { ...r, lighter: r.lighter }); + const tile19 = () => + r.fetched.filter((u) => tileOf(u) === 19 && u.includes('card-0-') && u.endsWith('colour.webp')).length; + await bd.ensure({ fromDeg: 215, toDeg: 216 }); + expect(tile19()).toBe(1); + // The scene asks every half second for a minute: the broken tile is asked for about as often as its pauses allow. + for (let t = 0; t < 120; t += 1) { + r.tick(500); + await bd.ensure({ fromDeg: 215, toDeg: 216 }); + } + expect(tile19()).toBeGreaterThan(3); + expect(tile19()).toBeLessThanOrEqual(8); // 1 s, 2 s, 4 s, 8 s, 16 s, 32 s: not 121 + expect(RETRY_MAX_MS).toBeGreaterThanOrEqual(32_000); + expect(bd.litTiles().some((t) => t.tile === 19)).toBe(false); + }); + + describe('the loader asks again on its own', () => { + /** Nothing waits on a timer but the retry: files and decodes settle at once. */ + const quick = (fail: (url: string) => boolean) => { + const r = rig(fail); + const decode = vi.fn(async (blob: Blob) => ({ url: (blob as unknown as { url: string }).url, close: () => undefined }) as unknown as ImageBitmap); + return { r, deps: { ...r, decode, lighter: r.lighter } }; + }; + const tile = (r: ReturnType, t: number) => r.fetched.filter((u) => tileOf(u) === t && u.includes('card-1-') && u.endsWith('colour.webp')).length; + + it('a tile that failed is asked for again at the end of its pause with no one asking, and the listener hears it arrive', async () => { + vi.useFakeTimers(); + let broken = true; + const { r, deps } = quick((u) => broken && tileOf(u) === 16 && u.includes('card-1-')); + const bd = createBackdrop(manifest, sky, deps); + const heard = vi.fn(); + bd.onTile(heard); + await bd.ensure({ fromDeg: 180, toDeg: 181 }); // the only ask: a still has no timer to make another + expect(bd.litTiles().some((t) => t.tile === 16)).toBe(false); + const arrived = heard.mock.calls.length; + broken = false; + r.tick(RETRY_FIRST_MS - 1); + await vi.advanceTimersByTimeAsync(RETRY_FIRST_MS - 1); + expect(tile(r, 16)).toBe(1); // not before its pause + r.tick(1); + await vi.advanceTimersByTimeAsync(1); + expect(bd.litTiles().filter((t) => t.tile === 16).map((t) => t.card).sort()).toEqual([0, 1, 2]); + expect(heard.mock.calls.length).toBe(arrived + 1); + const n = r.fetched.length; + r.tick(10 * RETRY_MAX_MS); + await vi.advanceTimersByTimeAsync(10 * RETRY_MAX_MS); + expect(r.fetched.length).toBe(n); // nothing is left to ask for + bd.dispose(); + }); + + it('keeps asking, on a pause that doubles, while the arc wants the tile, and stops when the arc has moved on or the backdrop is gone', async () => { + vi.useFakeTimers(); + const { r, deps } = quick((u) => tileOf(u) === 19); + const bd = createBackdrop(manifest, sky, deps); + await bd.ensure({ fromDeg: 215, toDeg: 216 }); + expect(tile(r, 19)).toBe(1); + for (let s = 0; s < 120; s += 1) { + r.tick(1000); + await vi.advanceTimersByTimeAsync(1000); + } + expect(tile(r, 19)).toBeGreaterThan(3); + expect(tile(r, 19)).toBeLessThanOrEqual(8); // 1 s, 2 s, 4 s, 8 s, 16 s, 32 s: a few a minute, not one a second + await bd.ensure({ fromDeg: 0, toDeg: 1 }); // the view has gone the other way: tile 19 is no longer wanted + const asked = tile(r, 19); + for (let s = 0; s < 300; s += 1) { + r.tick(1000); + await vi.advanceTimersByTimeAsync(1000); + } + expect(tile(r, 19)).toBe(asked); + await bd.ensure({ fromDeg: 215, toDeg: 216 }); + bd.dispose(); + const n = r.fetched.length; + r.tick(10 * RETRY_MAX_MS); + await vi.advanceTimersByTimeAsync(10 * RETRY_MAX_MS); + expect(r.fetched.length).toBe(n); // a disposed backdrop asks for nothing + }); + }); + + it('does not ask again for a file the server does not have: the tile is drawn with the cards that came', async () => { + const r = rig( + () => false, + (u) => tileOf(u) === 19 && u.includes('card-1-') + ); + const bd = createBackdrop(manifest, sky, { ...r, lighter: r.lighter }); + const tile19 = () => r.fetched.filter((u) => tileOf(u) === 19).length; + await bd.ensure({ fromDeg: 215, toDeg: 216 }); + const first = tile19(); + expect(first).toBeGreaterThan(0); + expect(bd.litTiles().filter((t) => t.tile === 19).map((t) => t.card)).toEqual([0, 2]); // card 1 is absent, the others are there + for (let t = 0; t < 40; t += 1) { + r.tick(5_000); + await bd.ensure({ fromDeg: 215, toDeg: 216 }); + } + expect(tile19()).toBe(first); // not once more while the tile stays + r.bitmaps.forEach((b) => expect(b.closed).toBe(true)); + }); + + it('gives up on a tile every file of which is gone, without a retry loop, and draws its neighbours', async () => { + const r = rig( + () => false, + (u) => tileOf(u) === 19 + ); + const bd = createBackdrop(manifest, sky, { ...r, lighter: r.lighter }); + await bd.ensure({ fromDeg: 215, toDeg: 216 }); + const n = r.fetched.length; + r.tick(RETRY_MAX_MS * 2); + await bd.ensure({ fromDeg: 215, toDeg: 216 }); + expect(r.fetched.length).toBe(n); + expect(bd.litTiles().some((t) => t.tile === 19)).toBe(false); + expect(bd.litTiles().some((t) => t.tile === 18)).toBe(true); + }); +}); diff --git a/src/app/features/scene/ridge/Backdrop.ts b/src/app/features/scene/ridge/Backdrop.ts new file mode 100644 index 00000000..13ef8d79 --- /dev/null +++ b/src/app/features/scene/ridge/Backdrop.ts @@ -0,0 +1,286 @@ +// The ridge cards the scene composes, lit, kept resident by tile: the one owner of which tiles of the ring are in memory. `ensure` is told the arc of +// azimuth the view is about to need; it fetches and decodes the tiles of that arc it does not hold, one tile at a time, lights each card of a tile +// (`lightCards.ts`, one lighter for the one sky this backdrop was made for) and drops the tiles beyond the arc and its margin. The files of the tiles to make +// are fetched a few at a time, each against a timeout. A tile that fails is a tile the scene draws as absence, asked for again by the loader itself after a growing +// pause, for as long as the arc last asked for wants it (whoever asked, a scene's timer or none: a still has no timer); a file the server says is not there (404) is +// not asked for again while its tile stays: the scene draws the cards of the tile that came. Nothing is thrown into the scene. +import type { RidgeManifest } from './manifest'; +import type { PhysicalSky } from './physicalSky'; +import { createLighter } from './lightCards'; +import type { CardBitmaps, Lighter } from './lightCards'; +import { KEEP_MARGIN_TILES, LOAD_MARGIN_TILES, residentTiles } from './ring'; + +/** A range of unwrapped compass azimuth, degrees, `fromDeg <= toDeg`. */ +export interface Arc { + fromDeg: number; + toDeg: number; +} + +/** One card of one tile, lit: its pixels premultiplied by the card's alpha, `tileW + 2` columns by the band's rows. */ +export interface LitTile { + tile: number; + card: number; + canvas: HTMLCanvasElement; +} + +export interface Backdrop { + manifest: RidgeManifest; + /** + * Hold the tiles of `arc` and one tile beyond it each side; let go of those past two tiles. Resolves when every tile it could make is made. They are asked for + * and made nearest first to `first`, the arc the view shows now (the middle of `arc` when absent), so what is on screen comes before what the sweep reaches later. + */ + ensure(arc: Arc, first?: Arc): Promise; + /** Every card of every tile held, in no order. */ + litTiles(): readonly LitTile[]; + /** Hear each tile as it is made and held, however late (a still scene has no timer of its own and draws only what it held); not a tile that failed. Returns the way to stop. */ + onTile(cb: () => void): () => void; + /** Let go of everything, the lighting context included. Idempotent. */ + dispose(): void; +} + +export interface BackdropDeps { + /** Rejects with `NotFound` when the server has no such file, with anything else for a failure that may pass. `signal` aborts it. */ + fetchBlob: (url: string, signal?: AbortSignal) => Promise; + decode: (blob: Blob) => Promise; + lighter: (manifest: RidgeManifest, sky: PhysicalSky) => Lighter; + /** The clock (ms) the pauses between a tile's attempts run on. */ + now: () => number; +} + +/** A file the server answered 404 or 410 for: asking again will not make it appear. */ +export class NotFound extends Error {} + +/** Requests in flight at once, over all tiles; how long one may take; the pause before a failed tile is asked for again (doubled each failure, to the cap). */ +export const FETCH_PARALLEL = 6; +export const FETCH_TIMEOUT_MS = 15_000; +export const RETRY_FIRST_MS = 1_000; +export const RETRY_MAX_MS = 60_000; + +const fetchBlob = async (url: string, signal?: AbortSignal): Promise => { + const res = await fetch(url, { signal }); + if (res.status === 404 || res.status === 410) throw new NotFound(`ridge: ${url} answered ${res.status}`); + if (!res.ok) throw new Error(`ridge: ${url} answered ${res.status}`); + return res.blob(); +}; + +/** Straight alpha and the file's own values: the colour file's alpha is coverage and the geometry file's channels are data, so neither may be premultiplied or colour-managed. */ +const decode = (blob: Blob): Promise => + createImageBitmap(blob, { premultiplyAlpha: 'none', colorSpaceConversion: 'none' }); + +/** + * A backdrop for `sky`. Throws at once when the cards cannot be lit (no WebGL2, a shader that will not link): the caller makes the sky-only scene. + * Nothing is fetched until the first `ensure`. + */ +export function createBackdrop( + manifest: RidgeManifest, + sky: PhysicalSky, + deps: Partial = {} +): Backdrop { + const get = deps.fetchBlob ?? fetchBlob; + const open = deps.decode ?? decode; + const makeLighter = deps.lighter ?? createLighter; + const now = deps.now ?? (() => (typeof performance !== 'undefined' ? performance.now() : Date.now())); + const { view } = manifest; + const tileDeg = 360 / view.tiles; + let lighter = makeLighter(manifest, sky); + const held = new Map(); + /** Tiles that failed, when they may be asked for again and the pause after the next failure. */ + const failed = new Map(); + const heard = new Set<() => void>(); + let disposed = false; + let running: Promise | null = null; + let want: { arc: Arc; first?: Arc } | null = null; + /** The arc last asked for: what the loader keeps its tiles for and retries for. */ + let wanted: { arc: Arc; first?: Arc } | null = null; + /** Ask for the arc wanted once more: a pass ends in `schedule`, which is defined before the backdrop that can be asked. */ + let askAgain: () => void = () => undefined; + let retry: ReturnType | undefined; + /** The pass that is on the wire: dispose gives up its requests, as a newer arc does. */ + let current: AbortController | null = null; + + const drop = (tile: number) => { + held.get(tile)?.forEach((t) => { + t.canvas.width = 0; + t.canvas.height = 0; + }); + held.delete(tile); + }; + + // At most FETCH_PARALLEL requests at once over every tile, each with its own timeout (the signal is passed on, and a fetch that ignores it is still given up on). + // A slot is handed straight to the next waiter, so `active` never dips for a request issued in between to slip into; it falls only when nobody waits. + let active = 0; + const queue: (() => void)[] = []; + const request = async (url: string, signal: AbortSignal): Promise => { + if (active < FETCH_PARALLEL) active += 1; + else await new Promise((go) => queue.push(go)); + try { + if (signal.aborted) throw new Error('ridge: aborted'); + return await new Promise((resolve, reject) => { + const ctl = new AbortController(); + const stop = () => { + ctl.abort(); + reject(new Error(`ridge: ${url} ${signal.aborted ? 'aborted' : 'timed out'}`)); + }; + const timer = setTimeout(stop, FETCH_TIMEOUT_MS); + signal.addEventListener('abort', stop, { once: true }); + get(url, ctl.signal).then(resolve, reject).finally(() => { + clearTimeout(timer); + signal.removeEventListener('abort', stop); + }); + }); + } finally { + const next = queue.shift(); + if (next) next(); + else active -= 1; + } + }; + + /** The files of a tile, each settled on its own: a blob, or what became of it (`gone`: the server has none; `failed`: it may pass). */ + type Fetched = { blob: Blob } | 'gone' | 'failed'; + async function fetchTile(tile: number, signal: AbortSignal): Promise<{ card: number; files: Fetched[] }[]> { + const cards = manifest.tiles[tile].flatMap((e, card) => (e ? [{ e, card }] : [])); + return Promise.all( + cards.map(async ({ e, card }) => ({ + card, + files: await Promise.all( + [e.colour, e.geometry].map( + (f): Promise => + request(`${manifest.dir}${f}`, signal).then( + (blob) => ({ blob }), + (err: unknown) => (err instanceof NotFound ? 'gone' : 'failed') + ) + ) + ), + })) + ); + } + + /** + * Decode and light what a tile's fetch brought, one card at a time, and hold the tile. A card with a file the server does not have is left out (the scene + * draws the others); a tile with any file that failed otherwise is not kept (it is lit whole or not at all) and is asked for again after a pause. + */ + async function make(tile: number, fetched: { card: number; files: Fetched[] }[]): Promise { + const made: LitTile[] = []; + const bitmaps: ImageBitmap[] = []; + try { + if (fetched.some((f) => f.files.includes('failed'))) throw new Error('ridge: a file of the tile failed'); + if (lighter.lost) { + lighter.release(); + lighter = makeLighter(manifest, sky); + } + for (const { card, files } of fetched) { + if (files.includes('gone')) continue; + const [colour, geometry] = await Promise.all( + files.map(async (f) => { + const b = await open((f as { blob: Blob }).blob); + bitmaps.push(b); + return b; + }) + ); + if (disposed) return; + made.push({ tile, card, canvas: lighter.light({ colour, geometry }, tile, card) }); + } + held.set(tile, made); + failed.delete(tile); + heard.forEach((cb) => cb()); + } catch { + made.forEach((t) => (t.canvas.width = 0)); + const pause = Math.min(RETRY_MAX_MS, (failed.get(tile)?.pause ?? RETRY_FIRST_MS / 2) * 2); + failed.set(tile, { until: now() + pause, pause }); + } finally { + bitmaps.forEach((b) => b.close?.()); + } + } + + async function pass(arc: Arc, first?: Arc): Promise { + const centre = (arc.fromDeg + arc.toDeg) / 2; + const from0 = first ? (first.fromDeg + first.toDeg) / 2 : centre; + const half = (arc.toDeg - arc.fromDeg) / 2; + const near = residentTiles(view, centre, half + LOAD_MARGIN_TILES * tileDeg); + const keep = new Set( + residentTiles(view, centre, half + KEEP_MARGIN_TILES * tileDeg).map((r) => r.tile) + ); + [...held.keys()].filter((t) => !keep.has(t)).forEach(drop); + // The tile under the view first, then outward along the sweep: what the view needs now comes before what it needs next. + const from = (r: { tile: number; turn: number }) => r.turn * 360 + r.tile * tileDeg + tileDeg / 2; + const order = [...near] + .sort((a, b) => Math.abs(from(a) - from0) - Math.abs(from(b) - from0)) + .map((r) => r.tile) + .filter((t) => !held.has(t) && (failed.get(t)?.until ?? 0) <= now()); + // Every tile's files are asked for at once (the requests queue to FETCH_PARALLEL, in this order) and made one tile at a time as they arrive. + const stop = new AbortController(); + current = stop; + try { + const asked = order.map((tile) => fetchTile(tile, stop.signal)); + for (const [i, tile] of order.entries()) { + const fetched = await asked[i]; + if (disposed) return; + await make(tile, fetched); + // A newer arc is waiting: take it up now, with this tile made, instead of finishing an arc the view has left. + if (want && held.has(tile)) return; + } + } finally { + stop.abort(); // what is still on the wire is for an arc the view has left + if (current === stop) current = null; + } + } + + /** When the arc wanted holds a tile that failed, ask for it again at the end of its pause: the loader's own retry, the same for every tier. */ + function schedule(): void { + clearTimeout(retry); + retry = undefined; + if (disposed || !wanted) return; + const { arc } = wanted; + const half = (arc.toDeg - arc.fromDeg) / 2 + LOAD_MARGIN_TILES * tileDeg; + const due = residentTiles(view, (arc.fromDeg + arc.toDeg) / 2, half) + .filter((r) => !held.has(r.tile) && failed.has(r.tile)) + .map((r) => (failed.get(r.tile) as { until: number }).until); + if (!due.length) return; + retry = setTimeout(() => { + retry = undefined; + askAgain(); + }, Math.max(0, Math.min(...due) - now())); + } + + async function loop(): Promise { + while (want && !disposed) { + const { arc, first } = want; + want = null; + await pass(arc, first); + } + schedule(); + } + + const api: Backdrop = { + manifest, + ensure(arc, first) { + if (disposed) return Promise.resolve(); + wanted = { arc, first }; + want = wanted; + running ??= loop().finally(() => { + running = null; + }); + return running; + }, + litTiles: () => [...held.values()].flat(), + onTile(cb) { + heard.add(cb); + return () => heard.delete(cb); + }, + dispose() { + if (disposed) return; + disposed = true; + heard.clear(); + wanted = null; + want = null; + clearTimeout(retry); + current?.abort(); // a scene that did not wait for its tiles, or was replaced, leaves nothing asking for them + [...held.keys()].forEach(drop); + lighter.release(); + }, + }; + askAgain = () => { + if (wanted) api.ensure(wanted.arc, wanted.first).catch(() => undefined); + }; + return api; +} diff --git a/src/app/features/scene/ridge/Ridge.test.ts b/src/app/features/scene/ridge/Ridge.test.ts index cb24f04b..884c3423 100644 --- a/src/app/features/scene/ridge/Ridge.test.ts +++ b/src/app/features/scene/ridge/Ridge.test.ts @@ -1,24 +1,33 @@ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { createRidgeScene } from './Ridge'; -import { bakeSlice, BakeParams, layerPaint } from './ridgeBake'; +import { createRidgeScene, RESIDENCY_MS } from './Ridge'; import { valueNoise, hash2 } from './noise'; import { FrameSampler, frameStats, SLOW_P95_MS, WARMUP_FRAMES, WINDOW_MS } from './probe'; -import { - AERIAL, - LAYERS, - edgeBlur, - hazeColour, - layerColour, - layerSize, - profile, - ridgeY, - scatterAlpha, - transmittance, -} from './ridgeWorld'; -import { skyColours, SkyColours } from './skyColour'; -import { makeStars } from './stars'; -import { makePhysicalSky } from './physicalSky'; +import type { SkyColours } from './skyColour'; +import { nightBodies } from './nightBodies'; +import { sunAt } from './sunAt'; +import { makePhysicalSky, paintSky as paintPhysicalSky } from './physicalSky'; +import { sunOfBand } from './skyTestkit'; import { startBackgroundScene } from '../index'; +import { parseIndex, parseManifest } from './manifest'; +import { ELSEWHERE_VIEW, wireManifest } from './manifest.fixture'; +import type { Arc, Backdrop, LitTile } from './Backdrop'; +import type { Mock } from 'vitest'; +import { cardArc, cardPose, FALLBACK_VIEW, HFOV_MAX_DEG, maxSpeed, offsetRange, SEGMENT_S, windowFor } from './view'; +import { LATENESS_S, plateCamera, plateSize, SLACK_MIN_DEG, slackFor } from './skyTurn'; +import { ringAzimuth, sunColumns, sunInColumn } from './lightCards'; +import { norm, residentTiles } from './ring'; +import { anchor, hold, poseAt, resetHeading, settledAt, STAGE_MS } from './heading'; +import { effectiveMode, getCamera, isHeld, resetCamera, setCamera } from '../cameraState'; + +/** The two stages of the ease of a mode pick (the angle, then the offset, or the other way round). */ +const EASE_MS = 2 * STAGE_MS; +/** A card's pose as the heading owner has the view at `t`: what the rig lays the card out from. */ +const posed = (m: Parameters[0], card: number, t: number, w: Parameters[5]) => { + const p = poseAt(t); + return cardPose(m, card, p.h, p.phi, p.r, w); +}; describe('noise', () => { it('is deterministic and in [0, 1)', () => { @@ -36,111 +45,6 @@ describe('noise', () => { }); }); -describe('ridge profile', () => { - it('stays in [0, 1] for any world-x, negative and far included, and layers differ', () => { - for (const spec of LAYERS) { - for (let i = -300; i < 300; i += 7) { - for (const off of [0, 1234.5, 98765.25]) { - const p = profile(spec, i / 50 + off); - expect(p).toBeGreaterThanOrEqual(0); - expect(p).toBeLessThanOrEqual(1); - } - } - } - expect(profile(LAYERS[0], 0.3)).not.toBeCloseTo(profile(LAYERS[1], 0.3), 3); - }); - - it('ridge tops lie inside the layer band', () => { - const size = layerSize(400, 800, 1); - for (const spec of LAYERS) { - for (let x = -500; x < 5 * size.period; x += 17) { - const y = ridgeY(spec, x / size.period, size.height, 800); - expect(y).toBeGreaterThanOrEqual(0); - expect(y).toBeLessThanOrEqual(size.height); - } - } - }); - - it('layers get darker and slower toward the viewer, and their sizes are integers', () => { - const sky = skyColours(); - const lum = (c: readonly number[]) => c[0] + c[1] + c[2]; - for (let i = 1; i < LAYERS.length; i += 1) { - expect(lum(layerColour(LAYERS[i], sky))).toBeLessThan(lum(layerColour(LAYERS[i - 1], sky))); - expect(LAYERS[i].seconds).toBeLessThan(LAYERS[i - 1].seconds); - } - for (const [w, h, s] of [ - [393, 851, 2], - [1280, 720, 1], - [412.5, 915.3, 2], - ] as const) { - const z = layerSize(w, h, s); - expect( - Number.isInteger(z.period) && Number.isInteger(z.chunk) && Number.isInteger(z.height) - ).toBe(true); - expect(z.chunk).toBeGreaterThan(z.period); - } - }); -}); - -describe('aerial perspective', () => { - const sky = skyColours(); - const lum = (c: readonly number[]) => 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]; - const chroma = (c: readonly number[]) => Math.max(...c) - Math.min(...c); - const far = LAYERS[0]; - const near = LAYERS[LAYERS.length - 1]; - - it('transmittance is Beer-Lambert in distance: 1 at the viewer, exp(-k d) behind, strictly falling', () => { - expect(transmittance(near)).toBe(1); - for (const l of LAYERS) - expect(transmittance(l)).toBeCloseTo(Math.exp(-AERIAL.extinction * (1 - l.depth)), 12); - for (let i = 1; i < LAYERS.length; i += 1) - expect(transmittance(LAYERS[i])).toBeGreaterThan(transmittance(LAYERS[i - 1])); - // two layers' optical depths add: T(a)*T(b) = T(a+b) - const t = (d: number) => Math.exp(-AERIAL.extinction * d); - expect(t(0.3) * t(0.4)).toBeCloseTo(t(0.7), 12); - }); - - it('the nearest layer is exactly the ground colour; the farthest tends to the haze', () => { - expect(layerColour(near, sky)).toEqual([...sky.ground]); - const h = hazeColour(sky); - const f = layerColour(far, sky); - const dist = (a: readonly number[], b: readonly number[]) => - Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]); - expect(dist(f, h)).toBeLessThan(dist(sky.ground, h) * (transmittance(far) + 0.2)); - }); - - it('colour moves toward the haze and loses chroma with distance, beyond what the mix alone does', () => { - const h = hazeColour(sky); - for (const l of LAYERS.slice(0, -1)) { - const t = transmittance(l); - const c = layerColour(l, sky); - const mixed = [0, 1, 2].map((i) => sky.ground[i] * t + h[i] * (1 - t)); - expect(chroma(c)).toBeLessThan(chroma(mixed)); - expect(Math.abs(lum(c) - lum(mixed))).toBeLessThan(1.5); // desaturation keeps luma - } - }); - - it('edge softening grows with distance and is zero at the viewer', () => { - expect(edgeBlur(near)).toBe(0); - for (let i = 1; i < LAYERS.length; i += 1) - expect(edgeBlur(LAYERS[i])).toBeLessThan(edgeBlur(LAYERS[i - 1])); - expect(edgeBlur(far)).toBeLessThanOrEqual(AERIAL.blurPx); - }); - - it('in-scatter is faint, grows with distance, is off without a sun, and never repeats', () => { - const az = 0.3; - const s = { ...sky, sunAzimuth: az }; - const lobe = (t: number) => scatterAlpha(far, s, t); - expect(lobe(az * 1.9)).toBeGreaterThan(lobe(az * 1.9 + 0.95)); - for (const period of [1, 1.9, 3.8, 5.7, 19]) - expect(Math.abs(lobe(0.7 + period) - lobe(0.7))).toBeGreaterThan(1e-4); - expect(lobe(az * 1.9)).toBeLessThanOrEqual(AERIAL.scatter); - expect(scatterAlpha(near, s, az)).toBe(0); - expect(scatterAlpha(LAYERS[1], s, az * 1.9)).toBeLessThan(scatterAlpha(far, s, az * 1.9)); - expect(scatterAlpha(far, { ...sky, sunAzimuth: undefined }, az)).toBe(0); - }); -}); - describe('frame sampler', () => { const feed = (s: FrameSampler, dt: number, frames: number, from = 0) => { let t = from; @@ -220,9 +124,16 @@ function fakeEl(tag = 'div') { this.children.push(c); return c; }, + insertBefore(c: any, before: any) { + c.parentElement = this; + this.children.splice(this.children.indexOf(before), 0, c); + return c; + }, animate: vi.fn((keyframes: any[], options: any) => { const a: any = { currentTime: 0, + /** The clock it was issued at (the mocked `performance.now`). */ + at: performance.now(), keyframes, options, onfinish: null, @@ -242,41 +153,62 @@ function fakeEl(tag = 'div') { }; return el; } -// A day sky has no stars, so the scene tests below see only the ridge loop; the dusk default +// A day sky has no stars, so the scene tests above see only the sky; the dusk default // carries stars and a twinkle overlay, tested in 'the starfield in the scene'. const DAY: SkyColours = { top: [96, 150, 220], mid: [150, 190, 235], horizon: [240, 215, 190], - ground: [7, 17, 26], - sunAzimuth: 0.3, }; const draws: string[] = []; -/** Every ImageData put on any canvas, in order. */ -const puts: any[] = []; -/** For every drawImage: the source canvas's width as it was at the moment of the draw. */ -const drawnWidths: number[] = []; -function ctx(withFilter = false) { +const images: unknown[][] = []; +/** Every RGBA grid the host canvas was painted from (the small canvas's putImageData). */ +const painted: Uint8ClampedArray[] = []; +/** Where each sun disc (its gradient's centre) and each body (an arc) was drawn into a sky canvas, in that canvas's device px, in paint order. */ +const suns: number[][] = []; +const arcs: number[][] = []; +/** Where each star of the twinkle overlay was drawn (its canvas's device px), in draw order; and what happens while a sky is painted (a paint takes time). */ +const twinks: number[][] = []; +let onPaint: (() => void) | undefined; +function ctx() { const c: any = { - globalCompositeOperation: 'source-over', createLinearGradient: () => ({ addColorStop: vi.fn() }), fillRect() { - draws.push(c.globalCompositeOperation === 'source-atop' ? 'scatter' : 'sky'); + draws.push('sky'); }, save() {}, - restore() {}, + restore() { + c.t = undefined; + c.k = undefined; + }, + translate(x: number, y: number) { + c.t = [x, y]; + }, + scale(k: number) { + c.k = k; + }, rect() {}, clip() {}, + rotate() {}, + ellipse() {}, createImageData: (w: number, h: number) => ({ data: new Uint8ClampedArray(w * h * 4), width: w, height: h, }), - putImageData: (img: any) => puts.push(img), + putImageData(img: { data: Uint8ClampedArray }) { + painted.push(img.data); + onPaint?.(); + }, beginPath() {}, moveTo() {}, - stroke() {}, - createRadialGradient: () => ({ addColorStop: vi.fn() }), + stroke() { + draws.push('line'); + }, + createRadialGradient: (x: number, y: number) => { + suns.push([x, y]); + return { addColorStop: vi.fn() }; + }, lineTo() {}, closePath() {}, // Stars: arc+fill is one draw. A context that has cleared a rect is the twinkle overlay's. @@ -284,21 +216,26 @@ function ctx(withFilter = false) { c.overlay = true; draws.push('clear'); }, - arc() { + arc(x: number, y: number) { draws.push(c.overlay ? 'twinkle' : 'star'); + if (!c.overlay) arcs.push([x, y]); + else twinks.push([x, y]); c.arcing = true; }, fill: () => { if (c.arcing) c.arcing = false; else draws.push('fill'); }, - drawImage: (src: any) => { - drawnWidths.push(src.width); - draws.push('flatten'); + drawImage(...a: unknown[]) { + draws.push('image'); + images.push( + Object.assign(a, { alpha: c.globalAlpha, op: c.globalCompositeOperation, t: c.t, k: c.k }) + ); }, + globalAlpha: 1, + globalCompositeOperation: 'source-over', set fillStyle(_v: unknown) {}, }; - if (withFilter) c.filter = 'none'; return c; } @@ -310,8 +247,12 @@ let search: string; beforeEach(() => { rafQueue = []; draws.length = 0; - puts.length = 0; - drawnWidths.length = 0; + images.length = 0; + painted.length = 0; + suns.length = 0; + arcs.length = 0; + twinks.length = 0; + onPaint = undefined; search = ''; motion = { matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() }; doc = Object.assign(new EventTarget(), { @@ -326,6 +267,7 @@ beforeEach(() => { innerWidth: 400, innerHeight: 800, matchMedia: () => motion, + clearTimeout, location: { get search() { return search; @@ -347,11 +289,6 @@ function host() { parent.appendChild(canvas); return { parent, canvas }; } -/** The rig holds one track per layer, farthest first; each track holds three chunk canvases. */ -const rigOf = (parent: any) => parent.children.find((c: any) => c.tag === 'div'); -const tracksOf = (parent: any): any[] => rigOf(parent).children; -const animsOf = (parent: any): any[] => - [rigOf(parent), ...tracksOf(parent)].flatMap((e: any) => e.anims); const runFrames = (dt: number, n: number, from = 0) => { let t = from; for (let i = 0; i < n && rafQueue.length; i += 1) { @@ -375,29 +312,29 @@ describe('createRidgeScene', () => { expect(createRidgeScene({ canvas, tier: 'full', sky: DAY })).toBeNull(); }); - it('bakes the sky once, and per layer only the first chunk before the first frame, at integer sizes, farthest first', () => { + it('paints the sky once at the viewport in canvas pixels and adds nothing to the page in a clear day', () => { const { parent, canvas } = host(); - const baked: any[] = []; - const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, onBake: (b) => baked.push(b) })!; + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY })!; expect(s).not.toBeNull(); - const tracks = tracksOf(parent); - expect(tracks).toHaveLength(LAYERS.length); - tracks.forEach((t: any, i: number) => { - expect(t.children).toHaveLength(3); - expect(t.animate).toHaveBeenCalledTimes(Number.isFinite(LAYERS[i].seconds) ? 1 : 0); - t.children.forEach((c: any) => { - expect(Number.isInteger(c.width) && Number.isInteger(c.height)).toBe(true); - expect(c.width).toBe(layerSize(400, 800, 2).chunk); - }); - }); - expect(baked.map((b) => [b.layer, b.chunk, b.first])).toEqual( - LAYERS.map((l) => [l.index, 0, true]) - ); + expect([canvas.width, canvas.height]).toEqual([800, 1600]); expect(draws.filter((d) => d === 'sky')).toHaveLength(1); + expect(parent.children).toEqual([canvas]); s.dispose(); }); - it('after the layers are painted, a smooth run draws nothing more and ends its rAF loop', () => { + it("paints the sky through the camera of the physical sky's own View, not a default one", () => { + const { canvas } = host(); + 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 } })!; + // a live sky is a plate about the heading, which with no ridge is the View's rest azimuth + const win = windowFor(ELSEWHERE_VIEW, 400, 800); + const want = paintPhysicalSky(physical, plateSize(win, 400, 800, 2, SLACK_MIN_DEG).cssW, 800, plateCamera(win, ELSEWHERE_VIEW.lookAzDeg, SLACK_MIN_DEG)); + expect(painted).toHaveLength(1); + expect(Array.from(painted[0])).toEqual(Array.from(want.data)); + s.dispose(); + }); + + it('a smooth run draws nothing more and ends its rAF loop', () => { const { canvas } = host(); const s = createRidgeScene({ canvas, tier: 'full', sky: DAY })!; const before = draws.length; @@ -407,53 +344,23 @@ describe('createRidgeScene', () => { s.dispose(); }); - it('p95 over 33 ms across 2 s flattens to a still image and removes the layers', () => { - const { parent, canvas } = host(); + it('p95 over 33 ms across 2 s settles to a still and reports it', () => { + const { canvas } = host(); const onProbe = vi.fn(); const s = createRidgeScene({ canvas, tier: 'full', onProbe, sky: DAY })!; runFrames(100, 100); - expect(draws.filter((d) => d === 'flatten')).toHaveLength(LAYERS.length); - expect(parent.children).toEqual([canvas]); expect(onProbe).toHaveBeenLastCalledWith(expect.objectContaining({ still: true })); expect(rafQueue).toHaveLength(0); s.dispose(); }); - it("'still' tier flattens immediately and never starts a loop", () => { + it("'still' tier never starts a loop", () => { const { parent, canvas } = host(); createRidgeScene({ canvas, tier: 'still' }); expect(parent.children).toEqual([canvas]); - expect(draws.filter((d) => d === 'flatten')).toHaveLength(LAYERS.length); expect(rafQueue).toHaveLength(0); }); - it('prefers-reduced-motion: layers are built but never played, and nothing is sampled', () => { - motion.matches = true; - const { canvas } = host(); - const s = createRidgeScene({ canvas, tier: 'full', sky: DAY })!; - const anims = animsOf(canvas.parentElement); - expect(anims.length).toBe(LAYERS.filter((l) => Number.isFinite(l.seconds)).length + 1); // one drift per drifting layer (the horizon does not) and the sway - expect(anims.every((a: any) => a.pause.mock.calls.length > 0)).toBe(true); - anims.forEach((a: any) => expect(a.play).not.toHaveBeenCalled()); - expect(rafQueue).toHaveLength(0); - s.dispose(); - }); - - it('pauses the drift when the tab is hidden and resumes when it is visible', () => { - const { parent, canvas } = host(); - const s = createRidgeScene({ canvas, tier: 'full', sky: DAY })!; - const anims = animsOf(parent); - anims.forEach((a: any) => a.pause.mockClear()); - doc.visibilityState = 'hidden'; - doc.dispatchEvent(new Event('visibilitychange')); - anims.forEach((a: any) => expect(a.pause).toHaveBeenCalled()); - anims.forEach((a: any) => a.play.mockClear()); - doc.visibilityState = 'visible'; - doc.dispatchEvent(new Event('visibilitychange')); - anims.forEach((a: any) => expect(a.play).toHaveBeenCalled()); - s.dispose(); - }); - it('?probe=1 keeps the rAF loop alive and shows median and p95', () => { search = '?probe=1'; const { parent, canvas } = host(); @@ -469,9 +376,8 @@ describe('createRidgeScene', () => { it('?probe=1 does nothing where the overlays are not allowed: no readout, the loop ends', () => { search = '?probe=1'; const { parent, canvas } = host(); - const before = parent.children.length; const s = createRidgeScene({ canvas, tier: 'full', sky: DAY })!; - expect(parent.children.length).toBe(before + 1); // the rig + expect(parent.children).toEqual([canvas]); runFrames(16.7, 300); expect(rafQueue.length).toBe(0); s.dispose(); @@ -485,31 +391,19 @@ describe('createRidgeScene', () => { (window as any).innerHeight = 0; const s = createRidgeScene({ canvas, tier: 'full', sky: DAY }); expect(s).not.toBeNull(); - expect(parent.children).toEqual([canvas]); expect(draws).toHaveLength(0); // Still zero: a resize does not paint either. window.dispatchEvent(new Event('resize')); await new Promise((r) => setTimeout(r, 300)); - expect(parent.children).toEqual([canvas]); + expect(draws).toHaveLength(0); (window as any).innerWidth = 400; (window as any).innerHeight = 800; window.dispatchEvent(new Event('resize')); await new Promise((r) => setTimeout(r, 300)); - expect(tracksOf(parent)).toHaveLength(LAYERS.length); expect(draws.filter((d) => d === 'sky')).toHaveLength(1); s!.dispose(); expect(parent.children).toEqual([canvas]); }); - - it('dispose cancels the loop, the animations and the layers', () => { - const { parent, canvas } = host(); - const s = createRidgeScene({ canvas, tier: 'full', sky: DAY })!; - const anims = animsOf(parent); - s.dispose(); - anims.forEach((a: any) => expect(a.cancel).toHaveBeenCalled()); - expect(parent.children).toEqual([canvas]); - expect(rafQueue).toHaveLength(0); - }); }); describe('the door', () => { @@ -530,95 +424,42 @@ describe('the door', () => { }); }); -describe('aerial perspective in the scene', () => { - it('is baked once: one scatter fill per hazy layer, none per frame, the nearest layer has none', () => { - const { canvas } = host(); - const s = createRidgeScene({ canvas, tier: 'full', sky: DAY })!; - expect(draws.filter((d) => d === 'scatter')).toHaveLength(LAYERS.length - 1); - const before = draws.length; - runFrames(16.7, 400); - expect(draws.length).toBe(before); - s.dispose(); - }); - - it('a sky without a sun bakes no scatter', () => { - const { canvas } = host(); - const s = createRidgeScene({ - canvas, - tier: 'full', - sky: { ...DAY, sunAzimuth: undefined }, - })!; - expect(draws.filter((d) => d === 'scatter')).toHaveLength(0); - s.dispose(); - }); - - it('softens with the canvas filter where it exists, blur scaled by DPR, from pixels baked past the chunk edges', () => { - const { parent, canvas } = host(); - const filters: string[] = []; - const orig = (document as any).createElement; - (document as any).createElement = (t: string) => { - const el = orig(t); - el.getContext = vi.fn(() => { - const c = ctx(true); - let f = 'none'; - Object.defineProperty(c, 'filter', { - get: () => f, - set: (v: string) => { - f = v; - filters.push(v); - }, - }); - return c; - }); - return el; - }; - const s = createRidgeScene({ canvas, tier: 'full', sky: DAY })!; - const blurs = filters.filter((f) => f !== 'none'); - expect(blurs).toHaveLength(LAYERS.length - 1); // nearest is sharp - expect(blurs[0]).toBe(`blur(${edgeBlur(LAYERS[0]) * 2}px)`); // DPR 2 - expect(parent.children).toHaveLength(2); // sky canvas and the rig - s.dispose(); - }); - - it("'still' tier keeps the sky and flattens the aerial layers without extra elements", () => { - const { parent, canvas } = host(); - createRidgeScene({ canvas, tier: 'still' }); - expect(parent.children).toEqual([canvas]); - expect(draws.filter((d) => d === 'sky')).toHaveLength(1); - expect(draws.filter((d) => d === 'flatten')).toHaveLength(LAYERS.length); - }); -}); - describe('the starfield in the scene', () => { const count = (kind: string) => draws.filter((d) => d === kind).length; - const night = { - ...DAY, - top: [10, 14, 40], - mid: [30, 34, 80], - horizon: [60, 50, 90], - } as SkyColours; - const N = makeStars(night, 400, 800).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. + const t = new Date('2026-12-04T00:00:00Z'); + const physical = makePhysicalSky(sunAt(FALLBACK_VIEW.place, t), 0, FALLBACK_VIEW); + const night: SkyColours = { ...DAY, physical }; + const view400 = windowFor(FALLBACK_VIEW, 400, 800); + /** The stars of a still, painted through the viewport's own camera, and of a live plate, painted through the viewport's plus the slack each side. */ + const N = nightBodies(physical, paintPhysicalSky(physical, 400, 800, view400.camera), false).stars.length; + const NPLATE = nightBodies( + physical, + paintPhysicalSky(physical, plateSize(view400, 400, 800, 2, SLACK_MIN_DEG).cssW, 800, plateCamera(view400, FALLBACK_VIEW.lookAzDeg, SLACK_MIN_DEG)), + false + ).stars.length; const hear = (name: string) => { const calls = motion.addEventListener.mock.calls.filter((c: any[]) => c[0] === name); return calls[calls.length - 1][1] as () => void; }; - // Everything but the overlay's own marks: the bake and the ridges. + // Everything but the overlay's own marks: the sky and its stars. const baked = () => draws.filter((d) => d !== 'twinkle' && d !== 'clear').length; it('bakes every star once into the sky; per frame only the overlay is touched', () => { const { parent, canvas } = host(); const s = createRidgeScene({ canvas, tier: 'full', sky: night })!; - expect(count('star')).toBe(N); - expect(count('sky')).toBe(1); - expect(parent.children[1].anims).toHaveLength(0); // the overlay: above the sky, under the ridges - expect(parent.children).toHaveLength(3); + expect(count('star')).toBe(NPLATE); + expect(painted).toHaveLength(1); // the physical sky's one grid + const plate = parent.children[1]; // one element over the host canvas: the sky and, above it, the twinkle canvas + expect(plate.children.map((c: any) => c.tag)).toEqual(['canvas', 'canvas']); + expect(parent.children).toHaveLength(2); const before = baked(); runFrames(16.7, 300); // 5 s at 60 fps; the overlay repaints at 20 fps expect(baked()).toBe(before); expect(count('clear')).toBeGreaterThan(60); expect(count('clear')).toBeLessThanOrEqual(101); - // each pass paints at most SLOTS stars - expect(count('twinkle')).toBeLessThanOrEqual(count('clear') * 32); + // the schedule runs over the catalogue and the plate has a share of it: SLOTS of the plate's stars twinkle on average, each drawn as its cover and the star again + expect(count('twinkle')).toBeLessThanOrEqual(count('clear') * 64 * 2); expect(count('twinkle')).toBeGreaterThan(0); s.dispose(); }); @@ -627,7 +468,7 @@ describe('the starfield in the scene', () => { const { parent, canvas } = host(); const s = createRidgeScene({ canvas, tier: 'full', sky: DAY })!; expect(count('star')).toBe(0); - expect(parent.children).toHaveLength(2); + expect(parent.children).toHaveLength(1); runFrames(16.7, 60); expect(count('clear')).toBe(0); s.dispose(); @@ -687,13 +528,12 @@ describe('the starfield in the scene', () => { s.dispose(); }); - it('flattening to a still (slow frames) drops the overlay and leaves every star baked under the ridges', () => { + it('flattening to a still (slow frames) drops the overlay and leaves every star baked into the sky', () => { const { parent, canvas } = host(); const s = createRidgeScene({ canvas, tier: 'full', sky: night })!; runFrames(100, 100); expect(parent.children).toEqual([canvas]); - expect(count('star')).toBe(N); - expect(draws.indexOf('flatten')).toBeGreaterThan(draws.lastIndexOf('star')); + expect(count('star')).toBe(NPLATE + N); // the plate's, then the still's own in the host canvas expect(rafQueue).toHaveLength(0); s.dispose(); }); @@ -707,125 +547,14 @@ describe('the starfield in the scene', () => { }); }); -describe('endless drift: chunks baked on demand and recycled', () => { - const size = layerSize(400, 800, 2); // the fake host: 400 x 800 CSS px at DPR 2 - const until = async (cond: () => boolean) => { - const t0 = Date.now(); - while (!cond()) { - if (Date.now() - t0 > 10000) throw new Error('timed out waiting for the background bakes'); - await new Promise((r) => setTimeout(r, 5)); - } - }; - /** The pixels chunk `m` of layer `li` must hold: the pure bake of its world columns, no blur. */ - const expected = (li: number, m: number) => { - const p: BakeParams = { - spec: LAYERS[li], - sky: DAY, - period: size.period, - scale: 2, - viewH: 1600, - rows: size.height, - bandH: size.height, - px0: m * size.chunk, - cols: size.chunk, - }; - const out = new Uint8ClampedArray(p.cols * p.rows * 4); - bakeSlice(out, p, layerPaint(p.spec, DAY), 0, p.cols); - return Buffer.from(out.buffer); - }; - /** Each distinct ImageData put, in order of first appearance: one per baked chunk. */ - const baked = () => [...new Set(puts)].map((img) => Buffer.from(img.data.buffer)); - const start = () => { - const { parent, canvas } = host(); - const records: any[] = []; - const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, onBake: (b) => records.push(b) })!; - return { parent, s, records }; - }; - - it('bakes every chunk from its own world columns: no offset, the next chunk continues the last', async () => { - const { s, records } = start(); - await until(() => records.length === 3 * LAYERS.length); - // First view: chunk 0 of each layer; then, per layer in queue order, chunks 1 and 2. - const order = [ - ...LAYERS.map((l) => [l.index, 0]), - ...LAYERS.flatMap((l) => [ - [l.index, 1], - [l.index, 2], - ]), - ]; - expect(records.map((r) => [r.layer, r.chunk])).toEqual(order); - const imgs = baked(); - expect(imgs).toHaveLength(order.length); - order.forEach(([li, m], i) => expect(imgs[i].equals(expected(li, m))).toBe(true)); - s.dispose(); - }); - - it('when the drift animation ends, the chunks move one slot left and the track restarts', async () => { - const { parent, s, records } = start(); - await until(() => records.length === 3 * LAYERS.length); - const track = tracksOf(parent)[1]; // the first layer that drifts: the horizon, [0], stands still - const [e0, e1, e2] = track.children; - const first = track.anims[0]; - // One chunk of drift, not one viewport: the track slides by the width of a chunk. - expect(first.keyframes[1].transform).toContain(`${-size.chunk / 2}px`); - expect(track.animate).toHaveBeenCalledTimes(1); - first.finish(); - expect(first.cancel).toHaveBeenCalled(); - expect(track.animate).toHaveBeenCalledTimes(2); - const w = size.chunk / 2; - expect([e1.style.left, e2.style.left, e0.style.left]).toEqual(['0px', `${w}px`, `${2 * w}px`]); - expect(track.anims[1].keyframes[1].transform).toContain(`${-w}px`); - s.dispose(); - }); - - it('the canvas that left is baked with the next stretch of world, and each rotation after it, without end', async () => { - const { parent, s, records } = start(); - await until(() => records.length === 3 * LAYERS.length); - const track = tracksOf(parent)[1]; - const done = () => records.filter((r) => r.layer === 1).map((r) => r.chunk); - for (let m = 3; m <= 5; m += 1) { - track.anims[track.anims.length - 1].finish(); - await until(() => done().includes(m)); - } - expect(done()).toEqual([0, 1, 2, 3, 4, 5]); - // The pixels of chunks 3 to 5 are the world's, not a repeat of an earlier one. - const imgs = baked(); - const layer1 = imgs.filter((_, i) => records[i].layer === 1); - [3, 4, 5].forEach((m, k) => expect(layer1[3 + k].equals(expected(1, m))).toBe(true)); - expect(layer1[3].equals(layer1[0])).toBe(false); - s.dispose(); - }); - - it('with the blur, each chunk is blurred from a scratch canvas of its own width: seams stay opaque and exact', async () => { - const orig = (document as any).createElement; - (document as any).createElement = (tag: string) => { - const el = orig(tag); - el.getContext = vi.fn(() => ctx(true)); - return el; - }; - const { s, records } = start(); - await until(() => records.length === 3 * LAYERS.length); - const want = new Set( - LAYERS.filter((l) => edgeBlur(l) > 0).map( - (l) => size.chunk + 2 * Math.ceil(3 * edgeBlur(l) * 2) - ) - ); - expect(want.size).toBeGreaterThan(1); // the layers' pads differ, which is what a shared canvas gets wrong - // Every blur reads a source exactly as wide as that chunk's padded bake, at the moment of the draw. - expect(new Set(drawnWidths)).toEqual(want); - s.dispose(); - }); -}); - describe('rain in the scene', () => { const rainy = (w: number): SkyColours => ({ ...DAY, - physical: makePhysicalSky('day', new Date('2026-06-21T10:40:00Z'), w), + 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' && c !== rigOf(parent)); + const rainEls = (parent: any) => parent.children.filter((c: any) => c.tag === 'div' && c.style.backgroundImage); - it('lays one falling tile per rain layer over the ridges when it rains, each slid by its own height on the compositor', () => { + it('lays one falling tile per rain layer over the sky when it rains, each slid by its own height on the compositor', () => { const { parent, canvas } = host(); const s = createRidgeScene({ canvas, tier: 'full', sky: rainy(1) })!; const els = rainEls(parent); @@ -860,3 +589,1404 @@ describe('rain in the scene', () => { s.dispose(); }); }); + +describe('the ridge cards in the scene', () => { + const manifest = parseManifest(wireManifest(), '/d/'); // four tiles of 90 degrees, three cards (card 2 absent in tile 2); rest azimuth 214 + const { view } = manifest; + const tilesOf = (): LitTile[] => + manifest.tiles.flatMap((row, tile) => + row.flatMap((e, card) => { + if (!e) return []; + const canvas = fakeEl('canvas'); + canvas.id = `t${tile}c${card}`; + canvas.width = 1602; + return [{ tile, card, canvas: canvas as unknown as HTMLCanvasElement }]; + }) + ); + const litCards = (): Backdrop & { ensure: Mock<[Arc, Arc?], Promise>; dispose: Mock<[], void> } => { + const lit = tilesOf(); + return { + manifest, + ensure: vi.fn(async (_arc: Arc): Promise => undefined), + litTiles: () => lit, + onTile: () => () => undefined, + dispose: vi.fn(), + }; + }; + const night: SkyColours = { + ...DAY, + top: [10, 14, 40], + mid: [30, 34, 80], + horizon: [60, 50, 90], + physical: makePhysicalSky(sunOfBand(FALLBACK_VIEW.place, 'night', new Date('2026-06-21T22:40:00Z')), 1, FALLBACK_VIEW), + }; + const rigOf = (parent: any) => + parent.children.find((c: any) => c.children.some((g: any) => g.anims.length)); + const win = windowFor(manifest.view, 400, 800); + const planeTop = 800 - win.plane.bottom - win.plane.h; + const horizonY = planeTop + view.horizonRow * win.plane.scale; + const k = win.plane.scale * view.pxPerDegH; + /** The animations of a box that are still running: a reissue cancels the one before it. */ + const live = (box: any): any[] => box.anims.filter((a: any) => a.cancel.mock.calls.length === 0); + const mountedIds = (rig: any): string[] => + rig.children.flatMap((box: any) => box.children.map((c: any) => c.id)).sort(); + const T0 = 5_000; + + beforeEach(() => { + resetHeading(); + resetCamera(); + vi.spyOn(performance, 'now').mockReturnValue(T0); + anchor(view.place.id, view.lookAzDeg, T0); // what index.ts prepare does before the scene is made + }); + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('lays the night bodies (lines, stars, moon) in the sky before any card, so the cards occlude them', () => { + const { canvas } = host(); + createRidgeScene({ + canvas, + tier: 'still', + sky: { ...night }, + backdrop: litCards(), + lines: true, + }); + const bodies = draws.map((d, i) => (d === 'line' || d === 'star' ? i : -1)).filter((i) => i >= 0); + const images = draws.map((d, i) => (d === 'image' ? i : -1)).filter((i) => i >= 0); + expect(bodies.length).toBeGreaterThan(0); + expect(draws).toContain('line'); // the lines are drawn (the sky is a night one) + const cards = images.slice(1); // the sky's upscale first, then the cards' tiles + expect(cards.length).toBeGreaterThan(0); + expect(Math.max(...bodies)).toBeLessThan(Math.min(...cards)); + }); + + it('keeps the live sky, with every body baked into it, and the twinkle canvas in one plate under the rig; the host canvas is not painted', () => { + const { parent, canvas } = host(); + createRidgeScene({ canvas, tier: 'full', sky: { ...night }, backdrop: litCards(), lines: true }); + const rig = rigOf(parent); + const plate = parent.children.find((c: any) => c.children.some((g: any) => g.tag === 'canvas')); + expect(plate.children.map((c: any) => c.tag)).toEqual(['canvas', 'canvas']); // the sky, then the twinkle canvas over it + expect(parent.children.indexOf(rig)).toBeGreaterThan(parent.children.indexOf(plate)); + expect(draws.filter((d) => d === 'image')).toHaveLength(1); // only the plate's sky upscale: nothing in the host canvas, the cards are DOM above the plate + expect(live(plate)).toHaveLength(1); // one animation slides it + }); + + it('stacks the rig after the twinkle canvas and before the rain, with no z-index and no fixed position, and disposes the backdrop with itself', () => { + const { parent, canvas } = host(); + const bd = litCards(); + const s = createRidgeScene({ canvas, tier: 'full', sky: night, backdrop: bd })!; + const kinds = parent.children.map((c: any) => c.tag); + expect(kinds).toEqual(['canvas', 'div', 'div', 'div', 'div']); // the host canvas, the sky plate, the rig, the rain + expect(parent.children[2].children).toHaveLength(3); + parent.children.forEach((c: any) => { + expect(c.style.zIndex).toBeUndefined(); + expect(c.style.position).not.toBe('fixed'); + }); + expect(bd.dispose).not.toHaveBeenCalled(); + s.dispose(); + expect(parent.children).toEqual([canvas]); + expect(bd.dispose).toHaveBeenCalledOnce(); + }); + + it('is one box per card, farthest first, spanning the viewport with its origin on the horizon centre, holding that card’s tiles', () => { + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!; + const rig = rigOf(parent); + expect(rig.children.map((c: any) => c.id)).toEqual(['card-2', 'card-1', 'card-0']); + rig.children.forEach((el: any) => { + expect(el.style.left).toBe('0'); + expect(el.style.width).toBe('400px'); + expect(el.style.height).toBe('800px'); + expect(el.style.transformOrigin).toBe(`200px ${horizonY}px`); + }); + // Each card's tiles are its own: the box of card 0 holds only c0 canvases. + rig.children.forEach((el: any) => { + const card = Number(el.id.slice(-1)); + el.children.forEach((c: any) => expect(c.id.endsWith(`c${card}`)).toBe(true)); + }); + s.dispose(); + }); + + it('mounts the tiles of the arc about to be seen at their unwrapped azimuth, at their own rows of the plane, one overlap column before the interior', () => { + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!; + const rig = rigOf(parent); + // Rest azimuth 214: tile 2 (180..270). Tile 1 and tile 3 are out of sight for the next 30 s at 0.6 degrees per second. + expect(mountedIds(rig)).toEqual(['t2c0', 't2c1']); + const c0 = rig.children[2].children[0]; + const e = manifest.tiles[2][0]!; + const colDeg = 360 / view.ringW; + const px = (v: string) => parseFloat(v); + expect(px(c0.style.left)).toBeCloseTo(200 + (180 - colDeg - 214) * k, 6); + expect(px(c0.style.top)).toBeCloseTo(horizonY + (e.top - view.horizonRow) * win.plane.scale, 6); + expect(px(c0.style.width)).toBeCloseTo((view.tileW + 2) * win.plane.scale, 6); + expect(px(c0.style.height)).toBeCloseTo(e.h * win.plane.scale, 6); + s.dispose(); + }); + + it('is one animation per card, not per tile, carrying the pose the heading owner gives each second for 30 seconds', () => { + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!; + const rig = rigOf(parent); + rig.children.forEach((box: any) => expect(live(box)).toHaveLength(1)); + rig.children.forEach((box: any) => { + const card = Number(box.id.slice(-1)); + const { keyframes, options } = live(box)[0]; + expect(options).toEqual({ duration: 30000, easing: 'linear', fill: 'forwards' }); + expect(keyframes).toHaveLength(31); + const pose = (t: number) => + posed(manifest, card, t, win); + [0, 1, 17, 30].forEach((n) => { + const p = pose(T0 + n * 1000); + expect(keyframes[n]).toEqual({ transform: `translate3d(${p.shiftPx}px,0,0) scale(${p.scale})` }); + }); + // The view turns at the viewer's 0.6 degrees per second: the container moves one pan per second, a nearer card faster. + }); + const near = live(rig.children[2])[0].keyframes; + const far = live(rig.children[0])[0].keyframes; + const shift = (kf: any) => Number(/translate3d\((-?[\d.e-]+)px/.exec(kf.transform)?.[1]); + expect(Math.abs(shift(near[30]) - shift(near[0]))).toBeGreaterThan(Math.abs(shift(far[30]) - shift(far[0]))); + s.dispose(); + }); + + describe('the sky turns with the heading', () => { + const W = 400; + const SUN_ABOVE_REST = 5; // the sun stands this many degrees clockwise of the rest azimuth, 15 degrees up + const sunSky = (): SkyColours => ({ + ...DAY, + physical: makePhysicalSky({ azimuth: view.lookAzDeg + SUN_ABOVE_REST, elevation: 15, time: new Date('2026-06-21T10:40:00Z') }, 0, view), + }); + const nightSky = (): SkyColours => ({ + ...DAY, + physical: makePhysicalSky(sunOfBand(view.place, 'night', new Date('2026-12-04T00:00:00Z')), 0, view), + }); + const px = (v: string) => parseFloat(v); + const plateOf = (parent: any) => parent.children.find((c: any) => c.children.some((g: any) => g.tag === 'canvas')); + /** The plate's pan (px) at the clock `t`, read from its running animation: its keyframes are a second apart. */ + const panAt = (plate: any, t: number): number => { + const a = live(plate)[0]; + const at = (n: number) => px(/translate3d\((-?[\d.e+-]+)px/.exec(a.keyframes[n].transform)![1]); + const s = Math.max(0, (t - a.at) / 1000); + const i = Math.min(Math.floor(s), a.keyframes.length - 2); + return at(i) * (1 - (s - i)) + at(i + 1) * (s - i); + }; + /** Where a point drawn at `x` device px of the plate's sky canvas is on the viewport at `t`, CSS px from its left edge. */ + const onViewport = (plate: any, x: number, t: number): number => { + const ratio = plate.children[0].width / px(plate.style.width); + return px(plate.style.left) + x / ratio + panAt(plate, t); + }; + const ticking = () => { + vi.useFakeTimers(); + (window as any).setTimeout = setTimeout; + (window as any).clearTimeout = clearTimeout; + }; + + it('paints the plate about the heading the view has, not the rest azimuth, and holds it still there', () => { + hold(100, T0); + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: sunSky(), backdrop: litCards() })!; + const sky = sunSky().physical!; + const wn = windowFor(view, W, 800); + const want = paintPhysicalSky(sky, plateSize(wn, W, 800, 2, SLACK_MIN_DEG).cssW, 800, plateCamera(wn, 100, SLACK_MIN_DEG)); + expect(Array.from(painted[0])).toEqual(Array.from(want.data)); + expect(painted).toHaveLength(1); // the host canvas has none: the plate is the sky + const plate = plateOf(parent); + expect(px(plate.style.left)).toBeCloseTo((W - plateSize(wn, W, 800, 2, SLACK_MIN_DEG).cssW) / 2, 9); // centred on the viewport + expect(panAt(plate, T0)).toBeCloseTo(0, 9); + s.dispose(); + }); + + it('moves the sun and a catalogue star by exactly the turn times the px per degree between a plate centred on h and one centred on h + delta', () => { + const first = host(); + const a = createRidgeScene({ canvas: first.canvas, tier: 'full', sky: sunSky(), backdrop: litCards() })!; + const sunA = [...suns[0]]; + const plateA = plateOf(first.parent); + const xA = onViewport(plateA, sunA[0], T0); + expect(xA).toBeCloseTo(W / 2 + SUN_ABOVE_REST * k, 0); // the sun at its true azimuth against the heading + a.dispose(); + suns.length = 0; + hold(view.lookAzDeg + 10, T0); + const second = host(); + const b = createRidgeScene({ canvas: second.canvas, tier: 'full', sky: sunSky(), backdrop: litCards() })!; + const xB = onViewport(plateOf(second.parent), suns[0][0], T0); + expect(xA - xB).toBeCloseTo(10 * k, 0); + expect(suns[0][1]).toBe(sunA[1]); // the sun does not climb: only the azimuth turns + b.dispose(); + + }); + + it('moves a catalogue star by exactly the turn times the px per degree too, and the stars that stay in sight are the same ones', () => { + const starsAt = (heading: number) => { + resetHeading(); + anchor(view.place.id, heading, T0); + arcs.length = 0; + const h = host(); + createRidgeScene({ canvas: h.canvas, tier: 'full', sky: nightSky(), backdrop: litCards() })!.dispose(); + return arcs.map((p) => [p[0], p[1]]); + }; + const plateX = (device: number) => { + const wn = windowFor(view, W, 800); + const size = plateSize(wn, W, 800, 2, SLACK_MIN_DEG); + return (device / Math.floor(size.cssW * size.ratio)) * size.cssW + (W - size.cssW) / 2; + }; + const here = starsAt(view.lookAzDeg).map(([x, y]) => [plateX(x), y]); + const turned = starsAt(view.lookAzDeg + 10).map(([x, y]) => [plateX(x), y]); + const inSight = here.filter(([x]) => x - 10 * k > 0 && x - 10 * k < W && x > 0 && x < W); + expect(inSight.length).toBeGreaterThan(3); + inSight.forEach(([x, y]) => { + // pan 0 in both: the viewport position is the plate's, and it moved left by ten degrees of pixels + const found = turned.find(([tx, ty]) => ty === y && Math.abs(tx - (x - 10 * k)) < 0.75); + expect(found).toBeDefined(); + }); + }); + + it('keeps the sun and every star where the view faces them across a re-centre: the old plate goes, a new one stands in its place, the sun moves by less than a pixel', () => { + ticking(); + const now = vi.mocked(performance.now); + setCamera({ speedDegPerS: 4 }); // the view turns 4 degrees a second: the plate runs to 14 degrees off its centre in 3.5 s + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: sunSky(), backdrop: litCards() })!; + const first = plateOf(parent); + const kinds = parent.children.map((c: any) => c.tag); + const seen = new Set([first]); + let last = onViewport(first, suns[suns.length - 1][0], T0); + for (let ms = 500; ms <= 9_000; ms += 500) { + now.mockReturnValue(T0 + ms); + vi.advanceTimersByTime(500); + const plate = plateOf(parent); + seen.add(plate); + const x = onViewport(plate, suns[suns.length - 1][0], T0 + ms); + const want = W / 2 + (view.lookAzDeg + SUN_ABOVE_REST - poseAt(T0 + ms).h) * k; // the sun's true place on the viewport + expect(Math.abs(x - want)).toBeLessThan(1); + expect(Math.abs(x - last + 4 * 0.5 * k)).toBeLessThan(1); // it moved only as the view turned (half a second of it) + last = x; + expect(parent.children.map((c: any) => c.tag)).toEqual(kinds); // the plate is replaced in its place: nothing stacks up + } + expect(seen.size).toBe(3); // 36 degrees of turn: replaced at 16 and at 32 degrees + expect([...seen].filter((p) => p.parentElement).length).toBe(1); + expect(live(plateOf(parent))).toHaveLength(1); + s.dispose(); + expect(parent.children).toEqual([canvas]); + vi.useRealTimers(); + }); + + it('keys a swapped plate from the clock after it is painted, so a paint, however long, is not lag behind the heading', () => { + ticking(); + const now = vi.mocked(performance.now); + setCamera({ speedDegPerS: 4 }); + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: sunSky(), backdrop: litCards() })!; + const first = plateOf(parent); + const PAINT_MS = 250; // a phone: the clock runs on while the sky is painted + let swapped: any; + for (let ms = 500; ms <= 9_000 && !swapped; ms += 500) { + now.mockReturnValue(T0 + ms); + onPaint = () => now.mockReturnValue(T0 + ms + PAINT_MS); + vi.advanceTimersByTime(500); + onPaint = undefined; + if (plateOf(parent) !== first) swapped = plateOf(parent); + } + expect(swapped).toBeDefined(); + const a = live(swapped)[0]; + expect(a.at % 500).toBe(PAINT_MS); // keyed after the paint: from the clock the paint ended at + // the sun is where the view faces it at the instant the slide begins, to the pixel + const x = onViewport(swapped, suns[suns.length - 1][0], a.at); + expect(Math.abs(x - (W / 2 + (view.lookAzDeg + SUN_ABOVE_REST - poseAt(a.at).h) * k))).toBeLessThan(1); + s.dispose(); + vi.useRealTimers(); + }); + + it('never runs a plate out at the speed in force, whichever phase a late tick falls in, and sizes the slack to that speed', () => { + ticking(); + const now = vi.mocked(performance.now); + const SPEED = 12; + setCamera({ speedDegPerS: SPEED }); + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: sunSky(), backdrop: litCards() })!; + const hfov = win.camera.hfovDeg; + expect(px(plateOf(parent).style.width) / k).toBeCloseTo(hfov + 2 * slackFor(SPEED, RESIDENCY_MS), 6); // the slack of 12 degrees a second, not of 0.6 + // Ticks every half second, one in four two seconds late: at no instant may the viewport's edge pass the plate's. + let t = 0; + let widest = 0; + for (let n = 0; t < 24_000; n += 1) { + const gap = n % 4 === 3 ? 500 + LATENESS_S * 1000 : 500; + for (let at = t; at < t + gap; at += 50) { + const plate = plateOf(parent); + const edge = (px(plate.style.width) - W) / 2; // px the plate reaches past the viewport each side + widest = Math.max(widest, Math.abs(panAt(plate, T0 + at)) - edge); + } + t += gap; + now.mockReturnValue(T0 + t); + vi.advanceTimersByTime(500); + } + expect(widest).toBeLessThanOrEqual(1e-6); // the viewport's edge never got past the plate's + s.dispose(); + vi.useRealTimers(); + }); + + it('slides a slow turn on the least slack, and sizes the plate again when the speed asks for more', () => { + ticking(); + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: sunSky(), backdrop: litCards() })!; + const hfov = win.camera.hfovDeg; + expect(px(plateOf(parent).style.width) / k).toBeCloseTo(hfov + 2 * SLACK_MIN_DEG, 6); + const slow = plateOf(parent); + setCamera({ speedDegPerS: 12 }); // the viewer speeds the turn up: a plate with the slack of a slow one would be run out + const fast = plateOf(parent); + expect(fast).not.toBe(slow); + expect(px(fast.style.width) / k).toBeCloseTo(hfov + 2 * slackFor(12, RESIDENCY_MS), 6); + expect(panAt(fast, T0)).toBeCloseTo(0, 6); + s.dispose(); + vi.useRealTimers(); + }); + + it('keeps which stars twinkle, and their phase, across a swap, and shows the new plate with its twinkles already drawn', () => { + ticking(); + const now = vi.mocked(performance.now); + setCamera({ speedDegPerS: 4 }); + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: nightSky(), backdrop: litCards() })!; + /** One display frame of the twinkle loop alone, at the clock now. */ + const frame = () => { + const cbs = rafQueue.filter((c) => c.name === 'twTick'); + rafQueue = rafQueue.filter((c) => c.name !== 'twTick'); + cbs.forEach((c) => c(now())); + }; + /** The stars drawn since `twinks` was cleared, as where they are on the viewport and how high, once each. */ + const seen = (plate: any): string[] => + [...new Set(twinks.map(([x, y]) => `${Math.round(onViewport(plate, x, now()))},${Math.round(y)}`))].filter((p) => { + const x = Number(p.split(',')[0]); + return x > 2 && x < W - 2; + }); + let compared = 0; + for (let ms = 500; ms <= 9_000 && compared === 0; ms += 500) { + now.mockReturnValue(T0 + ms); + const before = plateOf(parent); + twinks.length = 0; + frame(); // the loop's frame at this clock: the stars the plate that is up has swinging + const old = seen(before); + twinks.length = 0; + vi.advanceTimersByTime(500); // the tick, at the same clock, which swaps the plate when the heading is near its edge + const after = plateOf(parent); + if (after === before) continue; + const next = seen(after); + expect(old.length).toBeGreaterThan(0); + const near = (a: string, list: string[]) => + list.some((b) => { + const [ax, ay] = a.split(',').map(Number); + const [bx, by] = b.split(',').map(Number); + return Math.abs(ax - bx) <= 1 && ay === by; + }); + old.forEach((p) => expect(near(p, next)).toBe(true)); // each star swinging a moment ago is swinging now, at the same place + next.forEach((p) => expect(near(p, old)).toBe(true)); // and no other + compared += 1; + } + expect(compared).toBe(1); + s.dispose(); + vi.useRealTimers(); + }); + + it('does not repaint a plate for a view that stays or turns within its slack', () => { + ticking(); + const now = vi.mocked(performance.now); + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: sunSky(), backdrop: litCards() })!; // 0.6 degrees a second + const first = plateOf(parent); + for (let ms = 500; ms <= 20_000; ms += 500) { + now.mockReturnValue(T0 + ms); + vi.advanceTimersByTime(500); + } + expect(plateOf(parent)).toBe(first); // 12 degrees of turn: inside the 14 + expect(painted).toHaveLength(1); + s.dispose(); + vi.useRealTimers(); + }); + + it('re-centres on a reissue too: a turn by hand past the edge paints a plate about where the view now faces', () => { + ticking(); + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: sunSky(), backdrop: litCards() })!; + const first = plateOf(parent); + hold(view.lookAzDeg + 60, T0); + const plate = plateOf(parent); + expect(plate).not.toBe(first); + expect(panAt(plate, T0)).toBeCloseTo(0, 6); + expect(live(plate)).toHaveLength(1); + s.dispose(); + vi.useRealTimers(); + }); + + it('puts the twinkle canvas in the plate, over the sky, and nothing animates but the plate', () => { + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: nightSky(), backdrop: litCards() })!; + const plate = plateOf(parent); + expect(plate.children.map((c: any) => c.tag)).toEqual(['canvas', 'canvas']); + expect([plate.children[1].width, plate.children[1].height]).toEqual([plate.children[0].width, plate.children[0].height]); + plate.children.forEach((c: any) => expect(c.anims).toHaveLength(0)); // they ride the plate + expect(parent.children.filter((c: any) => c.tag === 'canvas')).toEqual([canvas]); // no twinkle canvas of the page's own + s.dispose(); + }); + + it('paints a plate that stays under the pixel cap and pans by the same px per degree as the cards', () => { + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: sunSky(), backdrop: litCards() })!; + const plate = plateOf(parent); + expect(plate.children[0].width * plate.children[0].height).toBeLessThanOrEqual(3_000_000); + expect(px(plate.style.width) / (win.camera.hfovDeg + 40)).toBeCloseTo(k, 9); + hold(view.lookAzDeg + 10, T0); // a turn by hand inside the slack: the same plate slides ten degrees of pixels + expect(panAt(plateOf(parent), T0)).toBeCloseTo(-10 * k, 6); + s.dispose(); + }); + + it('shows the sun at the azimuth the ridge is lit from: facing it the sky puts it on the centre column and the ridge faces it; facing away it is off the plate and the ridge is in shade', () => { + const sun = { azimuth: view.lookAzDeg + 17, elevation: 12 }; + const lit = { ...DAY, physical: makePhysicalSky({ ...sun, time: new Date('2026-06-21T10:40:00Z') }, 0, view) }; + // The ridge's own: the column whose face looks at the sun is the one the lit table gives most to. + const cols = sunColumns(view, sun); + let best = 0; + for (let c = 0; c < view.ringW; c += 1) if (cols[c * 4] > cols[best * 4]) best = c; + expect(Math.abs(ringAzimuth(best, view.ringW) - sun.azimuth)).toBeLessThanOrEqual(360 / view.ringW); + + resetHeading(); + anchor(view.place.id, sun.azimuth, T0); + const facing = host(); + createRidgeScene({ canvas: facing.canvas, tier: 'full', sky: lit, backdrop: litCards() })!.dispose(); + expect(suns).toHaveLength(1); + const wn = windowFor(view, W, 800); + const size = plateSize(wn, W, 800, 2, SLACK_MIN_DEG); + const centreCol = (suns[0][0] / Math.floor(size.cssW * size.ratio)) * size.cssW + (W - size.cssW) / 2; + expect(Math.abs(centreCol - W / 2)).toBeLessThan(1); // the sky's sun is on the column the view centres, whose face the ridge lights fullest + expect(sunInColumn(sun, sun.azimuth)[0]).toBeCloseTo(Math.cos((sun.elevation * Math.PI) / 180), 12); + + suns.length = 0; + resetHeading(); + anchor(view.place.id, sun.azimuth + 180, T0); + const away = host(); + createRidgeScene({ canvas: away.canvas, tier: 'full', sky: lit, backdrop: litCards() })!.dispose(); + expect(suns).toHaveLength(0); // the sun is behind the camera: no disc anywhere on the plate + expect(sunInColumn(sun, sun.azimuth + 180)[0]).toBeLessThan(0); // and the ridge faces it away + }); + }); + + it('a heading of 400 degrees places the tiles a heading of 40 does, a revolution on', () => { + const at = (h: number) => { + resetHeading(); + anchor(view.place.id, view.lookAzDeg, T0); + hold(h, T0); + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!; + const rig = rigOf(parent); + const out = { + ids: mountedIds(rig), + left: Number(rig.children[2].children[0].style.left.slice(0, -2)), + heading: poseAt(T0).h, + }; + s.dispose(); + return out; + }; + // A manual turn leaves the rotation off, and a scene made over it keeps it off. + const a = at(40); + const b = at(400); + expect(b.ids).toEqual(a.ids); + // The rig lays out from the heading brought into [0, 360): a revolution on is the same picture, with nothing grown. + expect(b.heading).toBeCloseTo(a.heading, 9); + expect(b.left).toBeCloseTo(a.left, 6); + }); + + it('asks the backdrop for the arc between now and the end of the stretch, at once and every half second, and mounts what it has made', async () => { + vi.useFakeTimers(); + (window as any).setTimeout = setTimeout; + (window as any).clearTimeout = clearTimeout; + const { parent, canvas } = host(); + const bd = litCards(); + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: bd })!; + expect(bd.ensure).not.toHaveBeenCalled(); // the first arc was made before the scene (index.ts prepare) + vi.advanceTimersByTime(500); + expect(bd.ensure).toHaveBeenCalledTimes(1); + const arc = bd.ensure.mock.calls[0][0]; + // The heading is 214 and turns 0.6 degrees per second to 232 in 30 s; on a 400 x 800 viewport a card shows about 28 degrees of itself. + expect(arc.fromDeg).toBeLessThan(214 - 10); + expect(arc.toDeg).toBeGreaterThan(232 + 10); + vi.advanceTimersByTime(1500); + expect(bd.ensure).toHaveBeenCalledTimes(4); + // The view is turned by hand to the north: the next tick holds the tiles there. + const before = mountedIds(rigOf(parent)); + hold(300, T0); + vi.advanceTimersByTime(500); + const after = mountedIds(rigOf(parent)); + expect(before).toEqual(['t2c0', 't2c1']); + expect(after).not.toContain('t2c0'); + expect(after.some((id) => id.startsWith('t3'))).toBe(true); + s.dispose(); + vi.useRealTimers(); + }); + + it('issues the next stretch of motion once 80% of the last has run, on any change of heading, mode or offset, and not otherwise', () => { + vi.useFakeTimers(); + (window as any).setTimeout = setTimeout; + (window as any).clearTimeout = clearTimeout; + const now = vi.mocked(performance.now); + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!; + const rig = rigOf(parent); + const issued = () => rig.children.map((b: any) => b.anims.length); + const base = issued()[0]; + now.mockReturnValue(T0 + 20_000); + vi.advanceTimersByTime(20_000); + expect(issued()[0]).toBe(base); // 20 s of 30: not yet + now.mockReturnValue(T0 + 24_500); + vi.advanceTimersByTime(4_500); + expect(issued()[0]).toBe(base + 1); + expect(rig.children[0].anims[base - 1].cancel).toHaveBeenCalled(); + const afterReissue = issued()[0]; + setCamera({ offsetM: 20 }); + expect(issued()[0]).toBe(afterReissue + 1); + setCamera({ offsetM: 20 }); // nothing changed + expect(issued()[0]).toBe(afterReissue + 1); + hold(10, T0 + 24_500); + expect(issued()[0]).toBe(afterReissue + 2); + s.dispose(); + setCamera({ offsetM: 30 }); + expect(issued()[0]).toBe(afterReissue + 2); // a disposed scene is deaf + vi.useRealTimers(); + }); + + it('adds no rAF of its own over ten idle seconds: the drift is Element.animate, the stars alone loop', () => { + vi.useFakeTimers(); + (window as any).setTimeout = setTimeout; + (window as any).clearTimeout = clearTimeout; + const { canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!; + expect(rafQueue).toHaveLength(1); // the frame sampler, as without cards + vi.advanceTimersByTime(10_000); + expect(rafQueue).toHaveLength(1); + s.dispose(); + vi.useRealTimers(); + }); + + it('runs constant keyframes under reduced motion, and the view turns nothing whatever the viewer asked for', () => { + motion.matches = true; + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!; + expect(poseAt(T0 + 10_000).h).toBe(poseAt(T0).h); // nothing turns, whatever the viewer chose + expect(getCamera().mode).toBe('both'); // and the viewer's choice is not rewritten for it + rigOf(parent).children.forEach((box: any) => { + const { keyframes } = live(box)[0]; + expect(keyframes.length).toBeGreaterThan(0); + keyframes.forEach((f: any) => expect(f).toEqual(keyframes[0])); + }); + s.dispose(); + }); + + it('pauses the motion in a hidden tab and when motion is reduced, plays it again from where the clock is, and cancels it on dispose', () => { + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!; + const rig = rigOf(parent); + const anims = () => rig.children.map((g: any) => g.anims[g.anims.length - 1]); + anims().forEach((a: any) => expect(a.play).toHaveBeenCalled()); + const first = anims(); + first.forEach((a: any) => a.pause.mockClear()); + motion.matches = true; + motion.addEventListener.mock.calls + .filter((c: any[]) => c[0] === 'change') + .forEach((c: any[]) => c[1]()); + anims().forEach((a: any) => expect(a.pause).toHaveBeenCalled()); + motion.matches = false; + doc.visibilityState = 'hidden'; + doc.dispatchEvent(new Event('visibilitychange')); + anims().forEach((a: any) => expect(a.pause).toHaveBeenCalled()); + doc.visibilityState = 'visible'; + (performance.now as any).mockReturnValue(T0 + 60_000); + doc.dispatchEvent(new Event('visibilitychange')); + const resumed = anims(); + resumed.forEach((a: any) => expect(a.play).toHaveBeenCalled()); + // Back in view the motion starts from the clock now, not from where it stopped. + const frame0 = (box: any) => box.anims[box.anims.length - 1].keyframes[0].transform; + const p = posed(manifest, 0, T0 + 60_000, win); + expect(frame0(rig.children[2])).toBe(`translate3d(${p.shiftPx}px,0,0) scale(${p.scale})`); + s.dispose(); + resumed.forEach((a: any) => expect(a.cancel).toHaveBeenCalled()); + }); + + describe('after the viewer takes the view by hand, and for the long run', () => { + const fixtureRing = (camera: Record = { r_max_m: 98.2, r_max_forward_m: 205.4 }) => + parseManifest(wireManifest({ camera }, 3, 32), '/d/'); // the ring as the baker cuts it, with Vienna's two offset bounds + const ringBackdrop = (m: typeof manifest): Backdrop & { ensure: Mock<[Arc, Arc?], Promise> } => { + const lit = m.tiles.flatMap((row, tile) => + row.flatMap((e, card) => { + if (!e) return []; + const canvas = fakeEl('canvas'); + canvas.id = `t${tile}c${card}`; + return [{ tile, card, canvas: canvas as unknown as HTMLCanvasElement }]; + }) + ); + return { + manifest: m, + ensure: vi.fn(async (_arc: Arc, _first?: Arc): Promise => undefined), + litTiles: () => lit, + onTile: () => () => undefined, + dispose: vi.fn(), + }; + }; + const frame = (box: any, n: number) => live(box)[0].keyframes[n].transform as string; + const pending = () => { + vi.useFakeTimers(); + (window as any).setTimeout = setTimeout; + (window as any).clearTimeout = clearTimeout; + }; + + it('a manual turn holds through a rebuild: a resize makes a new scene and the view stays where the viewer left it', () => { + pending(); + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!; + hold(100, T0); + const at = poseAt(T0).h; + window.dispatchEvent(new Event('resize')); + vi.advanceTimersByTime(300); // the debounced rebuild: startRig runs again + expect(effectiveMode()).toBe('still'); // held, and the chosen mode untouched + expect(getCamera().mode).toBe('both'); + expect(poseAt(T0 + 60_000).h).toBe(at); + rigOf(parent).children.forEach((box: any) => expect(frame(box, 30)).toBe(frame(box, 0))); + s.dispose(); + // And a scene made afterwards, as a sky change makes one. + const again = createRidgeScene({ canvas: host().canvas, tier: 'full', sky: night, backdrop: litCards() })!; + expect(poseAt(T0 + 60_000).h).toBe(at); + again.dispose(); + vi.useRealTimers(); + }); + + it('picking the mode they already had after a hold resumes the turn, and the rig moves again', () => { + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!; + hold(100, T0); + rigOf(parent).children.forEach((box: any) => expect(frame(box, 30)).toBe(frame(box, 0))); + expect(isHeld()).toBe(true); + setCamera({ mode: 'both' }); // what the View's rotation picker sends: the mode the viewer had when they took the view + expect(isHeld()).toBe(false); + expect(poseAt(T0 + 10_000).h).toBeCloseTo(106, 9); + rigOf(parent).children.forEach((box: any) => expect(frame(box, 30)).not.toBe(frame(box, 0))); + s.dispose(); + }); + + it('mounts and asks for the tiles of every pose a stretch passes through, not those at its ends: offset-only turning swings the near card out and back', () => { + pending(); + const ring = fixtureRing(); + const bd = ringBackdrop(ring); + const w2 = windowFor(ring.view, 400, 800); + setCamera({ mode: 'offset', speedDegPerS: 12, offsetM: 98 }); + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: bd })!; + vi.advanceTimersByTime(500); + const asked = bd.ensure.mock.calls[0][0]; + let from = Infinity; + let to = -Infinity; + let endFrom = Infinity; + let endTo = -Infinity; + for (let ms = 0; ms <= 30_000; ms += 100) { + for (let i = 0; i < 3; i += 1) { + const a = cardArc(ring.view, w2, 400, posed(ring, i, T0 + ms, w2)); + from = Math.min(from, a.fromDeg); + to = Math.max(to, a.toDeg); + if (ms === 0 || ms === 30_000) { + endFrom = Math.min(endFrom, a.fromDeg); + endTo = Math.max(endTo, a.toDeg); + } + } + } + expect(endTo - endFrom).toBeLessThan(to - from - 5); // the ends alone miss degrees of it (a whole turn of the camera comes back to where it began) + expect(asked.fromDeg).toBeLessThanOrEqual(from + 0.01); + expect(asked.toDeg).toBeGreaterThanOrEqual(to - 0.01); + const need = new Set(residentTiles(ring.view, (from + to) / 2, (to - from) / 2 - 0.02).map((r) => r.tile)); + const mounted = new Set(mountedIds(rigOf(parent)).map((id) => Number(/^t(\d+)c/.exec(id)?.[1]))); + need.forEach((t) => expect(mounted.has(t), `tile ${t}`).toBe(true)); + s.dispose(); + vi.useRealTimers(); + }); + + it('tells the loader where the view is now besides the arc it will sweep, so the tiles on screen are asked for first', () => { + pending(); + const ring = fixtureRing(); + const bd = ringBackdrop(ring); + const w2 = windowFor(ring.view, 400, 800); + const { canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: bd })!; + vi.advanceTimersByTime(500); + const [arc, first] = bd.ensure.mock.calls[0]; + expect(first).toBeDefined(); + const now = [0, 1, 2].map((i) => cardArc(ring.view, w2, 400, posed(ring, i, T0, w2))); + expect(first!.fromDeg).toBeCloseTo(Math.min(...now.map((a) => a.fromDeg)), 6); + expect(first!.toDeg).toBeCloseTo(Math.max(...now.map((a) => a.toDeg)), 6); + expect(first!.toDeg - first!.fromDeg).toBeLessThan(arc.toDeg - arc.fromDeg); + s.dispose(); + vi.useRealTimers(); + }); + + it('takes the default 200 m where the camera stays on its heading and the bake allows it, and the worst-case bound where the camera circles', () => { + const ring = fixtureRing(); + const w2 = windowFor(ring.view, 400, 800); + const keyframe0 = (mode: 'both' | 'offset') => { + resetHeading(); // a page of its own for each mode: the view starts where the choice puts it + anchor(view.place.id, view.lookAzDeg, T0); + setCamera({ mode, speedDegPerS: 0.6, offsetM: 200 }); + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(ring) })!; + const got = frame(rigOf(parent).children[2], 0); + s.dispose(); + return got; + }; + const posed = (offset: number) => { + const p = cardPose(ring, 0, poseAt(T0).h, poseAt(T0).phi, offset, w2); + return `translate3d(${p.shiftPx}px,0,0) scale(${p.scale})`; + }; + expect(keyframe0('both')).toBe(posed(200)); + expect(keyframe0('offset')).toBe(posed(98.2)); + }); + + it('bounds the speed at read to what the baked resident count sustains, for the mode in force, and never rewrites the stored speed', () => { + const ring = fixtureRing(); + const slow = maxSpeed(ring, 'both'); + expect(slow).toBeGreaterThan(0.6); + expect(slow).toBeLessThan(12); + setCamera({ mode: 'both', speedDegPerS: 50 }); // a stored or future-slider value + anchor(view.place.id, view.lookAzDeg, T0, (m) => maxSpeed(ring, m)); // what index.ts prepare does with the manifest, before the scene is made + const { canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(ring) })!; + expect(getCamera().speedDegPerS).toBe(50); + expect(poseAt(T0 + 10_000).h - poseAt(T0).h).toBeCloseTo(10 * slow, 9); + setCamera({ speedDegPerS: -50 }); + expect(getCamera().speedDegPerS).toBe(-50); + expect(poseAt(T0 + 10_000).h - poseAt(T0).h).toBeCloseTo(-10 * slow, 9); + setCamera({ mode: 'offset', speedDegPerS: 11 }); // the offset-only mode sweeps the circle the gate counts, whatever the speed + expect(poseAt(T0 + 20_000).phi - poseAt(T0 + 10_000).phi).toBeCloseTo(110, 9); + setCamera({ mode: 'both' }); + expect(getCamera().speedDegPerS).toBe(11); // still the viewer's value + expect(poseAt(T0 + 10_000).h - poseAt(T0).h).toBeCloseTo(10 * slow, 9); + s.dispose(); + }); + + it('derives the offset clamp at read and never writes it back: offset-only to a forward mode restores 200 m', () => { + const ring = fixtureRing(); + const w2 = windowFor(ring.view, 400, 800); + setCamera({ mode: 'offset', speedDegPerS: 0.6, offsetM: 200 }); + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(ring) })!; + const posed = (offset: number) => { + const p = cardPose(ring, 0, poseAt(T0).h, poseAt(T0).phi, offset, w2); + return `translate3d(${p.shiftPx}px,0,0) scale(${p.scale})`; + }; + expect(frame(rigOf(parent).children[2], 0)).toBe(posed(98.2)); + expect(getCamera().offsetM).toBe(200); + setCamera({ mode: 'both' }); + expect(getCamera().offsetM).toBe(200); + const keys = live(rigOf(parent).children[2])[0].keyframes; + expect(keys[0].transform).toBe(posed(98.2)); // the view leaves from the offset it showed (the pick does not move it) ... + const p = cardPose(ring, 0, poseAt(T0 + STAGE_MS).h, 0, 200, w2); + expect(keys.find((f: any) => f.offset >= STAGE_MS / (SEGMENT_S * 1000) - 1e-9).transform).toBe(`translate3d(${p.shiftPx}px,0,0) scale(${p.scale})`); // ... and is at 200 when the ease is spent + s.dispose(); + }); + + it('eases a mode pick: the view the viewer saw is the first frame, the new regime the frame an EASE_MS later, one animation and no timer of its own', () => { + const ring = fixtureRing(); + const w2 = windowFor(ring.view, 400, 800); + setCamera({ mode: 'offset', speedDegPerS: 12, offsetM: 200 }); + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(ring) })!; + const at = T0 + 7_500; // 90 degrees round its circle at 12 degrees a second, at the offset 98.2 the mode clamps to + const tf = (ms: number, phi: number, offset: number) => { + const p = cardPose(ring, 0, poseAt(at + ms).h, phi, offset, w2); + return { text: `translate3d(${p.shiftPx}px,0,0) scale(${p.scale})`, scale: p.scale }; + }; + expect(poseAt(at).phi).toBeCloseTo(90, 6); + const seen = tf(0, poseAt(at).phi, 98.2); + vi.mocked(performance.now).mockReturnValue(at); + setCamera({ mode: 'both' }, at); // phi goes to 0 and the clamp releases to 200: both used to land in one frame + const run = live(rigOf(parent).children[2])[0]; + expect(run.keyframes[0].transform).toBe(seen.text); + const spent = EASE_MS / (SEGMENT_S * 1000); + const end = run.keyframes.find((f: any) => f.offset >= spent - 1e-9); + const there = tf(EASE_MS, 0, 200); + expect(end.transform).toBe(there.text); + const eased = run.keyframes.filter((f: any) => f.offset <= spent + 1e-9); + expect(eased.length).toBeGreaterThan(10); // keyed finely while it runs + const scale = (f: any) => parseFloat(/scale\(([^)]*)\)/.exec(f.transform)![1]); + const jump = Math.abs(there.scale - seen.scale); + expect(jump).toBeGreaterThan(0.05); // the pop this pick used to be + eased.slice(1).forEach((f: any, i: number) => expect(Math.abs(scale(f) - scale(eased[i]))).toBeLessThan(jump / 4)); + expect(run.keyframes.at(-1).offset).toBe(1); + s.dispose(); + }); + + describe('the ease of a mode pick stays inside the fit of the card slide', () => { + // The baked Vienna: its distances and its two bounds, as shipped. + const root = join(process.cwd(), 'public', 'ridge'); + const dir = parseIndex(JSON.parse(readFileSync(join(root, 'index.json'), 'utf8'))).places.vienna; + const vienna = parseManifest(JSON.parse(readFileSync(join(root, dir, 'manifest.json'), 'utf8')), `${dir}/`); + const FIT_PX_MAX = 24; // scripts/ridge-bake/export.py + /** The baker's `fit_px` (export.py): the worst error, in card px, of a card at distance `d` metres seen from offset `r` at camera angle `phiDeg`, against its best line over the widest field, the continuous error (the line by the trapezoid rule on 1025 samples, the error on the same). */ + const fitPx = (d: number, r: number, phiDeg: number, n = 1025): number => { + const phi = (phiDeg * Math.PI) / 180; + const half = (HFOV_MAX_DEG * Math.PI) / 360; + const b = Array.from({ length: n }, (_, i) => -half + (2 * half * i) / (n - 1)); + const a = b.map((x) => Math.atan2(d * Math.sin(x) - r * Math.sin(phi), d * Math.cos(x) - r * Math.cos(phi))); + const w = (i: number) => (i === 0 || i === n - 1 ? 0.5 : 1); + let sw = 0; + let sa = 0; + let sab = 0; + let sbb = 0; + a.forEach((y, i) => { + sw += w(i); + sa += w(i) * y; + sab += w(i) * y * b[i]; + sbb += w(i) * b[i] * b[i]; + }); + const mean = sa / sw; + const s = sab / sbb; + return (Math.max(...a.map((y, i) => Math.abs(y - (mean + s * b[i])))) * 180) / Math.PI * vienna.view.pxPerDegH; + }; + // The baker holds r_max for the NEAREST solid terrain each card draws in each tile, not its median distance_m (export.py pack); the manifest carries only the median. + // Vienna's nearest solid pixel is 500.4523 m (the baker's report, in every card 0 tile terrain stands at the 500 m near clip to within a metre), so that is the distance that binds, beside the medians. + const NEAREST_TERRAIN_M = 500.4523; + const distances = [NEAREST_TERRAIN_M, ...vienna.tiles.flatMap((row) => row.flatMap((e) => (e ? [e.distanceM] : [])))]; + /** The worst of every card of the bake at the camera angle `phiDeg` and offset `r`. */ + const worstPx = (r: number, phiDeg: number): number => Math.max(...distances.map((d) => fitPx(d, r, phiDeg))); + /** The same over the six nearest cards and 129 samples (the trapezoid rule is exact to a few thousandths of a pixel there): the nearest cards bind, and a property run asks it thousands of times. */ + const nearest = [...distances].sort((a, b) => a - b).slice(0, 6); + const quickPx = (r: number, phiDeg: number): number => Math.max(...nearest.map((d) => fitPx(d, r, phiDeg, 129))); + const w2 = windowFor(vienna.view, 400, 800); + /** The offset a keyframe's pose was made from: the one `cardPose` gives the transform at this heading and camera angle (a scan, then a finer one), with how far it is off. */ + const offsetOf = (transform: string, heading: number, phi: number): { r: number; miss: number } => { + const m = /translate3d\((-?[\d.e+-]+)px,0,0\) scale\((-?[\d.e+-]+)\)/.exec(transform)!; + const want = { shiftPx: Number(m[1]), scale: Number(m[2]) }; + const miss = (r: number) => { + const p = cardPose(vienna, 0, heading, phi, r, w2); + return Math.hypot(p.shiftPx - want.shiftPx, (p.scale - want.scale) * 400); + }; + let best = { r: 0, miss: Infinity }; + for (const step of [0.5, 0.02, 0.001]) { + const from = best.miss === Infinity ? -300 : best.r - 20 * step; + const to = best.miss === Infinity ? 300 : best.r + 20 * step; + for (let r = from; r <= to; r += step) { + const e = miss(r); + if (e < best.miss) best = { r, miss: e }; + } + } + return best; + }; + /** Every (camera angle, offset) a stretch of keyframes poses card 0 from, recovered from the transforms, from the pick on. */ + const pairsOf = (box: any, at: number): { phi: number; r: number; ms: number; miss: number }[] => { + const keys = live(box)[0].keyframes; + return keys.map((f: any, n: number) => { + const ms = (f.offset ?? n / (keys.length - 1)) * SEGMENT_S * 1000; + const phi = poseAt(at + ms).phi; + return { phi, ms, ...offsetOf(f.transform, poseAt(at + ms).h, phi) }; + }); + }; + const pick = (from: { mode: 'both' | 'offset'; speed: number; waitS: number }, to: 'both' | 'offset') => { + setCamera({ mode: from.mode, speedDegPerS: from.speed, offsetM: 200 }); + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(vienna) })!; + const at = T0 + from.waitS * 1000; + vi.mocked(performance.now).mockReturnValue(at); + setCamera({ mode: to }, at); + const got = pairsOf(rigOf(parent).children[2], at); + s.dispose(); + return got; + }; + + it('measures the fit as the baker does: Vienna sits at the bound at its two offsets, and above it past them', () => { + const { rMaxM, rMaxForwardM } = vienna.camera; + expect([rMaxM, rMaxForwardM]).toEqual([95.8, 198.4]); + const circle = Array.from({ length: 24 }, (_, i) => i * 15); + expect(Math.max(...circle.map((phi) => worstPx(rMaxM, phi)))).toBeGreaterThan(FIT_PX_MAX - 0.5); + expect(Math.max(...circle.map((phi) => worstPx(rMaxM, phi)))).toBeLessThanOrEqual(FIT_PX_MAX + 0.05); + expect(worstPx(rMaxForwardM, 0)).toBeGreaterThan(FIT_PX_MAX - 0.5); + expect(worstPx(rMaxForwardM, 0)).toBeLessThanOrEqual(FIT_PX_MAX + 0.05); + expect(worstPx(200, 90)).toBeGreaterThan(FIT_PX_MAX); // the blend the ease used to pass through + expect(worstPx(rMaxForwardM + 1, 0)).toBeGreaterThan(FIT_PX_MAX); // past the forward bound, and the circle's bound is not the forward one + expect(Math.max(...circle.map((phi) => worstPx(rMaxM + 1, phi)))).toBeGreaterThan(FIT_PX_MAX); + }); + + [ + { name: 'offset-only to both from the camera a quarter round', from: { mode: 'offset', speed: 12, waitS: 7.5 }, to: 'both' }, + { name: 'offset-only to both with the camera half way round', from: { mode: 'offset', speed: 12, waitS: 15 }, to: 'both' }, + { name: 'offset-only to both with the camera just off its heading', from: { mode: 'offset', speed: 12, waitS: 1.25 }, to: 'both' }, + { name: 'both to offset-only at the default speed', from: { mode: 'both', speed: 0.6, waitS: 3 }, to: 'offset' }, + { name: 'both to offset-only at the fastest turn', from: { mode: 'both', speed: 12, waitS: 3 }, to: 'offset' }, + ].forEach(({ name, from, to }) => { + it(`${name}: every keyframe is the pose of an angle and an offset inside the card fit, at Vienna's bounds`, () => { + const got = pick(from as any, to as any); + expect(got.length).toBeGreaterThan(12); + got.forEach((g) => expect(g.miss, `a pose of the camera at ${g.phi.toFixed(1)} degrees, ${g.r.toFixed(1)} m`).toBeLessThan(0.05)); + const worst = Math.max(...got.map((g) => worstPx(g.r, g.phi))); + expect(worst).toBeLessThanOrEqual(FIT_PX_MAX + 0.05); + // The angle and the offset take a stage each: never both between their ends at once. + const moving = (v: number[], i: number) => i > 0 && Math.abs(v[i] - v[i - 1]) > 1e-3; + const phis = got.map((g) => g.phi); + const rs = got.map((g) => g.r); + got.forEach((_, i) => expect(moving(phis, i) && moving(rs, i), `keyframe ${i}`).toBe(false)); + const last = got.at(-1)!; + expect(last.r).toBeCloseTo(to === 'both' ? Math.min(200, vienna.camera.rMaxForwardM) : vienna.camera.rMaxM, 1); // the offset owed: the default 200 or the forward bound, or the bound of the circling mode + if (to === 'both') expect(last.phi % 360).toBe(0); + }); + }); + + /** A transform's two numbers. */ + const parsed = (transform: string): { shift: number; scale: number } => { + const m = /translate3d\((-?[\d.e+-]+)px,0,0\) scale\((-?[\d.e+-]+)\)/.exec(transform)!; + return { shift: Number(m[1]), scale: Number(m[2]) }; + }; + /** What the compositor shows `ms` into an animation: the keyframes' straight lines. */ + const playedAt = (anim: any, ms: number): { shift: number; scale: number } => { + const keys: any[] = anim.keyframes; + const at = (k: number) => (keys[k].offset ?? k / (keys.length - 1)) * anim.options.duration; + let k = 1; + while (k < keys.length - 1 && at(k) < ms) k += 1; + const [a, b] = [parsed(keys[k - 1].transform), parsed(keys[k].transform)]; + const x = Math.min(1, Math.max(0, (ms - at(k - 1)) / (at(k) - at(k - 1)))); + return { shift: a.shift + (b.shift - a.shift) * x, scale: a.scale + (b.scale - a.scale) * x }; + }; + + describe('a pick made while an ease is under way, and a rebuild in the middle of one', () => { + const picks: { name: string; from: 'both' | 'offset'; waitS: number; then: ['still' | 'offset' | 'both', number][] }[] = [ + { name: 'offset-only to both, then to still a moment later', from: 'offset', waitS: 7.8, then: [['both', 0], ['still', 100]] }, + { name: 'offset-only to both, then back to offset-only', from: 'offset', waitS: 7.8, then: [['both', 0], ['offset', 100]] }, + { name: 'offset-only to both, to still, and to both again', from: 'offset', waitS: 7.8, then: [['both', 0], ['still', 100], ['both', 150]] }, + { name: 'offset-only to both, then offset-only as the angle lands', from: 'offset', waitS: 7.8, then: [['both', 0], ['offset', 295]] }, + { name: 'offset-only to both, then still with the offset on its way out', from: 'offset', waitS: 7.8, then: [['both', 0], ['still', 450]] }, + { name: 'both to offset-only, then to both before the offset is in', from: 'both', waitS: 3, then: [['offset', 0], ['both', 150]] }, + { name: 'both to offset-only, then to still, then to offset-only', from: 'both', waitS: 3, then: [['offset', 0], ['still', 100], ['offset', 120]] }, + ]; + picks.forEach(({ name, from, waitS, then }) => { + it(`${name}: every keyframe the last pick lays out is the pose of an angle and an offset inside the card fit`, () => { + setCamera({ mode: from, speedDegPerS: 12, offsetM: 200 }); + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(vienna) })!; + let at = T0 + waitS * 1000; + for (const [mode, after] of then) { + at += after; + vi.mocked(performance.now).mockReturnValue(at); + setCamera({ mode }, at); + } + const got = pairsOf(rigOf(parent).children[2], at); + got.forEach((g) => expect(g.miss, `a pose of the camera at ${g.phi.toFixed(1)} degrees, ${g.r.toFixed(1)} m`).toBeLessThan(0.05)); + const worst = Math.max(...got.map((g) => worstPx(g.r, g.phi))); + expect(worst).toBeLessThanOrEqual(FIT_PX_MAX + 0.05); + s.dispose(); + }); + }); + + it('a rebuild in the middle of an ease lands where the old scene was: the first frame of the new rig is the frame the old one showed', () => { + pending(); + for (const gap of [100, 250, 400, 550]) { + resetHeading(); + resetCamera(); + vi.mocked(performance.now).mockReturnValue(T0); + anchor(vienna.view.place.id, vienna.view.lookAzDeg, T0); + setCamera({ mode: 'offset', speedDegPerS: 12, offsetM: 200 }); + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(vienna) })!; + const at = T0 + 7_800; + vi.mocked(performance.now).mockReturnValue(at); + setCamera({ mode: 'both' }, at); + const old = rigOf(parent).children.map((box: any) => live(box)[0]); + vi.mocked(performance.now).mockReturnValue(at + gap); + window.dispatchEvent(new Event('resize')); + vi.advanceTimersByTime(300); // the debounced rebuild: a new rig at this clock + const now = rigOf(parent).children.map((box: any) => live(box)[0]); + now.forEach((a: any, i: number) => { + expect(a).not.toBe(old[i]); + const was = playedAt(old[i], gap); + const is = parsed(a.keyframes[0].transform); + expect(Math.abs(is.shift - was.shift), `card ${i} ${gap} ms into the ease`).toBeLessThan(2); + expect(Math.abs(is.scale - was.scale), `card ${i} ${gap} ms into the ease`).toBeLessThan(0.01); + }); + s.dispose(); + } + vi.useRealTimers(); + }); + }); + + describe('random sequences of picks, holds, speeds, offsets and rebuilds at random times', () => { + /** A seeded generator (mulberry32): a failing sequence is the seed it prints. */ + const random = (seed: number) => () => { + seed = (seed + 0x6d2b79f5) | 0; + let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; + const modes = ['still', 'offset', 'both'] as const; + const inside = ([lo, hi]: [number, number], v: number, slack = 1e-6) => v >= lo - slack && v <= hi + slack; + + /** Every pose a laid-out stretch passes through is one the baker's bound allows, at the offset it has: whenever the camera angle moves, the circle's bound holds at both ends; and the keyframes are the poses the heading owner has. */ + const checkLayout = (parent: any, label: string) => { + const boxes = rigOf(parent).children as any[]; + boxes.forEach((box) => expect(live(box)).toHaveLength(1)); + // The rig lays every card out from the owner's pose at the clock of each keyframe. + boxes.forEach((box) => { + const card = Number(box.id.slice(-1)); + const { keyframes, options, at } = live(box)[0]; + keyframes.forEach((f: any, n: number) => { + const t = at + (f.offset ?? n / (keyframes.length - 1)) * options.duration; + const p = poseAt(t); + const c = cardPose(vienna, card, p.h, p.phi, p.r, w2); + expect(f.transform, `${label}: card ${card} keyframe ${n}`).toBe(`translate3d(${c.shiftPx}px,0,0) scale(${c.scale})`); + }); + }); + // The pose itself, every 2 ms through the ease and every half second after. + const t0: number = live(boxes[0])[0].at; + const home = Math.max(t0, settledAt()); + const times: number[] = []; + for (let t = t0; t <= home + 2; t += 2) times.push(t); + for (let t = home; t <= t0 + SEGMENT_S * 1000; t += 500) times.push(t); + let last = poseAt(times[0]); + times.forEach((t, i) => { + const p = poseAt(t); + expect(inside(offsetRange(vienna, w2, 'both', p.phi), p.r), `${label}: phi ${p.phi}, r ${p.r} at +${t - t0} ms`).toBe(true); + if (i && Math.abs(p.phi - last.phi) > 1e-9) { + const circle = offsetRange(vienna, w2, 'offset'); + expect(inside(circle, p.r, 0.02) && inside(circle, last.r, 0.02), `${label}: the angle moves with r ${last.r} then ${p.r} at +${t - t0} ms`).toBe(true); + } + if (i % 40 === 0 || i === times.length - 1) expect(quickPx(p.r, p.phi), `${label}: fit at phi ${p.phi}, r ${p.r}`).toBeLessThanOrEqual(FIT_PX_MAX + 0.1); + last = p; + }); + }; + + let inEase = 0; + const sequence = (seed: number): number => { + const next = random(seed); + const pick = (xs: readonly T[]): T => xs[Math.floor(next() * xs.length)]; + resetHeading(); + resetCamera(); + const clock = vi.mocked(performance.now); + let now = T0; + clock.mockReturnValue(now); + anchor(vienna.view.place.id, vienna.view.lookAzDeg, T0); + setCamera({ mode: pick(modes), speedDegPerS: pick([0.6, 3, 12, -12, 0]), offsetM: pick([200, 98, -60, 0, 999]) }, now); + let { parent, canvas } = host(); + let scene = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(vienna) })!; + let rebuilds = 0; + for (let step = 0; step < 36; step += 1) { + const gap = pick([0, 20, 60, 100, 150, 299, 301, 450, 700, 3000, 24_500]); + now += gap; + clock.mockReturnValue(now); + vi.advanceTimersByTime(gap); + const label = `seed ${seed} step ${step}`; + const op = Math.floor(next() * 9); + const before = poseAt(now); + const fine = now <= settledAt(); // the old stretch is keyed every 50 ms here, a second apart after: the straight lines between keyframes are the pose only where they are close + const old = rigOf(parent).children.map((box: any) => live(box)[0]); + if (op <= 2) setCamera({ mode: pick(modes) }, now); + else if (op === 3) hold(next() * 1000 - 300, now); + else if (op === 4) setCamera({ speedDegPerS: pick([0.6, 3, 12, -12, 0, 7.5]) }, now); + else if (op === 5) setCamera({ offsetM: Math.round(next() * 600 - 300) }, now); + else if (op === 6) setCamera({ mode: pick(modes), speedDegPerS: pick([0.6, 12, -12]), offsetM: pick([200, 0, 50]) }, now); + else if (op === 7) { + window.dispatchEvent(new Event('resize')); + vi.advanceTimersByTime(300); + } else { + scene.dispose(); + ({ parent, canvas } = host()); + scene = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(vienna) })!; + } + if (op >= 7) { + rebuilds += 1; + if (fine) inEase += 1; + // A rebuild changes where nothing is: the owner's pose is the same before and after it, and the first frame laid out is the frame that was showing. + const after = poseAt(now); + expect(after.r, label).toBeCloseTo(before.r, 9); + expect(norm(after.phi), label).toBeCloseTo(norm(before.phi), 6); + expect(norm(after.h), label).toBeCloseTo(norm(before.h), 6); + rigOf(parent).children.forEach((box: any, i: number) => { + if (!fine) return; + const was = playedAt(old[i], now - old[i].at); + const is = parsed(live(box)[0].keyframes[0].transform); + // The new stretch is laid out from angles brought into [0, 360): a whole turn of the heading is a whole turn of the shift, the same picture. + const turn = is.scale * w2.plane.scale * vienna.view.pxPerDegH * 360; + const jump = Math.abs(is.shift - was.shift); + expect(Math.abs(jump - turn * Math.round(jump / turn)), `${label}: card ${i} popped at the rebuild`).toBeLessThan(3); + expect(Math.abs(is.scale - was.scale), `${label}: card ${i} popped at the rebuild`).toBeLessThan(0.02); + }); + } + checkLayout(parent, label); + } + scene.dispose(); + return rebuilds; + }; + + it('every pose laid out is inside the bound the baker set, and a rebuild never moves the view', () => { + pending(); + let rebuilds = 0; + for (let seed = 1; seed <= 24; seed += 1) rebuilds += sequence(seed); + expect(rebuilds).toBeGreaterThan(100); + expect(inEase).toBeGreaterThan(10); // and some of them in the middle of eases, not only at rest + vi.useRealTimers(); + }, 120_000); + }); + }); + + describe('under reduced motion there is no ease: the pose owed is the pose issued', () => { + const owed = (ring: typeof manifest, offset: number, phi: number, at = T0) => { + const p = cardPose(ring, 0, poseAt(at).h, phi, offset, windowFor(ring.view, 400, 800)); + return `translate3d(${p.shiftPx}px,0,0) scale(${p.scale})`; + }; + + it('lands on the offset the mode allows at the pick, each way, and the next pick starts from there', () => { + const ring = fixtureRing(); + motion.matches = true; + setCamera({ mode: 'both', speedDegPerS: 0.6, offsetM: 200 }); + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(ring) })!; + const box = () => rigOf(parent).children[2]; + expect(frame(box(), 0)).toBe(owed(ring, 200, 0)); + setCamera({ mode: 'offset' }); + expect(frame(box(), 0)).toBe(owed(ring, 98.2, 0)); // the clamp, at once: not the 200 m it showed + setCamera({ mode: 'both' }); + expect(frame(box(), 0)).toBe(owed(ring, 200, 0)); // and back, not the 98.2 it was left at + s.dispose(); + }); + + it('lands on the camera angle the mode owes when the setting arrives with the camera turned away from its heading', () => { + const ring = fixtureRing(); + setCamera({ mode: 'offset', speedDegPerS: 12, offsetM: 200 }); + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(ring) })!; + const at = T0 + 7_500; // a quarter round + vi.mocked(performance.now).mockReturnValue(at); + motion.matches = true; + motion.addEventListener.mock.calls.filter((c: any) => c[0] === 'change').forEach((c: any) => c[1]()); + expect(poseAt(at).phi).toBeCloseTo(90, 6); + setCamera({ mode: 'both' }, at); + expect(poseAt(at + 10_000).phi).toBe(0); + expect(frame(rigOf(parent).children[2], 0)).toBe(owed(ring, 200, 0, at)); + s.dispose(); + }); + }); + + it('keeps the angles, the transforms and the tile positions bounded after days of uptime: the rig normalizes before each stretch', () => { + const now = vi.mocked(performance.now); + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!; + const fiveDays = 5 * 86_400_000; + now.mockReturnValue(T0 + fiveDays); + setCamera({ offsetM: 20 }); // any change issues the next stretch from the clock now + const h = poseAt(T0 + fiveDays).h; + expect(h).toBeGreaterThanOrEqual(0); + expect(h).toBeLessThan(360 + 1); + expect(h).toBeCloseTo((214 + 0.6 * (fiveDays / 1000)) % 360, 4); // the view is where five days of turning put it + const rig = rigOf(parent); + const shifts = rig.children.flatMap((box: any) => + live(box)[0].keyframes.map((f: any) => Math.abs(Number(/translate3d\((-?[\d.e+-]+)px/.exec(f.transform)?.[1]))) + ); + expect(Math.max(...shifts)).toBeLessThan(100_000); // days of turning would be millions of px + rig.children.forEach((box: any) => + box.children.forEach((c: any) => expect(Math.abs(parseFloat(c.style.left))).toBeLessThan(100_000)) + ); + expect(mountedIds(rig).length).toBeGreaterThan(0); // the tiles the heading shows are mounted, not lost in the wrap + s.dispose(); + }); + }); + + it('a still draws the tiles of the arc in the host canvas, farthest card first, each card at its pose about the rig’s origin, at the heading now', () => { + const { parent, canvas } = host(); + createRidgeScene({ canvas, tier: 'still', sky: DAY, backdrop: litCards() }); + const drawn = images.filter((a) => (a[0] as any).id) as any[]; + expect(drawn.map((a) => a[0].id)).toEqual(['t2c1', 't2c0']); + expect(drawn[0][0].id.endsWith('c1')).toBe(true); + const dpr = 2; + drawn.forEach((a) => { + const card = Number(a[0].id.slice(-1)); + const p = posed(manifest, card, T0, win); + expect(a.k).toBe(p.scale); + expect(a.t).toEqual([(200 + p.shiftPx) * dpr, horizonY * dpr]); + const e = manifest.tiles[2][card]!; + const colDeg = 360 / view.ringW; + expect([a[1], a[2], a[3], a[4]]).toEqual([ + (180 - colDeg - 214) * k * dpr, + (e.top - view.horizonRow) * win.plane.scale * dpr, + (view.tileW + 2) * win.plane.scale * dpr, + e.h * win.plane.scale * dpr, + ]); + expect([a.alpha, a.op]).toEqual([1, 'source-over']); + }); + expect(parent.children).toEqual([canvas]); + }); + + describe('a still whose tiles arrive after its paint', () => { + /** A backdrop holding the tiles of `held`, and tiles that arrive afterwards: `arrive` holds one more and tells whoever listens, as the loader does. */ + const ring = parseManifest(wireManifest({}, 3, 32), '/d/'); // 32 tiles of 11.25 degrees: the rest view shows tiles 16 to 21 + const arriving = (held: number[]) => { + const all = ring.tiles.flatMap((row, tile) => + row.flatMap((e, card) => { + if (!e) return []; + const canvas = fakeEl('canvas'); + canvas.id = `t${String(tile).padStart(2, '0')}c${card}`; + canvas.width = 202; + return [{ tile, card, canvas: canvas as unknown as HTMLCanvasElement }]; + }) + ); + const lit = all.filter((t) => held.includes(t.tile)); + const heard = new Set<() => void>(); + const bd = { + manifest: ring, + ensure: vi.fn(async (_arc: Arc): Promise => undefined), + litTiles: () => lit, + onTile: (cb: () => void) => (heard.add(cb), () => void heard.delete(cb)), + dispose: vi.fn(), + }; + const arrive = (tile: number) => { + lit.push(...all.filter((t) => t.tile === tile)); + heard.forEach((cb) => cb()); + }; + return { bd, arrive, listeners: () => heard.size }; + }; + const drawnTiles = () => new Set(images.filter((a) => (a[0] as any).id).map((a: any) => a[0].id.slice(0, 3))); + const timers = () => { + vi.useFakeTimers(); + (window as any).setTimeout = setTimeout; + (window as any).clearTimeout = clearTimeout; + }; + afterEach(() => { + vi.useRealTimers(); + }); + + it('repaints once for a burst of arrivals, with every tile held by then, asks for nothing, and is done when the tiles stop', () => { + timers(); + const { bd, arrive } = arriving([18]); + const { canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'still', sky: DAY, backdrop: bd })!; + expect(drawnTiles()).toEqual(new Set(['t18'])); + const first = images.length; + arrive(17); + vi.advanceTimersByTime(100); + arrive(19); // a burst: the wait starts again + vi.advanceTimersByTime(200); + expect(images.length).toBe(first); // not yet + vi.advanceTimersByTime(60); + expect(drawnTiles()).toEqual(new Set(['t18', 't17', 't19'])); // one paint, with all of them + const second = images.length; + expect(second).toBeGreaterThan(first); + vi.advanceTimersByTime(600_000); + expect(images.length).toBe(second); // no loop, no timer left + expect(bd.ensure).not.toHaveBeenCalled(); + arrive(20); + vi.advanceTimersByTime(300); + expect(drawnTiles().has('t20')).toBe(true); // a straggler is drawn too + s.dispose(); + }); + + it('a still shows one pose: a tile that arrives half a minute late is drawn at the pose of the first paint, and a resize takes the pose of its own clock', () => { + timers(); + const { bd, arrive } = arriving([18]); + const { canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'still', sky: DAY, backdrop: bd })!; + const placed = (id: string) => images.filter((a) => (a[0] as any).id?.startsWith(id)).map((a: any) => [a.t, a[1], a[2], a[3], a[4], a.k]); + const first = placed('t18'); + expect(first.length).toBeGreaterThan(0); + images.length = 0; + vi.spyOn(performance, 'now').mockReturnValue(T0 + 30_000); // the clock has turned the heading 18 degrees on + arrive(17); + vi.advanceTimersByTime(300); + expect(drawnTiles()).toEqual(new Set(['t18', 't17'])); // the tile chosen for the first pose is on the canvas + expect(placed('t18')).toEqual(first); // and the old ones have not moved + expect(bd.ensure).not.toHaveBeenCalled(); + images.length = 0; + window.dispatchEvent(new Event('resize')); + vi.advanceTimersByTime(300); + expect(bd.ensure).toHaveBeenCalledTimes(1); // a new view: the tiles of the pose it takes + const arc = bd.ensure.mock.calls[0][0]; + expect((arc.fromDeg + arc.toDeg) / 2).toBeCloseTo(poseAt(T0 + 30_000).h, 6); + expect(placed('t18')).not.toEqual(first); + s.dispose(); + }); + + it('is the same after a settle from the live tier, and stops listening with the scene', () => { + timers(); + const { bd, arrive, listeners } = arriving([18]); + const { canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: bd })!; + arrive(17); + vi.advanceTimersByTime(1_000); + expect(images.length).toBe(0); // the live tier mounts tiles from its own timer: nothing is painted into the host canvas + runFrames(100, 400); // a poor frame rate: it settles to a still + const settled = images.length; + expect(drawnTiles()).toEqual(new Set(['t18', 't17'])); + arrive(19); + vi.advanceTimersByTime(300); + expect(images.length).toBeGreaterThan(settled); + expect(drawnTiles().has('t19')).toBe(true); + s.dispose(); + expect(listeners()).toBe(0); + const after = images.length; + arrive(20); + vi.advanceTimersByTime(1_000); + expect(images.length).toBe(after); + }); + }); + + it('settles to a still with the tiles painted when the frame rate is poor', () => { + const { parent, canvas } = host(); + createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() }); + runFrames(100, 400); + expect(images.filter((a) => (a[0] as any).id).length).toBeGreaterThan(0); + expect(parent.children).toEqual([canvas]); + }); + + it('with no backdrop it is the sky alone', () => { + const { parent, canvas } = host(); + createRidgeScene({ canvas, tier: 'full', sky: DAY }); + expect(parent.children).toEqual([canvas]); + expect(images.filter((a) => (a[0] as any).id)).toHaveLength(0); + }); + + it('asks the host canvas, and every canvas it makes, only for 2d: the tiles arrive lit', () => { + const { canvas } = host(); + const kinds: string[] = []; + const ask = (el: any) => { + const real = el.getContext; + el.getContext = vi.fn((k: string) => (kinds.push(k), real(k))); + }; + ask(canvas); + const make = doc.createElement; + doc.createElement = (t: string) => { + const el = make(t); + ask(el); + return el; + }; + const s = createRidgeScene({ canvas, tier: 'full', sky: night, backdrop: litCards() })!; + expect(kinds.length).toBeGreaterThan(0); + expect(kinds.every((k) => k === '2d')).toBe(true); + s.dispose(); + }); +}); + +describe('the scene wiring', () => { + it('sizes from the window when the canvas has no client size', () => { + const { canvas } = host(); + canvas.clientWidth = 0; + canvas.clientHeight = 0; + (window as any).innerWidth = 300; + (window as any).innerHeight = 500; + createRidgeScene({ canvas, tier: 'full', sky: DAY })!.dispose(); + expect([canvas.width, canvas.height]).toEqual([600, 1000]); + }); + + it('a burst of resizes rebuilds once, after 250 ms, and not after dispose', async () => { + vi.useFakeTimers(); + (window as any).setTimeout = setTimeout; + const { canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY })!; + const skies = () => draws.filter((d) => d === 'sky').length; + window.dispatchEvent(new Event('resize')); + vi.advanceTimersByTime(200); + window.dispatchEvent(new Event('resize')); + vi.advanceTimersByTime(200); + expect(skies()).toBe(1); + vi.advanceTimersByTime(60); + expect(skies()).toBe(2); + s.dispose(); + window.dispatchEvent(new Event('resize')); + vi.advanceTimersByTime(1000); + expect(skies()).toBe(2); + vi.useRealTimers(); + }); +}); diff --git a/src/app/features/scene/ridge/Ridge.ts b/src/app/features/scene/ridge/Ridge.ts index b0320b1b..b6f5d729 100644 --- a/src/app/features/scene/ridge/Ridge.ts +++ b/src/app/features/scene/ridge/Ridge.ts @@ -1,32 +1,21 @@ -/* eslint-disable no-param-reassign -- the bake writes into the canvases and layer records it is handed */ import type { Scene, SceneOptions } from '../Scene'; import { overlayRequested } from '../debugOverlays'; import { FrameSampler, FrameStats } from './probe'; import { skyColours, SkyColours, Srgb } from './skyColour'; import { paintSky as paintPhysicalSky } from './physicalSky'; -import { activeAt, drawStars, drawTwinkle as paintTwinkle, makeStars, Star } from './stars'; -import { bakeSlice, BakeParams, layerPaint } from './ridgeBake'; -import { - LAYERS, - LayerSpec, - edgeBlur, - HORIZON_TRACK_SHIFT, - layerSize, - scatterAlpha, - transmittance, -} from './ridgeWorld'; -import { hfovDeg } from './horizon'; -import { viewFor, VFOV_DEG } from './skyDome'; +import { cardArc, cardPose, HFOV_MAX_DEG, offsetRange, SEGMENT_S, sweepArc, windowFor } from './view'; +import type { Camera, CardPose, View } from './view'; +import type { TileCard } from './manifest'; +import { residentTiles } from './ring'; +import { freeze, normalize, poseAt as headingPose, setRange, settledAt, subscribe as onHeading, turnRate } from './heading'; +import type { Pose } from './heading'; +import { activeAt, drawTwinkle as paintTwinkle, slotsFor, Star } from './stars'; +import { STAR_COUNT } from './nightSkyData'; +import { alignTurns, panPx, plateCamera, plateSize, recentre, slackFor } from './skyTurn'; +import { nightBodies, paintNightBodies } from './nightBodies'; +import type { NightBodies } from './nightBodies'; import { drawRainTile, RAIN_TILES } from './rain'; - -/** One chunk's bake: `ms` is the summed task time, `maxTaskMs` the longest single task; `first` marks the bake of the first view. */ -export interface BakeRecord { - layer: number; - chunk: number; - ms: number; - maxTaskMs: number; - first: boolean; -} +import type { Arc, Backdrop, LitTile } from './Backdrop'; export type RidgeOptions = Pick & { /** Show the rAF median/p95 readout. Default: the page URL has `?probe=1`, where `debug` allows it. */ @@ -37,8 +26,10 @@ export type RidgeOptions = Pick & { onProbe?: (s: FrameStats & { still: boolean }) => void; /** The sky's colours; default `skyColours()`, the one function to replace with Void's sun.js. */ sky?: SkyColours; - /** Called after each chunk is baked (a chunk is one layer's stretch of world-x): the cost record. */ - onBake?: (b: BakeRecord) => void; + /** The baked ridge cards by tile, lit for `sky` (`Backdrop.ts`), the arc around the heading already made; none is the sky-only scene (`view.ts` FALLBACK_VIEW). The scene owns it from here and disposes it with itself. */ + backdrop?: Backdrop; + /** Draw the constellation lines over the stars (a hidden extra, `skyState.ts`); only a night sky shows them. */ + lines?: boolean; }; const css = (c: Srgb): string => `rgb(${c[0]},${c[1]},${c[2]})`; @@ -66,20 +57,21 @@ function drawSun( } /** - * The host canvas's sky: the physical sky (`physicalSky.ts`) as a small grid of display pixels, scaled up smoothly (it is a soft - * field); without one, the three-stop gradient. + * A canvas's sky: the physical sky (`physicalSky.ts`) seen through `camera` as a small grid of display pixels, scaled up smoothly (it is a soft + * field); without one, the three-stop gradient. `cssW` and `cssH` are the canvas's size in CSS px, which `camera`'s field of view spans. */ function paintSky( canvas: HTMLCanvasElement, sky: SkyColours, + camera: Camera | undefined, cssW: number, cssH: number, makeCanvas: () => HTMLCanvasElement -): boolean { +): { ok: boolean; px?: ReturnType } { const ctx = context2d(canvas); - if (!ctx) return false; - if (sky.physical) { - const px = paintPhysicalSky(sky.physical, cssW, cssH); + if (!ctx) return { ok: false }; + if (sky.physical && camera) { + const px = paintPhysicalSky(sky.physical, cssW, cssH, camera); const small = makeCanvas(); small.width = px.w; small.height = px.h; @@ -92,7 +84,7 @@ function paintSky( ctx.imageSmoothingQuality = 'high'; ctx.drawImage(small, 0, 0, canvas.width, canvas.height); if (px.sunDisc) drawSun(ctx, px.sunDisc, canvas.width, canvas.height); - return true; + return { ok: true, px }; } } const g = ctx.createLinearGradient(0, 0, 0, canvas.height); @@ -102,222 +94,103 @@ function paintSky( g.addColorStop(1, css(sky.horizon)); ctx.fillStyle = g; ctx.fillRect(0, 0, canvas.width, canvas.height); - return true; + return { ok: true }; } const clock = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now()); -type Size = ReturnType; - -const SCATTER_STOPS = 16; - -/** Warm in-scatter over the silhouette only (source-atop): a horizontal gradient over the chunk's world-x. */ -function scatter( - ctx: CanvasRenderingContext2D, - spec: LayerSpec, - sky: SkyColours, - widthPx: number, - heightPx: number, - t0: number, - tPerPx: number, - bandX = 0, - bandW = widthPx -) { - if (sky.sunAzimuth === undefined || transmittance(spec) >= 1) return; // the nearest layer takes none - const g = ctx.createLinearGradient(0, 0, widthPx, 0); - const [r, gr, b] = sky.horizon; - for (let k = 0; k <= SCATTER_STOPS; k += 1) { - const a = scatterAlpha(spec, sky, t0 + (tPerPx * widthPx * k) / SCATTER_STOPS); - g.addColorStop(k / SCATTER_STOPS, `rgba(${r},${gr},${b},${a})`); - } - ctx.globalCompositeOperation = 'source-atop'; - ctx.fillStyle = g; - ctx.fillRect(bandX, 0, bandW, heightPx); - ctx.globalCompositeOperation = 'source-over'; -} - -/** A chunk's bake in slices: `step(budgetMs)` returns true once the chunk is on its canvas. */ -interface Job { - step(budgetMs: number): boolean; +/** The rig: one box per card, each holding that card's resident tiles and carried by one animation of its pose. */ +interface Rig { + el: HTMLElement; + anims: (Animation | undefined)[]; + /** Issue the next stretch of every card's motion from the heading owner's clock now (a tab shown again). */ + reissue: () => void; + /** Take the viewer's mode and speed to the heading owner again, then reissue (reduced motion switched). */ + sync: () => void; + /** Stop the residency timer and the subscriptions. */ + stop: () => void; } /** - * One layer's stretch of world-x `[m * chunk, (m + 1) * chunk)` painted onto `el`, in three phases of - * column bands, each band sized to the task budget by measuring the last one: bake the pixels - * (`bakeSlice`), put them on a canvas with the in-scatter, and (where the 2D `filter` exists) blur them - * into `el`. The blur needs neighbours, so the pixels are baked `pad` columns past both ends and - * the bottom into a scratch canvas this job owns, and each blurred band reads `pad` columns either side of - * itself: seams show no fade. The scratch is made when the job first runs and dropped when it ends. + * The sky of a live scene: one element, wider than the viewport, holding the painted sky (every real body baked into it) and, with stars, the twinkling + * stars' canvas over it. One animation slides it with the heading (`skyTurn.ts`). Replaced, element and all, when the heading nears its edge. */ -function chunkJob( - el: HTMLCanvasElement, - makeCanvas: () => HTMLCanvasElement, - spec: LayerSpec, - sky: SkyColours, - size: Size, - viewH: number, - scale: number, - m: number, - record: (ms: number, maxTaskMs: number) => void -): Job | null { - const ctx = context2d(el); - if (!ctx) return null; - const blur = edgeBlur(spec) * scale; - const pad = blur > 0 && 'filter' in ctx ? Math.ceil(3 * blur) : 0; - const cols = size.chunk + 2 * pad; - const rows = size.height + pad; - const params: BakeParams = { - spec, - sky, - horizonView: - spec.horizon && sky.physical - ? { - azimuthDeg: viewFor(sky.physical.sun, size.period / viewH).azimuthDeg, - hfovDeg: hfovDeg(size.period / viewH, VFOV_DEG), - } - : undefined, - period: size.period, - scale, - viewH, - rows, - bandH: size.height, - px0: m * size.chunk - pad, - cols, - }; - const paint = layerPaint(spec, sky); - const t0World = params.px0 / size.period; - let scratch: HTMLCanvasElement | undefined; - let sctx: CanvasRenderingContext2D | null = ctx; - let img: ImageData | undefined; - /** 0 bake, 1 put and in-scatter, 2 blur into el; a chunk with no blur ends after 1. */ - let phase = 0; - let pos = 0; - let sliceCols = 32; - let total = 0; - let longest = 0; - const last = pad > 0 ? 2 : 1; - const start = (): boolean => { - if (pad > 0) { - scratch = makeCanvas(); - scratch.width = cols; - scratch.height = rows; - sctx = context2d(scratch); - } else { - el.width = size.chunk; - el.height = size.height; - } - if (!sctx) return false; - img = sctx.createImageData(cols, rows); - return true; - }; - const work = (x: number, n: number) => { - if (!img || !sctx) return; - if (phase === 0) bakeSlice(img.data, params, paint, x, x + n); - else if (phase === 1) { - sctx.putImageData(img, 0, 0, x, 0, n, rows); - scatter(sctx, spec, sky, cols, rows, t0World, 1 / size.period, x, n); - } else { - // One draw: a blurred draw cut into bands costs more in the margins than it saves in task length. - ctx.drawImage(scratch as HTMLCanvasElement, -pad, 0); - } - }; - return { - step(budgetMs) { - const t0 = clock(); - // Allocating the canvases and the pixel buffer is a task of its own. - if (!img) { - if (!start()) return true; - if (Number.isFinite(budgetMs)) { - total += clock() - t0; - longest = Math.max(longest, clock() - t0); - return false; - } - } - while (phase <= last && clock() - t0 < budgetMs) { - const end = phase === 2 ? size.chunk : cols; - if (pos === 0 && phase === 2) { - el.width = size.chunk; - el.height = size.height; - ctx.filter = `blur(${blur}px)`; - } - const n = phase === 2 ? end : Math.min(end - pos, sliceCols); - const s0 = clock(); - work(pos, n); - pos += n; - const dt = Math.max(clock() - s0, 0.02); - sliceCols = Number.isFinite(budgetMs) - ? Math.max(8, Math.min(512, Math.round((n * budgetMs * 0.4) / dt))) - : cols; - if (pos >= end) { - if (phase === 2) ctx.filter = 'none'; - phase += 1; - pos = 0; - if (phase === 1 || phase === 2) sliceCols = Number.isFinite(budgetMs) ? 64 : cols; - } - } - const dt = clock() - t0; - total += dt; - longest = Math.max(longest, dt); - const done = phase > last; - if (done) { - img = undefined; - if (scratch) { - scratch.width = 0; - scratch.height = 0; - } - scratch = undefined; - record(total, longest); - } - return done; - }, - }; -} - -interface Chunk { - el: HTMLCanvasElement; - /** World chunk index it holds or is being baked to hold. */ - id: number; - job?: Job; - ready: boolean; -} - -/** One layer: a track that drifts by one chunk per animation, holding three chunk canvases. */ -interface LayerState { - spec: LayerSpec; - track: HTMLElement; - /** Slot 0 and 1 are what the window can see; slot 2 is the one ahead, baked in the background. */ - slots: Chunk[]; +interface Plate { + el: HTMLElement; + /** The twinkle canvas of this plate, over its sky; absent in a day sky. */ + twinkle?: HTMLCanvasElement; + /** The stars this plate was painted with, by catalogue index: the identity the twinkle schedule is keyed by. */ + stars: ReadonlyMap; + /** Device pixels per CSS px of the plate's canvases (capped by `PLATE_MAX_PX`). */ + ratio: number; + /** Degrees of sky it holds beyond the viewport each side (`skyTurn.ts` `slackFor`, at the speed it was painted for). */ + slack: number; + /** The compass azimuth the plate is centred on, unwrapped to the heading owner's turn. */ + centre: number; + /** The one animation that slides it. */ anim?: Animation; + /** + * Paint a new plate about the heading in this one's place when the heading is near its edge, or the speed in force needs more slack than it has; `periodMs`: + * the real period of the residency tick. True when it did, and then the slide is not keyed yet: `key` it, from a clock read after this. + */ + refit: (periodMs: number) => boolean; + /** Key the slide from `t0` (ms), the heading owner's clock read after the plate was last painted; `play`: the motion runs. */ + key: (t0: number, frozen: boolean, play: boolean) => void; + /** The residency tick: refit, and key from the clock after the paint if it painted. */ + tend: (periodMs: number) => void; + stop: () => void; } interface Built { - rig: HTMLElement; - layers: LayerState[]; - sway?: Animation; - size: Size; - /** CSS px to canvas px, and the viewport's height in canvas px, as baked. */ - scale: number; - viewH: number; - /** Makes a canvas, bound to the document the scene was built in. */ - makeCanvas: () => HTMLCanvasElement; - /** The twinkling stars' own canvas, between the sky and the ridges; absent in a day sky and in 'still'. */ - twinkle?: HTMLCanvasElement; + /** The sky and its twinkling stars, under the rig; absent in 'still' (the sky is painted into the host canvas) and in a sky with no physical model (a gradient in the host canvas). */ + plate?: Plate; + /** The ridge cards' rig, over the plate and under the rain; absent in 'still' (the cards are drawn into the host canvas). */ + rig?: Rig; /** The rain's tiles and their falling, present only when the weather rains (`rain.ts`). */ rain?: { els: HTMLElement[]; anims: (Animation | undefined)[] }; } -/** Yaw and pitch: the camera's slow sway, a loop of this many seconds over the whole rig. */ -const SWAY_SECONDS = 150; -const SLICE_BUDGET_MS = 6; - /** The twinkle overlay redraws at most this often: the swings are 2 to 7 s, no need for 60 fps. */ const TWINKLE_FRAME_MS = 50; +/** + * A card's motion is issued as one animation of SEGMENT_S seconds (`view.ts`), a keyframe each second sampled from the heading owner (`heading.ts`) and the + * viewer's offset, and issued again once REISSUE_FRAC of it has run, so the compositor always has the next stretch before it needs it. Authored. + */ +const REISSUE_FRAC = 0.8; +/** How often the arc of tiles ahead is asked for and the mounted tiles are brought up to date. */ +export const RESIDENCY_MS = 500; + +/** Keyframe spacing while an ease runs, ms: fine enough that the straight lines between them are the smoothstep to a pixel. */ +const EASE_KEY_MS = 50; +/** The instants of a stretch keyed finely up to `easeMs`, then every second to SEGMENT_S: ms from the stretch's start, ascending, ending at the stretch's length. */ +const easeTimes = (easeMs: number): number[] => { + const times: number[] = []; + for (let ms = 0; ms < easeMs; ms += EASE_KEY_MS) times.push(ms); + times.push(easeMs); + for (let ms = (Math.floor(easeMs / 1000) + 1) * 1000; ms <= SEGMENT_S * 1000; ms += 1000) times.push(ms); + return times; +}; + +/** + * The keyframes of a stretch of motion from `t0` (ms), the transform at each instant from `transformAt`: a keyframe a second for SEGMENT_S seconds, finely + * keyed while an ease of the heading owner runs, constant under reduced motion. The cards and the sky are keyed by it alike, so they turn together. + */ +const stretch = (t0: number, frozen: boolean, transformAt: (t: number) => string): Keyframe[] => { + if (frozen) { + const at = transformAt(t0); + return [{ transform: at }, { transform: at }]; + } + const easeMs = Math.min(SEGMENT_S * 1000, Math.max(0, settledAt() - t0)); + if (easeMs > 0) return easeTimes(easeMs).map((ms) => ({ transform: transformAt(t0 + ms), offset: ms / (SEGMENT_S * 1000) })); + return Array.from({ length: SEGMENT_S + 1 }, (_, n) => ({ transform: transformAt(t0 + n * 1000) })); +}; + /** * The ridge scene: same contract as `createScene` ({ login, dispose }, null for "keep the CSS - * ground"), no WebGL. The layers are painted once on the CPU; per frame the only work is the - * browser compositor sliding each layer with a CSS transform (a Web Animation, no script). The host - * canvas holds the baked sky; it and the layers' parent must be positioned, and the canvas should fill it. + * ground"). It draws the sky, the stars, the lit ridge cards when given a `backdrop` (none: the sky alone) and the rain. The scene itself + * requests no WebGL: the cards arrive lit (`lightCards.ts`, once per scene build) and only 2D contexts are asked of the host canvas. The host canvas holds the baked sky; it and + * its parent must be positioned, and the canvas should fill the parent. */ export function createRidgeScene(opts: RidgeOptions): Scene | null { const tier = opts.tier ?? 'full'; @@ -330,17 +203,17 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { const reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)'); let built: Built | undefined; - let field: Star[] = []; let twRaf = 0; let twLast = 0; + /** Paint a plate's twinkle canvas at t seconds, or clear it (set by the plate the scene is up with). */ + let paintTwinkleOf: (of: Pick, t?: number) => void = () => undefined; let still = tier === 'still'; - let jobTimer: ReturnType | undefined; - let queue: Chunk[] = []; - let generation = 0; let disposed = false; let raf = 0; let readout: HTMLElement | undefined; let resizeTimer = 0; + /** The pose a still shows: taken at its first paint and drawn at every repaint after, tile arrivals included; a resize takes a new one. A still has no clock. */ + let stillPose: Pose | undefined; const sampler = new FrameSampler(); const viewSize = () => { @@ -349,15 +222,13 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { return { w, h, scale: (window.devicePixelRatio || 1) >= 2 ? 2 : 1 }; }; - const teardownLayers = () => { - generation += 1; - clearTimeout(jobTimer); - jobTimer = undefined; - queue = []; - built?.sway?.cancel(); - built?.layers.forEach((l) => l.anim?.cancel()); - built?.rig.remove(); - built?.twinkle?.remove(); + const makeCanvas = () => document.createElement('canvas'); + + const teardown = () => { + built?.plate?.stop(); + built?.rig?.stop(); + built?.rig?.anims.forEach((a) => a?.cancel()); + built?.rig?.el.remove(); built?.rain?.anims.forEach((a) => a?.cancel()); built?.rain?.els.forEach((e) => e.remove()); cancelAnimationFrame(twRaf); @@ -368,111 +239,7 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { /** True while there is nothing to paint on: the canvas has no client size and the window itself is 0 x 0 (`viewSize` falls back to the window). */ const hasNoArea = () => { const { w, h, scale } = viewSize(); - const size = layerSize(w, h, scale); - return size.period < 1 || size.height < 1 || Math.round(h * scale) < 1; - }; - - /** - * Start baking chunk `c` of layer `l`. `first` runs it to the end in this task (the first view); - * otherwise it joins the queue, which `pump` works through in short tasks. False when the canvas has no 2D context. - */ - const bake = (l: LayerState, c: Chunk, first: boolean): boolean => { - if (!built) return false; - const { scale, viewH, makeCanvas } = built; - const job = chunkJob( - c.el, - makeCanvas, - l.spec, - sky, - built.size, - viewH, - scale, - c.id, - (ms, maxTaskMs) => { - c.ready = true; - c.job = undefined; - opts.onBake?.({ layer: l.spec.index, chunk: c.id, ms, maxTaskMs, first }); - } - ); - if (!job) return false; - c.ready = false; - c.job = job; - if (first) job.step(Infinity); - else queue.push(c); - return true; - }; - - const pump = () => { - if (jobTimer !== undefined || !queue.length) return; - const gen = generation; - jobTimer = setTimeout(() => { - jobTimer = undefined; - if (gen !== generation) return; - const c = queue[0]; - if (!c.job || c.job.step(SLICE_BUDGET_MS)) queue.shift(); - pump(); - }, 0); - }; - - /** Bake a still-queued chunk to the end now: only when the drift has caught up with the background work. */ - const flush = (c: Chunk) => { - while (c.job && !c.job.step(Infinity)); - queue = queue.filter((q) => q !== c); - }; - - const chunkSeconds = (spec: LayerSpec, size: Size) => (spec.seconds * size.chunk) / size.period; - - /** One chunk of drift as one animation, holding its end until `rotate` hands the track the next chunk. */ - const startDrift = (l: LayerState, onEnd: (l: LayerState) => void) => { - if (!built || !Number.isFinite(l.spec.seconds)) return; // the horizon layer does not drift - const { size, scale } = built; - l.anim = l.track.animate?.( - [ - { transform: 'translate3d(0,0,0)' }, - { transform: `translate3d(${-size.chunk / scale}px,0,0)` }, - ], - { duration: chunkSeconds(l.spec, size) * 1000, easing: 'linear', fill: 'forwards' } - ); - if (l.anim) l.anim.onfinish = () => onEnd(l); - }; - - /** - * The window has drifted one chunk. Slot 1 is now slot 0 and slot 2 slot 1, at the same screen place - * (the track restarts at 0 and the chunks move one slot left in the same task, so nothing jumps); the - * canvas that left becomes slot 2 and is baked with the world one chunk further on, off the critical path. - */ - const rotate = (l: LayerState) => { - if (!built || !built.layers.includes(l)) return; - const [s0, s1, s2] = l.slots; - flush(s1); - flush(s2); - l.slots = [s1, s2, s0]; - s0.id = s2.id + 1; - const { size, scale } = built; - l.slots.forEach((c, i) => { - c.el.style.left = `${(i * size.chunk) / scale}px`; - }); - l.anim?.cancel(); - startDrift(l, rotate); - bake(l, s0, false); - pump(); - syncPlayState(); - }; - - /** The camera's slow yaw and pitch: the rig eases sideways (up to 5% of the width) and down (up to 3% of the height) and back, in a loop. */ - const startSway = (rig: HTMLElement, w: number, h: number) => { - const x = 0.05 * w; - const y = 0.03 * h; - const at = (fx: number, fy: number) => `translate3d(${-x * fx}px,${y * fy}px,0)`; - return rig.animate?.( - [ - { transform: at(0, 0), offset: 0 }, - { transform: at(0.55, 1), offset: 0.35 }, - { transform: at(1, 0.3), offset: 0.7 }, - { transform: at(0, 0), offset: 1 }, - ], - { duration: SWAY_SECONDS * 1000, iterations: Infinity, easing: 'ease-in-out' } - ); + return Math.round(w * scale) < 1 || Math.round(h * scale) < 1; }; /** @@ -525,107 +292,341 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { return { els, anims }; }; - /** Bake the sky, then the layers. Returns false when a 2D context is missing or there is no area yet. */ - const build = (): boolean => { - teardownLayers(); - // A zero-size canvas throws on drawImage; wait for the first resize that gives the host an area. - if (hasNoArea()) return false; - const { w, h, scale } = viewSize(); - const size = layerSize(w, h, scale); - canvas.width = size.period; - canvas.height = Math.round(h * scale); - if (!paintSky(canvas, sky, w, h, () => document.createElement('canvas'))) return false; - // Every star is baked into the sky; the twinkling ones get their own canvas, which a per-frame - // pass clears and paints over. 'still' has no overlay. - const stars = makeStars(sky, w, h); - const skyCtx = context2d(canvas); - if (skyCtx) drawStars(skyCtx, stars, canvas.width, canvas.height, scale); - let twinkle: HTMLCanvasElement | undefined; - if (stars.length && tier !== 'still') { - twinkle = document.createElement('canvas'); - twinkle.width = canvas.width; - twinkle.height = canvas.height; - twinkle.setAttribute('aria-hidden', 'true'); - Object.assign(twinkle.style, { + /** Where a tile sits in a card's box, in viewport px from the centre column and the horizon: its left edge (one overlap column before its interior) and its band. */ + const tileBox = (view: View, scale: number, lt: LitTile, turn: number, entry: TileCard) => { + const colDeg = 360 / view.ringW; + const az = turn * 360 + (lt.tile * 360) / view.tiles - colDeg; + return { + left: (az - view.lookAzDeg) * view.pxPerDegH * scale, + top: (entry.top - view.horizonRow) * scale, + w: (view.tileW + 2) * scale, + h: entry.h * scale, + }; + }; + + /** + * The ridge over the sky: one box per card, farthest first (DOM order is paint order, stacking is by order alone). A box spans the viewport with its + * transform origin on the horizon centre and holds the resident tiles of its card at their azimuth; one animation per box carries its pose + * (`view.ts` `cardPose`) over SEGMENT_S seconds of the heading owner's clock. A timer asks the backdrop for the arc ahead and mounts what it has made. + */ + const startRig = (bd: Backdrop, w: number, h: number, plate?: Plate): Rig => { + const { view } = bd.manifest; + const win = windowFor(view, w, h); + const planeTop = h - win.plane.bottom - win.plane.h; + const horizonY = planeTop + view.horizonRow * win.plane.scale; + const k = bd.manifest.cards.length; + const el = document.createElement('div'); + el.setAttribute('aria-hidden', 'true'); + Object.assign(el.style, { + position: 'absolute', + left: '0', + top: '0', + width: '100%', + height: '100%', + overflow: 'hidden', + pointerEvents: 'none', + }); + const boxes: HTMLElement[] = []; + for (let i = k - 1; i >= 0; i -= 1) { + const box = document.createElement('div'); + box.id = `card-${i}`; + Object.assign(box.style, { position: 'absolute', left: '0', top: '0', - width: '100%', - height: '100%', + width: `${w}px`, + height: `${h}px`, + transformOrigin: `${w / 2}px ${horizonY}px`, + willChange: 'transform', pointerEvents: 'none', }); - parent.appendChild(twinkle); + el.appendChild(box); + boxes[i] = box; } - field = stars; - // The rig carries the camera's sway; each layer's track carries its drift; chunks sit on the track. - const rig = document.createElement('div'); - rig.setAttribute('aria-hidden', 'true'); - Object.assign(rig.style, { - position: 'absolute', - left: '0', - bottom: '0', - width: '100%', - height: '100%', - pointerEvents: 'none', - willChange: 'transform', - }); - const layers: LayerState[] = LAYERS.map((spec) => { - const track = document.createElement('div'); - Object.assign(track.style, { - position: 'absolute', - left: spec.horizon ? `${(-HORIZON_TRACK_SHIFT * size.period) / scale}px` : '0', - bottom: '0', - width: `${size.period / scale}px`, - height: `${size.height / scale}px`, - willChange: 'transform', - }); - const slots: Chunk[] = [0, 1, 2].map((i) => { - const el = document.createElement('canvas'); - el.width = size.chunk; - el.height = size.height; - Object.assign(el.style, { - position: 'absolute', - bottom: '0', - width: `${size.chunk / scale}px`, - height: `${size.height / scale}px`, - }); - return { el, id: i, ready: false }; - }); - return { spec, track, slots }; - }); - const doc = document; - built = { - rig, - layers, - size, - scale, - viewH: canvas.height, - makeCanvas: () => doc.createElement('canvas'), - twinkle, + const anims: (Animation | undefined)[] = new Array(k).fill(undefined); + freeze(reducedMotion?.matches === true, clock()); // reduced motion turns nothing, whatever the viewer chose + /** A card's pose at the clock `t`: the heading owner's pose (view direction, camera angle, offset), the one place any of them is decided. */ + const poseAt = (card: number, t: number): CardPose => { + const p = headingPose(t); + return cardPose(bd.manifest, card, p.h, p.phi, p.r, win); }; - // First view: only slot 0 of each layer, in this task. The window sees nothing else for the first - // fifth of a chunk's drift; slots 1 and 2 are baked in short tasks behind it. - if (!layers.every((l) => bake(l, l.slots[0], true))) { - teardownLayers(); - return false; + const transform = (p: CardPose) => `translate3d(${p.shiftPx}px,0,0) scale(${p.scale})`; + let issuedAt = 0; + let live = true; + + /** The next stretch of every card's motion, from now: it replaces the one running, which agrees with it where they meet. */ + const issue = () => { + if (!live) return; + normalize(clock()); // the angles of this stretch start within a turn of zero, so the transforms stay small however long the page has been open + plate?.refit(tickMs); // a new plate costs a paint: whatever it costs, the cards and the sky are keyed from the clock after it, so none of it is lag + const t0 = clock(); + issuedAt = t0; + const frozen = reducedMotion?.matches === true; + const play = moving(); + for (let i = 0; i < k; i += 1) { + const frames = stretch(t0, frozen, (t) => transform(poseAt(i, t))); + boxes[i].style.transform = frames[0].transform as string; + anims[i]?.cancel(); + anims[i] = boxes[i].animate?.(frames, { + duration: SEGMENT_S * 1000, + easing: 'linear', + fill: 'forwards', + }); + if (!play) anims[i]?.pause(); + } + plate?.key(t0, frozen, play); // the sky turns on the same keyframes, from the same poses + mount(sweep(t0)); // laid out from the same angles as the keyframes, in the same tick + }; + + /** The arc of azimuth any card shows at any instant of the stretch from `t0`: every pose it passes through, not its ends. */ + const sweep = (t0: number): Arc => sweepArc(view, win, w, k, poseAt, t0, SEGMENT_S); + + const mounted = new Map(); + /** Put the made tiles the arc shows into their card's box at their azimuth, and take the others out. */ + const mount = (arc: Arc) => { + const refs = residentTiles(view, (arc.fromDeg + arc.toDeg) / 2, (arc.toDeg - arc.fromDeg) / 2); + const turnOf = new Map(refs.map((r) => [r.tile, r.turn])); + const keep = new Set(); + for (const lt of bd.litTiles()) { + const turn = turnOf.get(lt.tile); + const entry = bd.manifest.tiles[lt.tile][lt.card]; + if (turn === undefined || !entry) continue; + keep.add(lt.canvas); + if (mounted.get(lt.canvas) === turn && lt.canvas.parentElement === boxes[lt.card]) continue; + const b = tileBox(view, win.plane.scale, lt, turn, entry); + Object.assign(lt.canvas.style, { + position: 'absolute', + left: `${w / 2 + b.left}px`, + top: `${horizonY + b.top}px`, + width: `${b.w}px`, + height: `${b.h}px`, + }); + mounted.set(lt.canvas, turn); + boxes[lt.card].appendChild(lt.canvas); + } + for (const c of [...mounted.keys()]) { + if (keep.has(c)) continue; + c.remove(); + mounted.delete(c); + } + }; + + // The one timer: ask for the arc ahead, mount what is made, and issue the next stretch once this one is mostly spent. + const win0 = window; + let timer = 0; + let lastTick: number | undefined; + /** The real period of the tick, ms: what the last two began apart (a tick is a timeout chain, so its work and its lateness are in it), never less than RESIDENCY_MS. */ + let tickMs = RESIDENCY_MS; + const residency = () => { + timer = 0; + if (!live) return; + const t = clock(); + if (lastTick !== undefined) tickMs = Math.max(RESIDENCY_MS, t - lastTick); + lastTick = t; + const play = moving(); + if (play && t - issuedAt >= SEGMENT_S * 1000 * REISSUE_FRAC) issue(); + else if (play) plate?.tend(tickMs); + const arc = sweep(t); + mount(arc); + void bd.ensure(arc, sweepArc(view, win, w, k, poseAt, t, 0)).then(() => live && mount(arc)); // the view now first, then along the sweep + timer = win0.setTimeout(residency, RESIDENCY_MS); + }; + parent.appendChild(el); + issue(); + const sync = () => { + freeze(reducedMotion?.matches === true, clock()); + issue(); + }; + const offHeading = onHeading(issue); // every change of the pose's course: the viewer's choice, a hold, a bound, a place + timer = win0.setTimeout(residency, RESIDENCY_MS); + return { + el, + anims, + reissue: issue, + sync, + stop: () => { + live = false; + win0.clearTimeout(timer); + offHeading(); + }, + }; + }; + + /** Paint the lit tiles of every card into the host canvas, farthest first, each card at its pose about the rig's origin, at the pose the still froze at its first paint: the still scene's one image. */ + const paintCards = (bd: Backdrop) => { + const ctx = context2d(canvas); + if (!ctx) return; + const { view } = bd.manifest; + const { w, h, scale: dpr } = viewSize(); + const win = windowFor(view, w, h); + stillPose ??= headingPose(clock()); + const at = stillPose; + const planeTop = h - win.plane.bottom - win.plane.h; + const horizonY = planeTop + view.horizonRow * win.plane.scale; + const poses = bd.manifest.cards.map((_, i) => + cardPose(bd.manifest, i, at.h, at.phi, at.r, win) + ); + const arcs = poses.map((p) => cardArc(view, win, w, p)); + const from = Math.min(...arcs.map((a) => a.fromDeg)); + const to = Math.max(...arcs.map((a) => a.toDeg)); + const turnOf = new Map(residentTiles(view, (from + to) / 2, (to - from) / 2).map((r) => [r.tile, r.turn])); + const lit = bd.litTiles(); + for (let i = poses.length - 1; i >= 0; i -= 1) { + ctx.save(); + ctx.translate((w / 2 + poses[i].shiftPx) * dpr, horizonY * dpr); + ctx.scale(poses[i].scale, poses[i].scale); + for (const lt of lit.filter((x) => x.card === i)) { + const turn = turnOf.get(lt.tile); + const entry = bd.manifest.tiles[lt.tile][i]; + if (turn === undefined || !entry) continue; + const b = tileBox(view, win.plane.scale, lt, turn, entry); + ctx.drawImage(lt.canvas, b.left * dpr, b.top * dpr, b.w * dpr, b.h * dpr); + } + ctx.restore(); } - layers.forEach((l) => { - l.slots.forEach((c, i) => { - c.el.setAttribute('aria-hidden', 'true'); - c.el.style.left = `${(i * size.chunk) / scale}px`; - l.track.appendChild(c.el); + }; + + /** A still's one image in the host canvas: the sky facing the pose it froze at, its bodies, and the cards of that pose over them. */ + const paintStill = () => { + const { w, h, scale } = viewSize(); + const physical = sky.physical; + if (opts.backdrop) stillPose ??= headingPose(clock()); + const facing = stillPose?.h ?? physical?.view.lookAzDeg ?? 0; // with no ridge there is no heading: the place's rest azimuth + const camera = physical && plateCamera(windowFor(physical.view, w, h), facing, 0); + const painted = paintSky(canvas, sky, camera, w, h, makeCanvas); + const ctx = context2d(canvas); + if (ctx && physical && painted.px) + paintNightBodies(ctx, nightBodies(physical, painted.px, opts.lines === true), canvas.width, canvas.height, scale); + if (opts.backdrop) paintCards(opts.backdrop); + }; + + /** + * The sky of a live scene (`skyTurn.ts`): a plate painted about the heading the view has, under a stretch of the heading owner's keyframes. The real stars, + * the moon and (when asked) the constellation lines are baked into the plate's sky; the twinkling stars get their own canvas on it, which a per-frame pass + * clears and paints over. A sky-only scene has no rig to issue it: its plate faces the place's rest azimuth and stays. + */ + const startPlate = (physical: NonNullable, w: number, h: number, dpr: number): Plate | undefined => { + const win = windowFor(physical.view, w, h); + const pxPerDeg = w / win.camera.hfovDeg; + /** Slots of the twinkle schedule, fixed by the first plate: the schedule runs over the catalogue, so every plate of this sky twinkles the same stars in the same phase. */ + let slots = 0; + const paint = (centre: number, slack: number) => { + const { cssW, ratio } = plateSize(win, w, h, dpr, slack); + const el = document.createElement('div'); + el.setAttribute('aria-hidden', 'true'); + Object.assign(el.style, { + position: 'absolute', + left: `${(w - cssW) / 2}px`, + top: '0', + width: `${cssW}px`, + height: `${h}px`, + willChange: 'transform', + pointerEvents: 'none', }); - rig.appendChild(l.track); - bake(l, l.slots[1], false); - bake(l, l.slots[2], false); - }); - // DOM order is paint order: farthest first, so the nearest ridge ends up on top. - parent.appendChild(rig); - layers.forEach((l) => startDrift(l, rotate)); - built.sway = startSway(rig, w, h); + const layer = (): HTMLCanvasElement => { + const c = document.createElement('canvas'); + c.width = Math.floor(cssW * ratio); + c.height = Math.floor(h * ratio); + c.setAttribute('aria-hidden', 'true'); + Object.assign(c.style, { position: 'absolute', left: '0', top: '0', width: '100%', height: '100%', pointerEvents: 'none' }); + el.appendChild(c); + return c; + }; + const skyEl = layer(); + const painted = paintSky(skyEl, sky, plateCamera(win, centre, slack), cssW, h, makeCanvas); + const skyCtx = context2d(skyEl); + if (!painted.ok || !painted.px || !skyCtx) return undefined; + const bodies: NightBodies = nightBodies(physical, painted.px, opts.lines === true); + paintNightBodies(skyCtx, bodies, skyEl.width, skyEl.height, ratio); + slots ||= slotsFor(STAR_COUNT, bodies.stars.length); + return { + el, + twinkle: bodies.stars.length ? layer() : undefined, + stars: new Map(bodies.stars.map((star) => [star.id, star])), + ratio, + slack, + }; + }; + /** The overlay of `of` at `t` seconds: the stars of the catalogue that twinkle then, those of them this plate has. */ + paintTwinkleOf = (of, t) => { + const el = of.twinkle; + const ctx = el && context2d(el); + if (!el || !ctx) return; + const active = t === undefined ? [] : activeAt(STAR_COUNT, t, slots); + paintTwinkle(ctx, of.stars, active, el.width, el.height, of.ratio); + }; + const facing = opts.backdrop ? headingPose(clock()).h : physical.view.lookAzDeg; // with no ridge there is no heading: the place's rest azimuth + const first = paint(facing, slackFor(turnRate(), RESIDENCY_MS)); + if (!first) return undefined; + parent.appendChild(first.el); + /** The slide from `t0` of a plate centred on `centre`: its pan at every instant of the stretch is the heading owner's `h` there against that centre. */ + const key = (el: HTMLElement, centre: number, t0: number, frozen: boolean, play: boolean): Animation | undefined => { + const frames = stretch(t0, frozen, (t) => `translate3d(${panPx(headingPose(t).h, centre, pxPerDeg)}px,0,0)`); + el.style.transform = frames[0].transform as string; + const anim = el.animate?.(frames, { duration: SEGMENT_S * 1000, easing: 'linear', fill: 'forwards' }); + if (!play) anim?.pause(); + return anim; + }; + const plate: Plate = { + ...first, + centre: facing, + refit: (periodMs) => { + const at = headingPose(clock()).h; + plate.centre = alignTurns(plate.centre, at); + const rate = turnRate(); + const slack = slackFor(rate, RESIDENCY_MS); + if (slack <= plate.slack && !recentre(at, plate.centre, plate.slack, rate, periodMs)) return false; + // A plate about the heading, in the place of this one: the same sky at the same place on the screen, so nothing moves. Undefined (this one stays) if it cannot be painted. + const next = paint(at, slack); + if (!next) return false; + if (moving()) paintTwinkleOf(next, clock() / 1000); // its twinkles as the old one's are now: shown with the stars already swinging + parent.insertBefore(next.el, plate.el); + plate.anim?.cancel(); + plate.el.remove(); + Object.assign(plate, next, { centre: at, anim: undefined }); + return true; + }, + key: (t0, frozen, play) => { + plate.anim?.cancel(); + plate.anim = key(plate.el, plate.centre, t0, frozen, play); + }, + tend: (periodMs) => { + if (plate.refit(periodMs)) plate.key(clock(), false, true); // ticks run only while moving + }, + stop: () => { + plate.anim?.cancel(); + plate.el.remove(); + }, + }; + return plate; + }; + + /** Paint the cards' rig, the sky and the rain. Returns false when a 2D context is missing or there is no area yet. */ + const build = (): boolean => { + teardown(); + // A zero-size canvas throws on drawImage; wait for the first resize that gives the host an area. + if (hasNoArea()) return false; + const { w, h, scale } = viewSize(); + canvas.width = Math.round(w * scale); + canvas.height = Math.round(h * scale); + if (!context2d(canvas)) return false; + built = {}; + if (!still) { + // The host canvas keeps a still's sky (`paintStill`); a live scene's physical sky is a plate over it, and one with none is a gradient in the host canvas. + if (sky.physical) { + built.plate = startPlate(sky.physical, w, h, scale); + if (!built.plate) return false; + } else if (!paintSky(canvas, sky, undefined, w, h, makeCanvas).ok) return false; + } + if (opts.backdrop) { + // The offsets this place and viewport allow, to the one owner of the pose: a rebuild at another size is a new bound, and the view eases from the pose it has. + const { manifest } = opts.backdrop; + const win = windowFor(manifest.view, w, h); + setRange((mode, phi) => offsetRange(manifest, win, mode, phi), clock()); + if (!still) built.rig = startRig(opts.backdrop, w, h, built.plate); + } if (tier !== 'still' && sky.physical && sky.physical.weather.rain > 0) built.rain = startRain(sky.physical.weather.rain, sky.horizon, w, h, scale); - pump(); syncPlayState(); return true; }; @@ -636,20 +637,16 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { !(reducedMotion?.matches ?? false) && document.visibilityState === 'visible'; - /** Paint the overlay at t seconds (stars away from base), or just clear it with no t (all at base). */ + /** Paint the overlay of the plate that is up at t seconds (stars away from base), or just clear it with no t (all at base). */ const drawTwinkle = (t?: number) => { - const el = built?.twinkle; - const ctx = el && context2d(el); - if (!el || !ctx) return; - const active = t === undefined ? [] : activeAt(field.length, t); - paintTwinkle(ctx, field, active, el.width, el.height, viewSize().scale); + if (built?.plate) paintTwinkleOf(built.plate, t); }; // The same guard as the drift: not still, not disposed, not reduced motion, tab visible. Not moving // stops the loop and leaves the stars steady at base brightness. const twTick = (now: number) => { twRaf = 0; - if (!moving() || !built?.twinkle) return; + if (!moving() || !built?.plate?.twinkle) return; if (now - twLast >= TWINKLE_FRAME_MS) { twLast = now; drawTwinkle(now / 1000); @@ -658,11 +655,10 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { }; function syncPlayState() { - const anims = built - ? [built.sway, ...built.layers.map((l) => l.anim), ...(built.rain?.anims ?? [])] - : []; + if (moving()) built?.rig?.reissue(); + const anims = [...(built?.rig?.anims ?? []), ...(built?.rain?.anims ?? []), built?.plate?.anim]; anims.forEach((a) => (moving() ? a?.play() : a?.pause())); - if (!built?.twinkle) return; + if (!built?.plate?.twinkle) return; if (moving()) { if (!twRaf) twRaf = requestAnimationFrame(twTick); } else { @@ -672,26 +668,15 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { } } - /** Flatten the sky and layers into the host canvas and drop the layers: a still image, no compositor layers left. */ + /** Drop the twinkle and the rain, leaving the painted sky as a still image. */ const settleToStill = () => { if (still && !built) return; + if (!still) stillPose = undefined; // a live scene that flattens freezes the pose it has now still = true; - const ctx = context2d(canvas); - if (ctx && built) { - const { size } = built; - built.layers.forEach((l) => { - // Freeze where the drift is, so the swap to a still does not jump; whatever is baked and in view. - const dur = chunkSeconds(l.spec, size) * 1000; - const p = Math.min(1, Math.max(0, Number(l.anim?.currentTime ?? 0) / dur)); - const x = -Math.round(p * size.chunk); - l.slots.slice(0, 2).forEach((c, i) => { - if (c.ready) ctx.drawImage(c.el, x + i * size.chunk, canvas.height - size.height); - }); - }); - } - teardownLayers(); + teardown(); cancelAnimationFrame(raf); raf = 0; + paintStill(); report(true); }; @@ -754,11 +739,23 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { sampler.reset(); wake(); }; - const onResize = () => { + /** Make the scene again at the size it has now and settle as it was: after a resize, and after tiles arrive into a still. A burst of either is one rebuild, 250 ms after the last. */ + let freshPose = false; + const rebuild = (fresh: boolean) => { + freshPose ||= fresh; clearTimeout(resizeTimer); resizeTimer = window.setTimeout(() => { if (disposed) return; const wasStill = still; + if (freshPose) { + // A resize is a new view: a still takes the pose the heading has now and asks for the tiles of it; the arrivals then repaint that pose. + stillPose = undefined; + if (wasStill && opts.backdrop) { + const { h } = headingPose(clock()); + opts.backdrop.ensure({ fromDeg: h - HFOV_MAX_DEG / 2, toDeg: h + HFOV_MAX_DEG / 2 }).catch(() => undefined); + } + } + freshPose = false; if (!build()) return; if (wasStill) settleToStill(); else { @@ -767,23 +764,35 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { } }, 250); }; + // A still draws once and has no timer to ask for tiles, so it is told of each one that is made after its paint (the deadline of a scene start leaves the rest of the + // first arc loading); the live tier mounts them on its own timer. Nothing asks for more: a repaint adds no request, so the fill-in ends with the last tile. + const offTile = opts.backdrop?.onTile(() => { + if (still && !disposed) rebuild(false); + }); document.addEventListener('visibilitychange', onVisibility); + const onResize = () => rebuild(true); window.addEventListener('resize', onResize); - reducedMotion?.addEventListener?.('change', syncPlayState); + const onMotionChange = () => { + built?.rig?.sync(); + syncPlayState(); + }; + reducedMotion?.addEventListener?.('change', onMotionChange); return { login() { - // No camera to pull back; the ridges are the same before and after. + // No camera to pull back; the sky is the same before and after. }, dispose() { if (disposed) return; disposed = true; cancelAnimationFrame(raf); + offTile?.(); + opts.backdrop?.dispose(); clearTimeout(resizeTimer); document.removeEventListener('visibilitychange', onVisibility); window.removeEventListener('resize', onResize); - reducedMotion?.removeEventListener?.('change', syncPlayState); - teardownLayers(); + reducedMotion?.removeEventListener?.('change', onMotionChange); + teardown(); readout?.remove(); }, }; diff --git a/src/app/features/scene/ridge/credits.test.ts b/src/app/features/scene/ridge/credits.test.ts index 887cc2d4..4ab1e58e 100644 --- a/src/app/features/scene/ridge/credits.test.ts +++ b/src/app/features/scene/ridge/credits.test.ts @@ -1,16 +1,46 @@ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; import { describe, expect, it } from 'vitest'; -import { HORIZON_CREDIT, WEATHER_CREDIT, WEATHER_CREDIT_URL, WEATHER_DATASET } from './credits'; -import { HORIZON_ATTRIBUTION } from './horizon'; -import { WEATHER_ATTRIBUTION } from './weatherFeed'; +import { + LINES_CREDIT, + LINES_SOURCE_URL, + STARS_CREDIT, + STARS_SOURCE_URL, + terrainCredit, +} from './credits'; +import { parseIndex, parseManifest } from './manifest'; +import { wireManifest } from './manifest.fixture'; -describe('the credits the Sky menu shows', () => { - it("are the sources' own", () => { - expect(HORIZON_CREDIT).toBe(HORIZON_ATTRIBUTION); - expect(WEATHER_CREDIT).toBe(WEATHER_ATTRIBUTION); +describe('the terrain credit', () => { + const shipped = (): { attribution: { credit_line: string; licence: string } } | undefined => { + const root = join(process.cwd(), 'public', 'ridge'); + const index = parseIndex(JSON.parse(readFileSync(join(root, 'index.json'), 'utf8'))); + return JSON.parse( + readFileSync(join(root, index.places[index.default], 'manifest.json'), 'utf8') + ); + }; + + it("is the shipped manifest's attribution, credit line then licence", () => { + const wire = shipped(); + const manifest = parseManifest(wireManifest({ attribution: wire?.attribution }), '/d/'); + expect(terrainCredit(manifest)).toBe( + `${wire?.attribution.credit_line} ${wire?.attribution.licence}` + ); + expect(terrainCredit(manifest)).toMatch(/Copernicus/); }); - it('credit GeoSphere with its requested line, and state a licence only with the dataset named', () => { - expect(WEATHER_CREDIT).toBe(`Datenquelle: GeoSphere Austria - ${WEATHER_CREDIT_URL}`); - expect(WEATHER_CREDIT).not.toMatch(/CC BY/); - expect(WEATHER_DATASET).toMatch(/TAWES.*10-minute.*CC BY 4\.0/); + + it('is absent without a manifest', () => { + expect(terrainCredit(undefined)).toBeUndefined(); + }); +}); + +describe('the night sky credits', () => { + const data = readFileSync(join(__dirname, 'nightSkyData.ts'), 'utf8'); + it("name the sources the generated data's header names, with their licences", () => { + expect(data).toContain(STARS_SOURCE_URL); + expect(data).toContain(LINES_SOURCE_URL); + expect(data).toMatch(/BSD-3-Clause/); + expect(STARS_CREDIT).toMatch(/Yale Bright Star Catalogue.*public domain/); + expect(LINES_CREDIT).toMatch(/Olaf Frohn.*BSD-3-Clause/); }); }); diff --git a/src/app/features/scene/ridge/credits.ts b/src/app/features/scene/ridge/credits.ts index 1a0327ea..2252381f 100644 --- a/src/app/features/scene/ridge/credits.ts +++ b/src/app/features/scene/ridge/credits.ts @@ -1,11 +1,20 @@ -// What the Ridge background owes its data sources, shown in the Sky menu (SkyStateControl). Plain strings in their own module so the -// main chunk carries these and not the baked horizon table or the weather parser; credits.test.ts holds them equal to the sources'. +// What the Ridge background owes its data sources, shown in the scene view (the Place submenu, all of them: ruling ridge-view-credits-home). The terrain, stars and lines +// credits are plain strings in their own module; credits.test.ts holds them equal to the sources'. The weather's credit is owed place by place and is the feed row's (`weatherFeed.ts`). The terrain credit is the loaded +// manifest's own `attribution` (terrainCredit): the baker writes it, so no constant here can drift from the bake. +import type { RidgeManifest } from './manifest'; -/** GeoSphere's own requested credit line. It names no licence: that is the dataset's (below). */ -export const WEATHER_CREDIT = 'Datenquelle: GeoSphere Austria - https://data.hub.geosphere.at'; -export const WEATHER_CREDIT_URL = 'https://data.hub.geosphere.at'; -/** The dataset the weather is read from, and its licence as the dataset page names it (data.hub.geosphere.at, tawes-v1-10min). */ -export const WEATHER_DATASET = 'TAWES weather stations, 10-minute data (station 11035), CC BY 4.0'; -/** The terrain silhouette's credit, as the Copernicus DEM licence asks (equal to `HORIZON_ATTRIBUTION`). */ -export const HORIZON_CREDIT = - '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.'; +/** The terrain's credit line and licence as the loaded bake states them; undefined until a manifest has loaded (no manifest, no line). */ +export const terrainCredit = ( + manifest: Pick | undefined +): string | undefined => + manifest ? `${manifest.attribution.creditLine} ${manifest.attribution.licence}` : undefined; + +/** The stars: the Yale Bright Star Catalogue, public domain (CDS/VizieR V/50; the file is the SAO Telescope Data Center's copy, see `nightSkyData.ts`). */ +export const STARS_CREDIT = + 'Stars: Yale Bright Star Catalogue, 5th revised ed. (Hoffleit and Warren 1991), public domain, CDS VizieR V/50'; +export const STARS_SOURCE_URL = 'http://tdc-www.harvard.edu/catalogs/bsc5.dat.gz'; +/** The constellation lines: d3-celestial by Olaf Frohn, BSD-3-Clause (the repository's LICENSE, 2015). The licence asks for its notice to travel with redistributions: the full text is in `THIRD_PARTY_NOTICES.md` at the repository root. */ +export const LINES_CREDIT = + 'Constellation lines: d3-celestial by Olaf Frohn (BSD-3-Clause, copyright 2015 Olaf Frohn), https://github.com/ofrohn/d3-celestial'; +export const LINES_SOURCE_URL = + 'https://github.com/ofrohn/d3-celestial/blob/master/data/constellations.lines.json'; diff --git a/src/app/features/scene/ridge/earthAtmosphere.ts b/src/app/features/scene/ridge/earthAtmosphere.ts index cadddbc5..b3fe9d10 100644 --- a/src/app/features/scene/ridge/earthAtmosphere.ts +++ b/src/app/features/scene/ridge/earthAtmosphere.ts @@ -97,6 +97,11 @@ function sampleMedium(altKm: number, mieScale: number): Medium { }; } +/** The air's extinction per km (per channel) at a height above sea level: a horizontal path of d km keeps exp(-extinction x d) of the light. */ +export function extinctionAt(altKm: number, mieScale: number): Vec3 { + return sampleMedium(altKm, mieScale).extinction; +} + /** Nearest positive hit of a unit-direction ray with a sphere at the origin: its distance, or -1. */ function raySphere( ox: number, diff --git a/src/app/features/scene/ridge/heading.test.ts b/src/app/features/scene/ridge/heading.test.ts new file mode 100644 index 00000000..4019bc70 --- /dev/null +++ b/src/app/features/scene/ridge/heading.test.ts @@ -0,0 +1,450 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { anchor, freeze, hold, normalize, poseAt, resetHeading, setRange, settledAt, STAGE_MS, subscribe, turnRate } from './heading'; +import type { RotationMode } from './heading'; +import * as camera from '../cameraState'; +import { effectiveMode, getCamera, isHeld, resetCamera, setCamera, subscribe as onCamera } from '../cameraState'; +import { maxSpeed } from './view'; +import { norm } from './ring'; +import { parseManifest } from './manifest'; +import { wireManifest } from './manifest.fixture'; + +const S = 1000; + +/** The viewer's choice, at the clock `at` (ms): the one way the mode and the speed reach the view. */ +const choose = (mode: RotationMode, speedDegPerS: number, at: number) => setCamera({ mode, speedDegPerS }, at); + +/** The bound of a baked place, as `view.ts` `offsetRange` draws it: 100 m round the circle, 200 m forward with the camera exactly on its heading and the view turning with it. */ +const BACK = 100; +const FORWARD = 200; +const range = (mode: RotationMode, phi: number): [number, number] => [-BACK, mode !== 'offset' && Math.abs(norm(phi + 180) - 180) < 1e-6 ? FORWARD : BACK]; +/** Whether a pose is one the bound allows, whatever mode led there. */ +const fits = (p: { phi: number; r: number }): boolean => p.r >= range('both', p.phi)[0] - 1e-9 && p.r <= range('both', p.phi)[1] + 1e-9; + +const store = new Map(); + +beforeEach(() => { + store.clear(); + vi.stubGlobal('localStorage', { + getItem: (k: string) => store.get(k) ?? null, + setItem: (k: string, v: string) => void store.set(k, v), + }); + resetCamera(); + resetHeading(); + setCamera({ mode: 'still', speedDegPerS: 0, offsetM: 0 }, 0); +}); + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('turnRate', () => { + it('is the speed the view direction turns at: the viewer sets, bounded by the place, and nothing while it does not turn', () => { + anchor('p', 0, 0, (mode) => (mode === 'both' ? 5 : 12)); + expect(turnRate()).toBe(0); // still + choose('both', 3, 0); + expect(turnRate()).toBe(3); + choose('both', -12, 0); + expect(turnRate()).toBe(5); // the place sustains 5, not the ceiling + choose('offset', 12, 0); + expect(turnRate()).toBe(0); // the camera circles: the view direction stays + choose('both', 3, 0); + freeze(true, 0); + expect(turnRate()).toBe(0); + freeze(false, 0); + hold(40, 0); + expect(turnRate()).toBe(0); // held by hand + }); +}); + +describe('the heading owner', () => { + it('faces nothing in particular until a place anchors it, and turns nothing while the viewer chose nothing to turn', () => { + expect(poseAt(5 * S)).toEqual({ h: 0, phi: 0, r: 0 }); + }); + + it('anchors a place at its rest azimuth once, and a later anchor of the same place changes nothing', () => { + anchor('vienna', 214, 0); + expect(poseAt(0).h).toBe(214); + choose('both', 0.6, 0); + expect(poseAt(10 * S).h).toBeCloseTo(220, 9); + anchor('vienna', 214, 10 * S); // a rebuild for a new sky: the view keeps the direction it has turned to + expect(poseAt(10 * S).h).toBeCloseTo(220, 9); + anchor('fuji', 100, 10 * S); // another place faces its own rest azimuth, with the camera on its heading + expect(poseAt(10 * S)).toMatchObject({ h: 100, phi: 0 }); + }); + + it('is unwrapped over several revolutions between normalizations: nothing wraps or clamps it', () => { + anchor('p', 0, 0); + choose('both', 6, 0); + expect(poseAt(60 * S).h).toBeCloseTo(360, 9); + expect(poseAt(210 * S).h).toBeCloseTo(1260, 9); + choose('both', -6, 210 * S); + expect(poseAt(330 * S).h).toBeCloseTo(540, 9); + expect(poseAt(500 * S).h).toBeLessThan(0); + }); + + it('turns the view direction in both mode, the camera on its circle alone in offset mode, and nothing when still', () => { + anchor('p', 100, 0); + choose('both', 2, 0); + expect(poseAt(10 * S)).toMatchObject({ h: 120, phi: 0 }); + choose('offset', 2, 10 * S); // nothing jumps at the change + expect(poseAt(10 * S)).toMatchObject({ h: 120, phi: 0 }); + expect(poseAt(20 * S)).toMatchObject({ h: 120, phi: 20 }); + choose('still', 2, 20 * S); + expect(poseAt(99 * S)).toMatchObject({ h: 120, phi: 20 }); + choose('offset', 2, 99 * S); // the camera keeps the angle it stopped at, and goes on from there + expect(poseAt(104 * S)).toMatchObject({ h: 120, phi: 30 }); + }); + + it('puts the camera back on its heading when the view direction is made to turn with it, by the short way round, and the view direction turns meanwhile', () => { + anchor('p', 100, 0); + choose('offset', 12, 0); + expect(poseAt(7.5 * S).phi).toBeCloseTo(90, 9); + choose('both', 12, 7.5 * S); + expect(poseAt(7.5 * S)).toMatchObject({ h: 100 }); // the pick moves nothing in the frame it is made + const gone = [0, 0.25, 0.5, 0.75, 1].map((x) => poseAt(7.5 * S + x * STAGE_MS).phi); + gone.slice(1).forEach((v, i) => expect(v).toBeLessThan(gone[i])); + expect(gone[4]).toBe(0); + expect(poseAt(7.5 * S + 5 * S).phi).toBe(0); + expect(poseAt(7.5 * S + 5 * S).h).toBeCloseTo(100 + 12 * 5, 9); + // 270 degrees on is 90 short of home the other way: the camera goes forward to 360, not back through 270. + choose('offset', 12, 20 * S); + choose('offset', 12, 20 * S + 22.5 * S); + const t = 20 * S + 22.5 * S; + expect(norm(poseAt(t).phi)).toBeCloseTo(270, 9); + choose('both', 12, t); + const mid = poseAt(t + STAGE_MS / 2).phi; + expect(norm(mid)).toBeGreaterThan(270); + expect(norm(poseAt(t + STAGE_MS).phi)).toBeCloseTo(0, 9); + }); + + it('a speed change takes effect from now, without moving the view', () => { + anchor('p', 0, 0); + choose('both', 1, 0); + choose('both', 3, 10 * S); + expect(poseAt(10 * S).h).toBe(10); + expect(poseAt(20 * S).h).toBe(40); + }); + + it('a manual turn sets the view direction in every mode and stops the rotation: the hold is the one fact, the chosen mode is left alone', () => { + for (const mode of ['still', 'offset', 'both'] as const) { + resetHeading(); + anchor('p', 0, 0); + choose(mode, 1, 0); + hold(300, 10 * S); + expect(poseAt(10 * S).h).toBe(300); + expect(getCamera().mode).toBe(mode); + expect(effectiveMode()).toBe('still'); + expect(poseAt(500 * S).h).toBe(300); + expect(poseAt(500 * S).phi).toBe(poseAt(10 * S).phi); + choose('both', 1, 500 * S); // a rotation mode chosen again resumes it + expect(poseAt(510 * S).h).toBe(310); + } + }); + + it('a hold outlives a rebuild and not a reload: a reload is a Return, and rotation resumes in the chosen mode', () => { + anchor('p', 0, 0); + choose('both', 1, 0); + hold(100, 10 * S); + anchor('p', 0, 20 * S); // what every scene build does + expect(poseAt(60 * S).h).toBe(100); + expect(isHeld()).toBe(true); + const stored = getCamera(); + expect(stored.mode).toBe('both'); // what is stored is what the viewer chose + resetCamera(); // a reload reads the stored choice + expect(getCamera()).toEqual(stored); + expect(isHeld()).toBe(false); + expect(effectiveMode()).toBe('both'); + resetHeading(); + anchor('p', 0, 100 * S); // the new page faces its rest azimuth and turns + expect(poseAt(110 * S).h).toBe(10); + }); + + it('bounds the speed for the mode and the place and never rewrites the stored one: switching to a mode with room restores it', () => { + const ring = parseManifest(wireManifest({}, 3, 32), '/d/'); + const slow = maxSpeed(ring, 'both'); + anchor('p', 0, 0, (m) => maxSpeed(ring, m)); + choose('both', 50, 0); + expect(poseAt(10 * S).h).toBeCloseTo(10 * slow, 9); + expect(getCamera().speedDegPerS).toBe(50); // the viewer's value + choose('offset', 50, 10 * S); + expect(poseAt(11 * S).phi).toBeCloseTo(12, 9); // the ceiling of that mode, not the turning mode's bound + choose('both', 50, 11 * S); + expect(poseAt(21 * S).h - poseAt(11 * S).h).toBeCloseTo(10 * slow, 9); + expect(getCamera().speedDegPerS).toBe(50); + setCamera({ speedDegPerS: -50 }, 21 * S); + expect(poseAt(31 * S).h - poseAt(21 * S).h).toBeCloseTo(-10 * slow, 9); + }); + + it('bounds the speed from the anchor, before anything has been told the place is loaded: a stored speed above the bound does not run over the load', () => { + const ring = parseManifest(wireManifest({}, 3, 32), '/d/'); + const slow = maxSpeed(ring, 'both'); + setCamera({ mode: 'both', speedDegPerS: 12 }, 0); + anchor('p', 214, 0, (m) => maxSpeed(ring, m)); // what a scene start does, then awaits the first tiles + expect(poseAt(5 * S).h).toBeCloseTo(214 + 5 * slow, 9); + expect(slow).toBeLessThan(12); + anchor('p', 214, 5 * S, (m) => maxSpeed(ring, m)); // a rebuild keeps the heading and the bound + expect(poseAt(10 * S).h).toBeCloseTo(214 + 10 * slow, 9); + }); + + it('choosing the mode the viewer had before a hold resumes the view: the mode they had is not still any more, so the choice is a change', () => { + anchor('p', 0, 0); + choose('both', 1, 0); + hold(100, 10 * S); + setCamera({ mode: 'both' }, 20 * S); + expect(poseAt(30 * S).h).toBe(110); + expect(getCamera().mode).toBe('both'); + }); + + it('keeps the pose when the scene is rebuilt: the module outlives it', () => { + anchor('p', 50, 0); + choose('both', 1, 0); + expect(poseAt(30 * S).h).toBe(80); + anchor('p', 50, 30 * S); + expect(poseAt(30 * S).h).toBe(80); + }); + + it('freezes under reduced motion without moving the view, and goes on from where it stopped', () => { + anchor('p', 0, 0); + choose('both', 1, 0); + freeze(true, 10 * S); + expect(poseAt(10 * S).h).toBe(10); + expect(poseAt(50 * S).h).toBe(10); + expect(getCamera().mode).toBe('both'); // the viewer's choice is untouched + freeze(false, 50 * S); + expect(poseAt(60 * S).h).toBe(20); + }); + + it('normalizes into [0, 360) without changing the view, so the angles never grow with uptime, and an ease under way goes on as it was', () => { + anchor('p', 0, 0); + choose('both', 6, 0); + const day = 24 * 3600 * S; + normalize(day); + const h = poseAt(day).h; + expect(h).toBeGreaterThanOrEqual(0); + expect(h).toBeLessThan(360); + expect(h).toBeCloseTo((6 * 86400) % 360, 6); + expect(poseAt(day + 30 * S).h).toBeCloseTo(h + 180, 6); + choose('offset', 6, day + 30 * S); + normalize(day + 100 * S); + expect(poseAt(day + 100 * S).phi).toBeGreaterThanOrEqual(0); + expect(poseAt(day + 100 * S).phi).toBeLessThan(360); + setCamera({ speedDegPerS: -6 }, day + 100 * S); + normalize(day + 101 * S); + expect(poseAt(day + 101 * S).phi).toBeGreaterThanOrEqual(0); // a turn the other way is brought into range too + // An ease is the same ease before and after it is renormalized, in the middle. + choose('offset', 12, day + 200 * S); + choose('both', 12, day + 207.5 * S); + const at = day + 207.5 * S; + const before = [0.2, 0.5, 0.9].map((x) => poseAt(at + x * STAGE_MS)); + normalize(at + 0.3 * STAGE_MS); + const after = [0.2, 0.5, 0.9].map((x) => poseAt(at + x * STAGE_MS)); + after.forEach((p, i) => { + expect(norm(p.phi)).toBeCloseTo(norm(before[i].phi), 6); + expect(norm(p.h)).toBeCloseTo(norm(before[i].h), 6); + expect(p.r).toBeCloseTo(before[i].r, 9); + }); + }); + + it('tells subscribers of every change of its course: a choice, a hold, a bound, a manual turn while held, a new place; and of nothing that changes nothing', () => { + const cb = vi.fn(); + const off = subscribe(cb); + anchor('p', 0, 0); + expect(cb).toHaveBeenCalledTimes(1); + anchor('p', 0, 1); // the same place, no new bound: nothing + expect(cb).toHaveBeenCalledTimes(1); + setCamera({ mode: 'both', speedDegPerS: 1 }, 2); + expect(cb).toHaveBeenCalledTimes(2); + setCamera({ mode: 'both', speedDegPerS: 1 }, 3); // nothing changed + expect(cb).toHaveBeenCalledTimes(2); + hold(5, 4); // takes the hold: told once + expect(cb).toHaveBeenCalledTimes(3); + hold(6, 5); // turned again by hand while held: told + expect(cb).toHaveBeenCalledTimes(4); + setRange(range, 6); + expect(cb).toHaveBeenCalledTimes(5); + off(); + anchor('q', 0, 7); + expect(cb).toHaveBeenCalledTimes(5); + }); + + it('is the one owner of the order: the heading is current when a listener of the camera hears of a change, whenever the listener registered', () => { + setCamera({ mode: 'both', speedDegPerS: 1 }, 0); + const early: number[] = []; + const offEarly = onCamera((_n, _p, at) => early.push(poseAt(at).h)); // before the place is anchored: first of the listeners, as a control mounted before the scene start is + anchor('p', 214, 0); + const late: number[] = []; + const offLate = onCamera((_n, _p, at) => late.push(poseAt(at).h)); + anchor('p', 214, 1 * S); // a rebuild for a sky anchors the same place again + setCamera({ speedDegPerS: 4 }, 5 * S); + expect(poseAt(10 * S).h).toBeCloseTo(214 + 5 + 20, 9); + setCamera({ mode: 'still' }, 11 * S); + expect(early).toEqual(late); + expect(early[0]).toBeCloseTo(214 + 5, 9); // the heading at the change, with the speed it had until it + expect(early[1]).toBeCloseTo(214 + 5 + 24, 9); + offEarly(); + offLate(); + }); + + it('keeps no log of the camera: the owner takes each change as it is made, so a change nobody reads is held nowhere', () => { + expect(Object.keys(camera)).not.toContain('takeChanges'); + anchor('p', 100, 0); + choose('both', 2, 0); + choose('both', 4, 3 * S); // 6 degrees by then + choose('offset', 4, 5 * S); // 14 degrees: the view stops, the camera starts + choose('both', 1, 7 * S); // the camera went 8 degrees round, and is put back on its heading + expect(poseAt(9 * S).h).toBeCloseTo(100 + 14 + 2, 9); + }); + + describe('a change of mode eases the pose in two stages inside the bound, from wherever the pose is', () => { + const sample = (from: number, to: number, step = 1): { h: number; phi: number; r: number }[] => { + const out = []; + for (let t = from; t <= to; t += step) out.push(poseAt(t)); + return out; + }; + /** Every pose inside the bound, and whenever the camera angle moves the offset is inside the circle's bound at both ends of the move. */ + const insideTheBound = (poses: { phi: number; r: number }[]) => { + poses.forEach((p, i) => { + expect(fits(p), `pose ${i}: phi ${p.phi}, r ${p.r}`).toBe(true); + if (i && Math.abs(p.phi - poses[i - 1].phi) > 1e-9) { + expect(Math.abs(p.r)).toBeLessThanOrEqual(BACK + 0.02); // a sample step may straddle the end of a stage: a thousandth of the ease on + expect(Math.abs(poses[i - 1].r)).toBeLessThanOrEqual(BACK + 0.02); + } + }); + }; + + /** The clock at which the camera has gone a quarter round its circle at 12 degrees a second, started when its offset is in: the offset comes in first, and the angle is let go after. */ + const QUARTER = 90 / 12 * S + STAGE_MS; + + beforeEach(() => { + setCamera({ offsetM: 200 }, 0); + anchor('p', 100, 0); + setRange(range, 0); + }); + + it('goes to a mode that stands the camera on its heading in two stages: the angle first, the offset let out after, and the view direction never waits', () => { + choose('offset', 12, 0); + const at = QUARTER; + expect(poseAt(at)).toMatchObject({ phi: 90, r: BACK }); + choose('both', 12, at); + expect(poseAt(at)).toMatchObject({ h: 100, phi: 90, r: BACK }); // what is seen at the pick + expect(settledAt()).toBe(at + 2 * STAGE_MS); + const stage1 = sample(at, at + STAGE_MS); + expect(stage1.every((p) => p.r === BACK)).toBe(true); // the angle alone + expect(stage1.at(-1)!.phi).toBeCloseTo(0, 9); + const stage2 = sample(at + STAGE_MS, at + 2 * STAGE_MS); + expect(stage2.every((p) => p.phi === 0)).toBe(true); // the offset alone + expect(stage2.at(-1)!.r).toBe(FORWARD); + expect(poseAt(at + 10 * S)).toMatchObject({ phi: 0, r: FORWARD }); + expect(poseAt(at + 3 * S).h).toBeCloseTo(100 + 36, 9); // turning from the instant of the pick + insideTheBound(sample(at, at + 2 * STAGE_MS)); + }); + + it('goes to a mode that takes the camera off its heading the other way: the offset comes in first with the camera held where it stood, then the camera goes', () => { + choose('both', 12, 0); + const at = 10 * S; + expect(poseAt(at)).toMatchObject({ phi: 0, r: FORWARD }); + choose('offset', 12, at); + const stage1 = sample(at, at + STAGE_MS); + expect(stage1.every((p) => p.phi === 0)).toBe(true); + expect(stage1.at(-1)!.r).toBe(BACK); + expect(poseAt(at + STAGE_MS + 1 * S)).toMatchObject({ r: BACK }); + expect(poseAt(at + STAGE_MS + 1 * S).phi).toBeCloseTo(12, 9); // and goes round from the angle it stood at, at the speed + insideTheBound(sample(at, at + 3 * STAGE_MS)); + }); + + it('a pick that asks nothing of the offset does not wait for it: the angle goes at once', () => { + choose('both', 12, 0); + setCamera({ offsetM: 50 }, 1 * S); + choose('offset', 12, 2 * S); + expect(poseAt(2 * S + 1 * S).phi).toBeCloseTo(12, 9); + }); + + it('a pick made while an ease is under way starts from the pose the view has, and every pose on the way stays inside the bound', () => { + const picks: RotationMode[] = ['still', 'offset', 'both']; + let checked = 0; + for (const first of picks) { + for (const second of picks) { + for (const gap of [10, 100, 250, 310, 450, 590]) { + resetHeading(); + resetCamera(); + setCamera({ mode: 'offset', speedDegPerS: 12, offsetM: 200 }, 0); + anchor('p', 100, 0); + setRange(range, 0); + const at = QUARTER; + setCamera({ mode: first }, at); + const seen = poseAt(at + gap); + setCamera({ mode: second }, at + gap); + expect(poseAt(at + gap), `${first} then ${second} after ${gap} ms`).toEqual(seen); // nothing moves at the pick + insideTheBound(sample(at, at + 4 * STAGE_MS, 3)); + checked += 1; + } + } + } + expect(checked).toBe(54); + }); + + it('a pick to both made from the offset-only mode mid-way, then to offset-only again, never leaves the bound: the case a target-only order got wrong', () => { + choose('offset', 12, 0); + const at = QUARTER; + choose('both', 12, at); // the angle goes first, the offset held at the circle's bound + choose('offset', 12, at + 100); // and the offset-only mode has the offset on the circle's bound already + insideTheBound(sample(at, at + 4 * STAGE_MS, 2)); + // From both with the offset out, pick still then both then offset within a stage each. + resetHeading(); + resetCamera(); + setCamera({ mode: 'both', speedDegPerS: 12, offsetM: 200 }, 0); + anchor('p', 100, 0); + setRange(range, 0); + choose('offset', 12, 5 * S); // the offset comes in first + choose('both', 12, 5 * S + 100); // back out: the camera is still on its heading, so the offset can go straight out + insideTheBound(sample(5 * S, 5 * S + 4 * STAGE_MS, 2)); + expect(poseAt(5 * S + 10 * S)).toMatchObject({ phi: 0, r: FORWARD }); + }); + + it('a slider eases in one stage, inside the bound the mode keeps, and an offset past it is held to it', () => { + choose('both', 0.6, 0); + setCamera({ offsetM: 20 }, 1 * S); + expect(poseAt(1 * S).r).toBe(FORWARD); + expect(poseAt(1 * S + STAGE_MS).r).toBe(20); + expect(settledAt()).toBe(1 * S + STAGE_MS); + setCamera({ offsetM: 999 }, 5 * S); + expect(poseAt(6 * S).r).toBe(FORWARD); + choose('offset', 0.6, 7 * S); + expect(poseAt(9 * S).r).toBe(BACK); // the viewer's 999 is not rewritten + expect(getCamera().offsetM).toBe(999); + choose('both', 0.6, 10 * S); + expect(poseAt(12 * S).r).toBe(FORWARD); + }); + + it('a new bound is a new segment from the pose the view has: a rebuild mid-ease lands exactly where the old scene was', () => { + choose('offset', 12, 0); + const at = QUARTER; + choose('both', 12, at); + for (const gap of [50, 150, 299, 301, 450]) { + const seen = poseAt(at + gap); + setRange(range, at + gap); // what a rebuild at another size, or a rebuilt scene, does + const now = poseAt(at + gap); + expect(now.h).toBeCloseTo(seen.h, 9); + expect(now.phi).toBeCloseTo(seen.phi, 9); + expect(now.r).toBeCloseTo(seen.r, 9); + } + insideTheBound(sample(at, at + 4 * STAGE_MS, 2)); + expect(poseAt(at + 5 * S)).toMatchObject({ phi: 0, r: FORWARD }); + }); + + it('has no ease under reduced motion: the pose owed is the pose shown at once, and one begun before is cut short', () => { + choose('offset', 12, 0); + const at = QUARTER; + choose('both', 12, at); + expect(settledAt()).toBeGreaterThan(at); + freeze(true, at + 10); + expect(poseAt(at + 10)).toMatchObject({ phi: 0, r: FORWARD }); + expect(poseAt(at + 5 * S).h).toBe(poseAt(at + 10).h); // and nothing turns + setCamera({ mode: 'offset', speedDegPerS: 12 }, at + 20); + expect(poseAt(at + 21)).toMatchObject({ r: BACK }); // the clamp, at once + setCamera({ mode: 'both', speedDegPerS: 12 }, at + 30); + expect(poseAt(at + 31)).toMatchObject({ phi: 0, r: FORWARD }); + expect(settledAt()).toBeLessThanOrEqual(at + 30); + }); + }); +}); diff --git a/src/app/features/scene/ridge/heading.ts b/src/app/features/scene/ridge/heading.ts new file mode 100644 index 00000000..880caa59 --- /dev/null +++ b/src/app/features/scene/ridge/heading.ts @@ -0,0 +1,210 @@ +// The heading owner: the one place that knows where the view faces (`h`), where the camera stands on its circle against that (`phi`) and how far from the +// centre (`r`), at any clock. Module-level state, so a sky change that makes a new scene keeps the pose. Angles are unwrapped compass degrees between two +// `normalize` calls (the rig makes one before each stretch of motion); `ring.ts` is the one place that reasons about 0 / 360. +// +// The state is one SEGMENT: the pose at its start `t0`, the mode and bounded speed in force, and the ease that takes the pose to the one the inputs owe. +// `poseAt(t)` is a pure function of the segment and `t`, ease included. Every change of an input (a mode pick, a hold, the speed, the offset, a bound, reduced +// motion, a place) starts a new segment from `poseAt(now)`: no log of changes, no second copy of the ease, so whoever reads at any clock, a rebuilt scene +// included, gets the pose the view has. +// +// The camera sits on its circle at angle `h + phi` and distance `r` (signed, forward positive): with `phi` 0 it is pushed forward along its own heading +// (`view.ts` `cardPose`), and rotating the offset alone moves `phi` and leaves the view direction where it is (ruling ridge-scene-view-submenus). `phi` is 0 +// whenever the view direction turns with the camera ('both'). The bound on `r` is the baker's (`view.ts` `offsetRange`, given by the scene as `setRange`): a +// forward offset past `rMaxM` fits only with the camera exactly on its heading. So an ease takes `phi` and `r` one after the other, STAGE_MS each, in the +// order that keeps every pose inside it from wherever it starts: a camera going to stand on its heading turns first and lets the offset out after; one going +// off it brings the offset in first and lets the camera go after. +import { bindOwner, getCamera, holdCamera, isHeld } from '../cameraState'; + +/** `still`: nothing turns. `offset`: the camera circles the centre, the view direction stays. `both`: the view direction turns and the camera with it. */ +export type RotationMode = 'still' | 'offset' | 'both'; + +/** Where the view faces, where the camera stands on its circle against that, and its offset (m, signed): the pose the rig lays the cards out from. */ +export interface Pose { + h: number; + phi: number; + r: number; +} + +/** What the baked place and the viewport allow: the speed (degrees per second, either way) a mode may turn at, and the offsets the camera may take at an angle in a mode. */ +type Speed = (mode: RotationMode) => number; +type Range = (mode: RotationMode, phiDeg: number) => [number, number]; + +export const STAGE_MS = 300; // one stage of an ease, ms +const EPS = 1e-9; // a pose this close to the one owed is there: nothing eases + +interface Segment extends Pose { + /** The clock (ms) at which `h`, `phi` and `r` hold. */ + t0: number; + /** Degrees per second of whatever turns, signed and bounded, and what that is: the view direction ('both'), the camera on its circle ('offset') or nothing. */ + rate: number; + turns: 'h' | 'phi' | undefined; + /** The camera's angle turns only from this clock (ms): after the offset has come in. */ + turnsFrom: number; + /** The angle an ease takes `phi` to from `t0` (unwrapped, the nearest way round); undefined: `phi` is what `turns` makes it. */ + phiTo: number | undefined; + /** The offset an ease takes `r` to, from `rAt`. */ + rTo: number; + rAt: number; + /** The clock (ms) at which everything eased is home. */ + endAt: number; +} + +let seg: Segment | undefined; +let frozen = false; +let anchored: string | undefined; +let speed: Speed | undefined; +let range: Range | undefined; +const listeners = new Set<() => void>(); + +/** 0 at `at`, 1 at `at + STAGE_MS` (smoothstep): the one curve of the view's easing. */ +const ease = (at: number, now: number): number => { + const x = Math.min(1, Math.max(0, (now - at) / STAGE_MS)); + return x * x * (3 - 2 * x); +}; +const free: [number, number] = [-Infinity, Infinity]; +/** What each mode turns: the view direction, the camera on its circle, or nothing. */ +const TURNS: Record = { both: 'h', offset: 'phi', still: undefined }; +const rangeOf = (mode: RotationMode, phi: number): [number, number] => range?.(mode, phi) ?? free; + +function pose(s: Segment, t: number): Pose { + const sec = (t - s.t0) / 1000; + return { + h: s.h + (s.turns === 'h' ? s.rate * sec : 0), + phi: + s.phiTo !== undefined + ? s.phi + (s.phiTo - s.phi) * ease(s.t0, t) + : s.phi + (s.turns === 'phi' ? (s.rate * Math.max(0, t - s.turnsFrom)) / 1000 : 0), + r: s.r + (s.rTo - s.r) * ease(s.rAt, t), + }; +} + +/** + * Start a segment at `now` from `from`, the pose the view has there, under the inputs in force: the viewer's choice, the hold, reduced motion and the bounds. + * What the inputs owe is where the camera must stand (on its heading when the view turns with it and is not held) and the offset the bound allows there; an + * ease is what takes `from` to it, none when `snap` (a place or a bound met for the first time) or while frozen. + */ +function begin(now: number, from: Pose, snap = false): void { + const cam = getCamera(); + const held = isHeld(); + const kin: RotationMode = frozen || held ? 'still' : cam.mode; + const toHeading = cam.mode === 'both' && !held; + const limit = speed?.(cam.mode) ?? Infinity; + const phiTo = toHeading ? 360 * Math.round(from.phi / 360) : undefined; + const landed = phiTo ?? from.phi; + const [lo, hi] = rangeOf(cam.mode, landed); // the bound is the chosen mode's, held or frozen or not: a hold does not move the offset + const rTo = Math.min(hi, Math.max(lo, cam.offsetM)); + const easing = !snap && !frozen; + const turnsPhi = easing && phiTo !== undefined && Math.abs(phiTo - from.phi) > EPS; + const movesR = easing && Math.abs(rTo - from.r) > EPS; + // Going to circle with the offset out past the circle's bound: the camera stays on its heading until the offset is in. + const [circleLo, circleHi] = rangeOf('offset', from.phi); + const holdsPhi = movesR && kin === 'offset' && (from.r < circleLo || from.r > circleHi); + const rAt = turnsPhi ? now + STAGE_MS : now; + seg = { + t0: now, + h: from.h, + phi: turnsPhi ? from.phi : landed, + r: movesR ? from.r : rTo, + rate: Math.sign(cam.speedDegPerS) * Math.min(Math.abs(cam.speedDegPerS), limit), + turns: TURNS[kin], + turnsFrom: holdsPhi ? now + STAGE_MS : now, + phiTo: turnsPhi ? phiTo : undefined, + rTo, + rAt, + endAt: Math.max(turnsPhi ? now + STAGE_MS : now, movesR ? rAt + STAGE_MS : now), + }; +} + +const current = (now: number): Segment => { + if (!seg) begin(now, { h: 0, phi: 0, r: 0 }, true); + return seg as Segment; +}; +/** The pose at `now` (ms): unwrapped degrees, bounded by the last `normalize` and the stretch since. */ +export function poseAt(now: number): Pose { + return pose(current(now), now); +} +const emit = () => [...listeners].forEach((cb) => cb()); +/** A new segment at `now` from the pose the view has, told to the subscribers. */ +function restart(now: number, over: Partial = {}, snap = false): void { + begin(now, { ...poseAt(now), ...over }, snap); + emit(); +} + +/** + * Degrees per second the view direction turns at under the inputs in force: the viewer's speed bounded by what the place sustains in the mode picked (`anchor`'s + * limit), and nothing while the view does not turn (a mode that turns the camera on its circle, a hold, reduced motion). Every change of any of these starts a + * segment and is heard by `subscribe`, so a reader that sizes something to this speed learns when it must size again. + */ +export const turnRate = (): number => (seg?.turns === 'h' ? Math.abs(seg.rate) : 0); + +/** The clock (ms) at which what the last change eased is home. */ +export const settledAt = (): number => seg?.endAt ?? 0; + +// The viewer's choice or hold changed: a new segment at that clock, before any listener hears of it. +bindOwner((at) => restart(Math.max(at, seg?.t0 ?? at))); + +/** + * Bound the speed in each mode to what the baked place sustains (`view.ts` `maxSpeed`), from this moment, before anything awaits the place's tiles, and point + * the view at a place: a place not shown before faces its rest azimuth, the camera on its heading, with no ease; the same place again keeps the pose. + */ +export function anchor(key: string, restDeg: number, now: number, limit?: Speed): void { + if (limit) speed = limit; + if (anchored === key) { + if (limit) restart(now); + return; + } + anchored = key; + range = undefined; // the bound belongs to the place before + restart(now, { h: restDeg, phi: 0 }, true); +} + +/** The offsets the scene's place and viewport allow (`view.ts` `offsetRange`); the first one met takes the offset to its bound at once, a new one eases there. */ +export function setRange(limit: Range, now: number): void { + const first = range === undefined; + range = limit; + restart(now, {}, first); +} + +/** + * A manual turn: the view direction becomes `h` now, in every mode, and the rotation stops where the viewer left it (ruling ridge-view-turn-handback): the view + * is held in cameraState, which leaves the chosen mode as it is; a rebuild keeps the hold, and picking a mode, the one already chosen included, resumes it. + */ +export function hold(h: number, now: number): void { + begin(now, { ...poseAt(now), h }); + if (isHeld()) emit(); + else holdCamera(now); // the owner starts the held segment, then the camera's listeners hear it, once +} + +/** Nothing turns while `on` (reduced motion), whatever the viewer chose; the view takes the pose owed at once and stays there. */ +export function freeze(on: boolean, now: number): void { + if (on === frozen) return; + frozen = on; + restart(now); +} + +/** Bring `h` and `phi` into [0, 360) at `now`, so the transforms stay small however long the page has been open: the whole turns are all that goes, and the ease and the motion go on. Silent: the caller lays out again. */ +export function normalize(now: number): void { + const s = current(now); + const p = pose(s, now); + const dh = 360 * Math.floor(p.h / 360); + const dphi = 360 * Math.floor(p.phi / 360); + s.h -= dh; + s.phi -= dphi; + if (s.phiTo !== undefined) s.phiTo -= dphi; +} + +/** Hear every change of the pose's course: the viewer's choice or hold, a bound, reduced motion, a manual turn, a new place; returns the way to stop. */ +export function subscribe(cb: () => void): () => void { + listeners.add(cb); + return () => listeners.delete(cb); +} + +/** For tests: the state of a fresh page. */ +export function resetHeading(): void { + seg = undefined; + frozen = false; + anchored = undefined; + speed = undefined; + range = undefined; + listeners.clear(); +} diff --git a/src/app/features/scene/ridge/horizon.test.ts b/src/app/features/scene/ridge/horizon.test.ts deleted file mode 100644 index 0061bab1..00000000 --- a/src/app/features/scene/ridge/horizon.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -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); - }); -}); diff --git a/src/app/features/scene/ridge/horizon.ts b/src/app/features/scene/ridge/horizon.ts deleted file mode 100644 index 89d896bc..00000000 --- a/src/app/features/scene/ridge/horizon.ts +++ /dev/null @@ -1,54 +0,0 @@ -// 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]; -} - -/** The elevations blurred over +-SMOOTH_DEG (a box, around the ring): at 30 m a city's roofs are the horizon's teeth, and a silhouette of them reads as a fence. */ -const SMOOTH_DEG = 1.5; -const SMOOTH = Array.from({ length: N }, (_, i) => { - const k = Math.round(SMOOTH_DEG / bake.stepDeg); - let sum = 0; - for (let d = -k; d <= k; d += 1) sum += bake.elevationDeg[(i + d + N) % N]; - return sum / (2 * k + 1); -}); -const MIN_E = Math.min(...SMOOTH); -const RANGE_E = Math.max(...SMOOTH) - MIN_E; - -/** The horizon at an azimuth as 0..1 of the ring's own range (the lowest point of the horizon 0, the highest 1): the silhouette's shape, not its scale. */ -export const horizonShape = (azimuth: number): number => (lerp(SMOOTH, azimuth) - MIN_E) / RANGE_E; - -/** Real range of the smoothed horizon, degrees: what `horizonShape` stretches to the layer's relief. */ -export const HORIZON_RANGE_DEG = RANGE_E; - -/** Horizontal field of view, degrees, of a camera with the sky's vertical field (`skyDome.ts` VFOV_DEG) at an aspect ratio. */ -export const hfovDeg = (aspect: number, vfovDeg: number): number => - (2 * Math.atan(aspect * Math.tan((vfovDeg * Math.PI) / 360)) * 180) / Math.PI; diff --git a/src/app/features/scene/ridge/horizonLayer.test.ts b/src/app/features/scene/ridge/horizonLayer.test.ts deleted file mode 100644 index b034d03c..00000000 --- a/src/app/features/scene/ridge/horizonLayer.test.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { hfovDeg, horizonShape } from './horizon'; -import { HORIZON_TRACK_SHIFT, LAYERS, layerProfile, profile } from './ridgeWorld'; -import { layerPaint } from './ridgeBake'; -import { weatherOf } from './weather'; -import { skyColours } from './skyColour'; -import { makePhysicalSky } from './physicalSky'; -import { VFOV_DEG } from './skyDome'; - -describe('the horizon layer', () => { - const far = LAYERS[0]; - const view = { azimuthDeg: 200, hfovDeg: hfovDeg(16 / 9, VFOV_DEG) }; - - it('is the farthest layer, real and standing still', () => { - expect(far.horizon).toBe(true); - expect(Number.isFinite(far.seconds)).toBe(false); - expect(LAYERS.slice(1).every((l) => !l.horizon && Number.isFinite(l.seconds))).toBe(true); - }); - - it('reads world-x as azimuth across the viewport: the left edge is half the field to the left of the view, the right edge half to the right', () => { - const left = layerProfile(far, HORIZON_TRACK_SHIFT, view); - const right = layerProfile(far, HORIZON_TRACK_SHIFT + 1, view); - expect(left).toBeCloseTo(horizonShape(200 - view.hfovDeg / 2), 9); - expect(right).toBeCloseTo(horizonShape(200 + view.hfovDeg / 2), 9); - }); - - it('stays in 0..1 and covers a real range of shape, not a line', () => { - const v = Array.from({ length: 200 }, (_, i) => - layerProfile(far, -0.06 + (i / 200) * 1.2, { azimuthDeg: 305, hfovDeg: view.hfovDeg }) - ); - expect(Math.min(...v)).toBeGreaterThanOrEqual(0); - expect(Math.max(...v)).toBeLessThanOrEqual(1); - expect(Math.max(...v) - Math.min(...v)).toBeGreaterThan(0.2); - }); - - it('is the noise profile for the other layers, and for the horizon layer when no view is known', () => { - expect(layerProfile(LAYERS[2], 0.4, view)).toBe(profile(LAYERS[2], 0.4)); - expect(layerProfile(far, 0.4)).toBe(profile(far, 0.4)); - }); - - it('the horizontal field of a 1:1 view is the vertical one, and grows with the aspect', () => { - expect(hfovDeg(1, VFOV_DEG)).toBeCloseTo(VFOV_DEG, 9); - expect(hfovDeg(16 / 9, VFOV_DEG)).toBeGreaterThan(VFOV_DEG); - }); -}); - -describe('weather in the layers', () => { - it("mist multiplies the layers' own, and clear air leaves it alone", () => { - const base = skyColours(); - const day = new Date('2026-06-21T10:40:00Z'); - const clear = layerPaint(LAYERS[1], { ...base, physical: makePhysicalSky('day', day, 0) }); - const misty = layerPaint(LAYERS[1], { ...base, physical: makePhysicalSky('day', day, 0.8) }); - expect(clear.mistK).toBe(1); - expect(misty.mistK).toBeGreaterThan(2); - expect(layerPaint(LAYERS[1], base).mistK).toBe(1); - }); -}); - -describe('the weather number', () => { - it('a number that is not finite is a clear sky, not an error', () => { - expect(weatherOf(Number.NaN).value).toBe(0); - expect(weatherOf(Infinity).value).toBe(0); - expect(weatherOf(0.5).value).toBe(0.5); - }); -}); diff --git a/src/app/features/scene/ridge/lightCards.test.ts b/src/app/features/scene/ridge/lightCards.test.ts new file mode 100644 index 00000000..8b1b76b3 --- /dev/null +++ b/src/app/features/scene/ridge/lightCards.test.ts @@ -0,0 +1,409 @@ +import { describe, expect, it, vi } from 'vitest'; +import { + decodeNormal, + DEFAULT_LOOK, + PHYSICAL_LOOK, + celShade, + celLevels, + FRAGMENT, + createLighter, + lightingOf, + ringAzimuth, + skyLut, + SKY_LUT, + sunColumns, + sunInColumn, + WALL_RT2, +} from './lightCards'; +import type { RidgeLook } from './lightCards'; +import { parseManifest } from './manifest'; +import { wireManifest } from './manifest.fixture'; +import type { PhysicalSky } from './physicalSky'; +import { ACES_FIT, ACES_IN, ACES_OUT, BLACK_LIFT, makeCurve } from './toneMap'; + +const manifest = parseManifest(wireManifest(), '/d/'); +const RAD = Math.PI / 180; +const dot = (a: readonly number[], b: readonly number[]) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + +/** A display curve that is the straight line from the black lift to white: a fixture, the cards only need some curve to carry. */ +const FLAT_CURVE = makeCurve( + [0, 0.25, 0.5, 0.75, 1], + [0, 0.25, 0.5, 0.75, 1].map((v) => BLACK_LIFT + (1 - BLACK_LIFT) * v) +); + +describe("the sun in a column's frame", () => { + it.each([5, 30, 60, 89])( + 'at elevation %i it lights an up-facing normal by sin e and a normal facing it by 1', + (e) => { + const s = sunInColumn({ azimuth: 130, elevation: e }, 130); + expect(dot([0, 0, 1], s)).toBeCloseTo(Math.sin(e * RAD), 12); + expect(dot([Math.cos(e * RAD), 0, Math.sin(e * RAD)], s)).toBeCloseTo(1, 12); + expect(Math.hypot(...s)).toBeCloseTo(1, 12); + } + ); + + it('turns with the column: a sun 90 degrees clockwise of the ray lights the across axis, one behind lights the back', () => { + const across = sunInColumn({ azimuth: 100, elevation: 0 }, 10); + expect(across[0]).toBeCloseTo(0, 12); + expect(across[1]).toBeCloseTo(1, 12); + expect(sunInColumn({ azimuth: 190, elevation: 0 }, 10)[0]).toBeCloseTo(-1, 12); + expect(sunInColumn({ azimuth: 10, elevation: 0 }, 100)[1]).toBeCloseTo(-1, 12); + }); + + it('is computed for every column of the ring, from its own absolute azimuth', () => { + const view = manifest.view; + const cols = sunColumns(view, { azimuth: 214, elevation: 20 }); + expect(cols).toHaveLength(view.ringW * 4); + const at = (x: number) => Array.from(cols.slice(x * 4, x * 4 + 3)); + const sunCol = Math.floor((214 / 360) * view.ringW); + expect(ringAzimuth(sunCol, view.ringW)).toBeCloseTo(214, 1); + expect(at(sunCol)[0]).toBeCloseTo(Math.cos(20 * RAD), 3); // the column that looks at the sun's azimuth + expect(at(sunCol - 1000)[1]).toBeGreaterThan(0.1); // the sun is to the right of columns before it, and to the left of those after + expect(at(sunCol + 1000)[1]).toBeLessThan(-0.1); + // Every column is a unit vector, the first column of the ring looks north and the last looks just west of it. + for (let x = 0; x < view.ringW; x += 400) expect(Math.hypot(...at(x))).toBeCloseTo(1, 5); + expect(ringAzimuth(0, view.ringW)).toBeCloseTo(0.028125, 6); + expect(ringAzimuth(view.ringW - 1, view.ringW)).toBeCloseTo(360 - 0.028125, 6); + }); +}); + +describe('the wall code', () => { + it('reads R = G = 255 as a wall and a real normal as a normal', () => { + expect(decodeNormal(255, 255)).toEqual({ wall: true }); + const flat = decodeNormal(128, 128); + expect(flat.wall).toBe(false); + if (!flat.wall) expect(flat.n[2]).toBeGreaterThan(0.99); + // The steepest real normal of the Vienna bake (r2 + t2 = 0.998) still decodes as terrain. + const r8 = Math.round(((Math.sqrt(0.998) + 1) / 2) * 255); + const steep = decodeNormal(r8, 128); + expect(steep.wall).toBe(false); + if (!steep.wall) expect(Math.hypot(...steep.n)).toBeCloseTo(1, 1); + expect(0.998).toBeLessThan(WALL_RT2); + expect(2).toBeGreaterThan(WALL_RT2); + }); + + it('the shader carries the same threshold', () => { + expect(FRAGMENT).toContain(`const float WALL_RT2 = ${WALL_RT2};`); + }); +}); + +describe('the lighting inputs', () => { + const atm = (sinLog: number[] = []) => ({ + observerKm: 0.183, + mieScale: 1, + transmittanceToSpace: (mu: number, out: number[]) => { + sinLog.push(mu); + out[0] = 0.9 * mu; + out[1] = 0.8 * mu; + out[2] = 0.7 * mu; + }, + irradiance: { direct: [0, 0, 0], ambient: [0.1, 0.2, 0.3] }, + radiance: vi.fn((vz: number, cosSun: number, out: number[]) => { + out[0] = vz; + out[1] = cosSun; + out[2] = 1; + }), + }); + const sky = (elevation: number, a = atm()): PhysicalSky => + ({ + sun: { azimuth: 214, elevation }, + atm: a, + fit: { display: { exposure: 12, curve: FLAT_CURVE } }, + view: manifest.view, + } as unknown as PhysicalSky); + + it("takes the display of the sky's own fit, so terrain and sky share one exposure", () => { + const l = lightingOf(manifest, sky(30)); + expect([l.exposure, l.curve]).toEqual([12, FLAT_CURVE]); + [0.1, 0.2, 0.3].forEach((a, i) => expect(l.key.ambient[i]).toBeCloseTo(a, 6)); // plus the airglow's + expect(l.logDMin).toBe(4.6); + expect(l.logDSpan).toBeCloseTo(11.5 - 4.6, 12); + }); + + it("gives the ground the sun's transmittance at its elevation, and none with the sun below the atmosphere's cut-off", () => { + const l = lightingOf(manifest, sky(30)); + expect(l.key.direct[0]).toBeCloseTo(0.9 * Math.sin(30 * RAD), 12); + expect(l.key.direct[2]).toBeCloseTo(0.7 * Math.sin(30 * RAD), 12); + expect(lightingOf(manifest, sky(DEFAULT_LOOK.sunCutoffDeg - 1)).key.direct).toEqual([0, 0, 0]); + expect( + lightingOf(manifest, sky(DEFAULT_LOOK.sunCutoffDeg + 0.5)).key.direct[0] + ).toBeGreaterThanOrEqual(0); + }); + + it("takes the haze's extinction from the atmosphere at the observer: more aerosol, more extinction", () => { + const clear = lightingOf(manifest, sky(30, { ...atm(), mieScale: 1 })); + const hazy = lightingOf(manifest, sky(30, { ...atm(), mieScale: 4 })); + expect(clear.extinction.every((e) => e > 0)).toBe(true); + hazy.extinction.forEach((e, k) => expect(e).toBeGreaterThan(clear.extinction[k])); + }); + + it("builds the haze lookup from the view direction of each texel, the horizon's below it", () => { + const a = atm(); + const lut = skyLut(sky(30, a), manifest.view, SKY_LUT.w, SKY_LUT.h); + expect(lut).toHaveLength(SKY_LUT.w * SKY_LUT.h * 4); + const texel = (i: number, j: number) => + Array.from(lut.slice((j * SKY_LUT.w + i) * 4, (j * SKY_LUT.w + i) * 4 + 3)); + const { horizonRow, planeH, pxPerDegV } = manifest.view; + const rowAt = (j: number) => ((j + 0.5) / SKY_LUT.h) * planeH; + // A row above the horizon asks the sky for the sine of its elevation; a row below it asks for the horizon. + const above = Math.floor((horizonRow / planeH) * SKY_LUT.h) - 6; + expect(texel(0, above)[0]).toBeCloseTo( + Math.sin(((horizonRow - rowAt(above)) / pxPerDegV) * RAD), + 7 // the airglow floor adds a few 1e-9 + ); + expect(texel(0, SKY_LUT.h - 1)[0]).toBeCloseTo(0, 7); + // The sun lies at 214 degrees: the cosine from the sun is 1 at its column and falls round the ring. The table spans the ring, so 320 columns. + expect(SKY_LUT.w).toBe(320); + const sunI = Math.floor((214 / 360) * SKY_LUT.w); + const mid = texel(sunI, above)[1]; + expect(mid).toBeGreaterThan(0.999); + expect(texel(0, above)[1]).toBeLessThan(mid); + expect(texel(sunI + 160, above)[1]).toBeLessThan(-0.9); + }); +}); + +describe('the ring in the shader', () => { + it('reads the sun and the sky by the column of the ring, not of the file, and wraps at the ends', () => { + expect(FRAGMENT).toContain('int col = ((uCol0 + p.x) % uRingW + uRingW) % uRingW;'); + expect(FRAGMENT).toContain('texelFetch(uSun, ivec2(col, 0), 0)'); + expect(FRAGMENT).toContain('(float(col) + 0.5) / float(uRingW)'); + expect(FRAGMENT).toContain('(int(b.x) % w + w) % w'); // the sky table wraps in azimuth + }); + it('gives the ground noise the ground point, so it is the same at ring column 0 and column 6400', () => { + // The noise coordinate is dist x (sin psi, cos psi) with psi from the wrapped column: sin and cos of 0 and of a whole turn are one point. + expect(FRAGMENT).toContain('vec2 world = vec2(sin(psi), cos(psi)) * dist;'); + expect(FRAGMENT).toContain('float psi = (float(col) + 0.5) / float(uRingW) * 2.0 * PI;'); + expect(FRAGMENT).not.toContain("uRadPerPx"); + const at = (col: number, w: number) => { + const psi = ((((col % w) + w) % w) + 0.5) / w * 2 * Math.PI; + return [Math.sin(psi), Math.cos(psi)]; + }; + expect(at(6400, 6400)[0]).toBeCloseTo(at(0, 6400)[0], 12); + expect(at(6400, 6400)[1]).toBeCloseTo(at(0, 6400)[1], 12); + }); +}); + +describe('the display of the shader', () => { + const g = (n: number) => (Number.isInteger(n) ? `${n}.0` : String(n)); + it("writes toneMap.ts's ACES matrices and fit into the source", () => { + ACES_IN.forEach((row, i) => + expect(FRAGMENT).toContain(`const vec3 IN_R${i} = vec3(${row.map(g).join(', ')});`) + ); + ACES_OUT.forEach((row, i) => + expect(FRAGMENT).toContain(`const vec3 OUT_R${i} = vec3(${row.map(g).join(', ')});`) + ); + expect(FRAGMENT).toContain(`vec3(${g(ACES_FIT[0])}, ${g(ACES_FIT[1])}, 0.0)`); + expect(FRAGMENT).toContain(`vec3(${g(ACES_FIT[2])}, ${g(ACES_FIT[3])}, ${g(ACES_FIT[4])})`); + }); +}); + +describe('the look reaches the shader', () => { + // A recording WebGL2: every uniform call is kept by the name of its location, nothing is drawn. + const run = (look?: Partial, tile = 0) => { + const uniforms: Record = {}; + const crops: number[][] = []; + const gl = new Proxy( + { + getUniformLocation: (_p: unknown, name: string) => name, + drawImage: (...a: unknown[]) => crops.push(a.slice(1) as number[]), + getShaderParameter: () => true, + getProgramParameter: () => true, + getExtension: () => null, + } as Record, + { + get: (t, k: string) => + k in t + ? t[k] + : k.startsWith('uniform') + ? (name: string, ...v: number[]) => { + uniforms[name] = v; + } + : () => ({}), + } + ); + const el = { width: 0, height: 0, getContext: () => gl }; + vi.stubGlobal('document', { createElement: () => el }); + const bmp = { width: 1604, height: 7, close: () => undefined } as unknown as ImageBitmap; + const sky = { + sun: { azimuth: 214, elevation: 30 }, + atm: { + observerKm: 0.183, + mieScale: 1, + transmittanceToSpace: (_m: number, o: number[]) => o.fill(1), + irradiance: { direct: [0, 0, 0], ambient: [0.1, 0.2, 0.3] }, + radiance: (_a: number, _b: number, o: number[]) => o.fill(0), + }, + fit: { display: { exposure: 1, curve: FLAT_CURVE } }, + view: manifest.view, + } as unknown as PhysicalSky; + const one = { ...manifest, cards: manifest.cards.slice(0, 1) }; + let canvas: { width: number; height: number } | undefined; + try { + const lighter = createLighter(one, sky, look && { ...DEFAULT_LOOK, ...look }); + canvas = lighter.light({ colour: bmp, geometry: bmp }, tile, 0) as unknown as typeof canvas; + } finally { + vi.unstubAllGlobals(); + } + return Object.assign(uniforms, { crops, canvas }); + }; + + it('lights a tile from its own columns: the ring column of the file, the band, and the interior with one overlap column each side', () => { + const u = run(undefined, 3); + const { view } = manifest; + expect(u.uCol0).toEqual([3 * view.tileW - view.apron]); // tile 3 of 4: the file starts two columns before its first + expect(u.uRingW).toEqual([view.ringW]); + expect(u.uTop).toEqual([manifest.tiles[3][0]!.top]); + expect(u.uSkySize).toEqual([320, 64]); + // The file holds tileW + 2 apron columns; the canvas keeps columns apron - 1 .. apron + tileW: the interior and one column each side. + expect(u.crops).toEqual([[view.apron - 1, 0, view.tileW + 2, 7, 0, 0, view.tileW + 2, 7]]); + expect(u.canvas).toMatchObject({ width: view.tileW + 2, height: 7 }); + }); + + it('throws without WebGL2: the caller makes the sky alone', () => { + vi.stubGlobal('document', { createElement: () => ({ getContext: () => null }) }); + expect(() => createLighter(manifest, {} as PhysicalSky)).toThrow(/WebGL2/); + vi.unstubAllGlobals(); + }); + + it('defaults to DEFAULT_LOOK', () => { + const u = run(); + expect(u.uInkKeep).toEqual([0.45, 0.55, 0.8]); + expect(u.uInkGeometry).toEqual([0.35, 0.85]); + }); + + it('carries an ink override to the uniforms: edge keep 1 removes edge ink', () => { + const u = run({ inkKeep: { edge: 1, occlude: 0.55, crease: 0.8 } }); + expect(u.uInkKeep[0]).toBe(1); + }); + + it('carries the art-pass axes: relief, fixed light, tint, tone, ink scale, noise', () => { + const u = run({ + reliefWeight: 0.15, + reliefLight: { mix: 1, azimuthDeg: 0, elevationDeg: 90 }, + hazeTint: [0, 0.1, 0.3], + nearWarm: 0.5, + contrastByDistance: 1.5, + cardToneStep: 0.2, + cardGradient: 0.3, + inkScale: 0, + groundNoise: 0.4, + cloudShadows: 0.6, + }); + expect(u.uRelief).toEqual([0.15, 1]); + expect(u.uFixedLight[2]).toBeCloseTo(1, 12); // a light straight up + expect(u.uHazeTint).toEqual([0, 0.1, 0.3]); + expect(u.uDist).toEqual([0.5, 1.5]); + expect(u.uCard).toEqual([1, 0.3]); // a single card sits at the centre of the tone steps + expect(u.uInkScale).toEqual([0]); + expect(u.uGround).toEqual([0.4, 0.6]); + }); + + it('scales the haze optical depth and the ambient light, and moves the sun cut-off', () => { + const base = run(); + const look = run({ hazeScale: 2 * DEFAULT_LOOK.hazeScale, ambientScale: 0.5 }); + look.uExt.forEach((e, k) => expect(e).toBeCloseTo(2 * base.uExt[k], 12)); + expect(look.uAmbient[2]).toBeCloseTo(0.15, 6); // plus the airglow's ambient + expect( + lightingOf(manifest, sky30(), { ...DEFAULT_LOOK, sunCutoffDeg: 45 }).key.direct + ).toEqual([0, 0, 0]); + }); +}); + +function sky30(): PhysicalSky { + return { + sun: { azimuth: 214, elevation: 30 }, + atm: { + observerKm: 0.183, + mieScale: 1, + transmittanceToSpace: (_m: number, o: number[]) => o.fill(1), + irradiance: { direct: [0, 0, 0], ambient: [0, 0, 0] }, + }, + fit: { display: { exposure: 1, curve: FLAT_CURVE } }, + } as unknown as PhysicalSky; +} + +describe('night key light', () => { + const atmOf = (ambient: [number, number, number]) => ({ + observerKm: 0.183, + mieScale: 1, + transmittanceToSpace: (_m: number, o: number[]) => o.fill(1), + irradiance: { direct: [0, 0, 0], ambient }, + radiance: (_a: number, _b: number, o: number[]) => o.fill(0), + }); + const night = (moonEl: number | undefined, state = 'night') => + lightingOf(manifest, { + state, + sun: { azimuth: 0, elevation: -30 }, + moon: { azimuth: 150, elevation: moonEl ?? -20 }, + night: + moonEl === undefined + ? {} + : { moon: { azimuth: 150, elevation: moonEl, ratio: 2.5e-6, atm: atmOf([0.4, 0.5, 0.8]) } }, + atm: atmOf([0.001, 0.001, 0.002]), + fit: { display: { exposure: 1, curve: FLAT_CURVE } }, + view: manifest.view, + } as unknown as PhysicalSky); + + it('is the moon at night: its direction, its irradiance ratio times the transmittance, its ambient scaled by the ratio', () => { + const l = night(40); + expect([l.key.azimuth, l.key.elevation]).toEqual([150, 40]); + expect(l.key.direct[0]).toBeCloseTo(2.5e-6, 12); + expect(l.key.ambient[2]).toBeGreaterThan(0.002); + expect(l.key.ambient[2]).toBeCloseTo(0.002 + 0.8 * 2.5e-6, 4); + }); + it('has no direct light with the moon down, and keeps the ambient (twilight and airglow)', () => { + const l = night(undefined); + expect(l.key.direct).toEqual([0, 0, 0]); + expect(l.key.ambient.every((a) => a > 0)).toBe(true); + }); + it('fades the moon out over the horizon', () => { + expect(night(-0.5).key.direct[0]).toBe(0); + expect(night(0.5).key.direct[0]).toBeGreaterThan(0); + expect(night(0.5).key.direct[0]).toBeLessThan(night(5).key.direct[0]); + }); + it('the sun lights the other states', () => { + const l = lightingOf(manifest, sky30()); + expect(l.key.elevation).toBe(30); + }); +}); + +describe('cel shading', () => { + const sweep = (bands: number, softness: number, levels?: number[]) => { + const out = new Set(); + for (let i = -20; i <= 100; i += 1) { + const x = i / 100; + // away from the band edges (i / bands), where a softened edge is between two levels + if (Array.from({ length: bands }, (_, k) => k / bands).some((e) => e > 0 && Math.abs(x - e) <= softness / 2 + 1e-9)) continue; + out.add(Math.round(celShade(x, bands, softness, levels) * 1e9)); + } + return out; + }; + it.each([1, 2, 3, 4, 6])('quantizes a normal sweep to exactly %i levels away from the edges', (n) => { + expect(sweep(n, 0.05).size).toBe(n); + expect(sweep(n, 0).size).toBe(n); + }); + it('is monotone in n.s, from the lowest level to the highest, and softens an edge without a jump', () => { + let prev = -1; + let maxStep = 0; + for (let i = -20; i <= 100; i += 1) { + const v = celShade(i / 100, 3, 0.1); + expect(v).toBeGreaterThanOrEqual(prev - 1e-12); + if (prev >= 0) maxStep = Math.max(maxStep, v - prev); + prev = v; + } + expect(maxStep).toBeLessThan(0.3); + expect(celShade(-0.5, 3, 0)).toBe(0); + expect(celShade(1, 3, 0)).toBe(1); + }); + it('takes the band levels it is given', () => { + expect(celLevels(3, [0.2, 0.5, 0.9]).slice(0, 3)).toEqual([0.2, 0.5, 0.9]); + expect(celShade(0.9, 3, 0, [0.2, 0.5, 0.9])).toBe(0.9); + expect(celShade(-1, 3, 0, [0.2, 0.5, 0.9])).toBe(0.2); + }); + it('is on in the default look and off in the physical one; the shader carries the ramp', () => { + expect(DEFAULT_LOOK.celBands).toBeGreaterThan(0); + expect(PHYSICAL_LOOK.celBands).toBe(0); + expect(FRAGMENT).toContain('float cel(float x)'); + expect(FRAGMENT).toContain('uBandLevels[6]'); + }); +}); diff --git a/src/app/features/scene/ridge/lightCards.ts b/src/app/features/scene/ridge/lightCards.ts new file mode 100644 index 00000000..39c5fcc9 --- /dev/null +++ b/src/app/features/scene/ridge/lightCards.ts @@ -0,0 +1,674 @@ +// The one lighting pass of the ridge cards (ruling ridge-cards-runtime-lit): each baked G-buffer card tile (colour with straight alpha, geometry with the +// 'rt8' normal and log-distance, `scripts/ridge-bake/export.py`) is lit once, for the sky this scene build was made for, in one WebGL2 context on a +// canvas of its own (a lighter, one per sky), and copied into a 2D canvas of the tile's interior plus one overlap column each side. The sun and the sky's +// haze are tables over the whole ring in absolute azimuth, so a tile is lit from its own files alone and the apron (the neighbours' real columns, read for +// the ink pass and dropped) makes its edges equal what a lit neighbour would give. There is no per-frame WebGL, and the host canvas stays 2D +// (`Ridge.ts`). A sky change rebuilds the scene and makes a new lighter; nothing patches the lit canvases. +// +// Per pixel: the normal from the geometry card in the column's frame (r along the ray, t across it, up), the sun brought into that frame per column; +// radiance = albedo x (sun transmittance x max(n.s, 0) + ambient irradiance) / pi; aerial perspective L T(d) + Lsky (1 - T(d)) with d from the +// geometry's log-distance and the sky's own extinction at the ground; contours; then the sky's own display (exposure, ACES with `toneMap.ts`'s +// constants written into the shader, the sky's fitted curve, sRGB), so terrain and sky share one exposure. Wall pixels (R = G = 255 in the geometry file, a code +// no real normal reaches) are the extruded face under a ridge: they are lit with the face up and wear no crease ink. +import { extinctionAt } from './earthAtmosphere'; +import type { Vec3 } from './earthAtmosphere'; +import type { RidgeManifest } from './manifest'; +import type { PhysicalSky } from './physicalSky'; +import { addNightRadiance, airglow } from './nightSky'; +import { ACES_FIT, ACES_IN, ACES_OUT, KNOTS, SCOTOPIC } from './toneMap'; +import type { Curve } from './toneMap'; +import type { View } from './view'; + + +/** A real normal has r2 + t2 at most 0.998 (probe on the Vienna bake); the wall code is 2. A code of the data, not of the look. */ +export const WALL_RT2 = 1.02; +/** The lookup of the sky's radiance for the haze: azimuth columns over the whole ring (the angular density of 64 over a 72 degree window) by plane rows, filtered in the shader. */ +export const SKY_LUT = { w: 320, h: 64 } as const; + +/** + * The look: every number of the art pass (ratatoskr:follow_up:ridge-art-quality-rework), the one owner of them. None is a rule of the machine. + * The shader reads them as uniforms, so one compiled program serves every look. + */ +export interface RidgeLook { + /** A neighbour farther by more than this many nats of distance draws occluding ink on this pixel. */ + occludeLogD: number; + /** A normal turning past this cosine between two non-wall pixels draws crease ink. */ + creaseCos: number; + /** How much each ink keeps of the radiance it falls on (1 = no ink). */ + inkKeep: { edge: number; occlude: number; crease: number }; + /** Below this sun elevation (degrees) no direct sun reaches the ground (the atmosphere's own cut-off, `earthAtmosphere.ts` irradiance). */ + sunCutoffDeg: number; + /** Multiplies the optical depth of the aerial perspective: 1 is the sky's own extinction, 0 no haze. */ + hazeScale: number; + /** Multiplies the ambient irradiance the terrain is lit by. */ + ambientScale: number; + /** 0 = no normal shading (the flat card tone, as a horizontal surface), 1 = shaded by the normals. */ + reliefWeight: number; + /** The relief light: `mix` 0 is the sun, 1 a fixed light; `azimuthDeg` is clockwise of the view ray (-45 = upper left, behind the ridge), `elevationDeg` above the horizon. */ + reliefLight: { mix: number; azimuthDeg: number; elevationDeg: number }; + /** Added to the sky radiance used for the haze, rgb in units of that radiance's own luminance (so it holds at every sky): positive blue = cool far. */ + hazeTint: readonly [number, number, number]; + /** Strength (0..1) of a warm tint on the near, fading out with the log-distance across the baked range. */ + nearWarm: number; + /** The relief's contrast about the pixel's flat tone scales by exp(c (1 - 2 d)), d the log-distance across the baked range: c > 0 near contrasty, far flat. */ + contrastByDistance: number; + /** Value of each card multiplies by 1 + step (index - centre); the nearest card is index 0, so a positive step makes near darkest. */ + cardToneStep: number; + /** Value ramp inside each card: 1 + g (y - 1/2), y the fraction down the card; positive lightens toward the foot. */ + cardGradient: number; + /** Multiplies each ink's darkening: 0 = no lines. */ + inkScale: number; + /** Procedural albedo variation (a stand-in for land cover we do not bake): fbm in metres on the ground, so its screen frequency follows distance. 0 = none. */ + groundNoise: number; + /** Low-frequency noise darkening of the direct sun (static). 0 = none. */ + cloudShadows: number; + /** Cel shading: the lit side of the relief (n.s) in this many flat bands instead of Lambert's ramp (0 = Lambert; at most `CEL_MAX`). */ + celBands: number; + /** Width of each band edge in n.s units (0 = hard). */ + celSoftness: number; + /** The level of each band, 0..1, darkest first (default: evenly from 0 to 1). Length `celBands`. */ + celBandLevels?: readonly number[]; + /** The ambient is coarse too: surfaces facing the sky (the normal's up component past `celAmbientEdge`) keep it whole, the rest keep this fraction (1 = no step). */ + celAmbientAway: number; + celAmbientEdge: number; +} + +/** The first art pass's look: Lambert relief, no procedural variation, the sky's own haze, full ink. Kept for comparison in the look sheet. */ +export const PHYSICAL_LOOK: RidgeLook = { + occludeLogD: 0.35, + creaseCos: 0.85, + inkKeep: { edge: 0.45, occlude: 0.55, crease: 0.8 }, + sunCutoffDeg: -1, + hazeScale: 1, + ambientScale: 1, + reliefWeight: 1, + reliefLight: { mix: 0, azimuthDeg: -45, elevationDeg: 40 }, + hazeTint: [0, 0, 0], + nearWarm: 0, + contrastByDistance: 0, + cardToneStep: 0, + cardGradient: 0, + inkScale: 1, + groundNoise: 0, + cloudShadows: 0, + celBands: 0, + celSoftness: 0, + celAmbientAway: 1, + celAmbientEdge: 0.7, +}; + +/** The default: painterly (ground variation, cloud shadows, warm near, moderate haze, light ink) with cel-shaded relief. */ +export const DEFAULT_LOOK: RidgeLook = { + ...PHYSICAL_LOOK, + groundNoise: 0.35, + cloudShadows: 0.5, + nearWarm: 0.6, + hazeScale: 2, + inkScale: 0.4, + celBands: 3, + celSoftness: 0.05, + celAmbientAway: 0.7, +}; + +/** Most bands the shader's uniform holds. */ +export const CEL_MAX = 6; + +/** The level of each of `bands` cel bands, darkest first: `custom` where given, else evenly 0..1 (one band is fully lit). Padded to `CEL_MAX`. */ +export function celLevels(bands: number, custom?: readonly number[]): number[] { + const n = Math.min(CEL_MAX, Math.max(1, Math.round(bands))); + return Array.from({ length: CEL_MAX }, (_, i) => { + const k = Math.min(i, n - 1); + return custom?.[k] ?? (n === 1 ? 1 : k / (n - 1)); + }); +} + +const smooth = (a: number, b: number, v: number): number => { + const t = Math.min(1, Math.max(0, (v - a) / (b - a))); + return t * t * (3 - 2 * t); +}; + +/** + * The cel ramp: the light of a surface whose normal makes `ndl` with the sun, in `bands` flat bands, edges at i / bands (i = 1..bands-1), each + * edge `softness` wide. The lowest band holds the unlit side too (its level is what ambient light alone leaves). The shader writes the same. + */ +export function celShade(ndl: number, bands: number, softness: number, levels?: readonly number[]): number { + const n = Math.min(CEL_MAX, Math.max(1, Math.round(bands))); + const lv = celLevels(n, levels); + let out = lv[0]; + for (let i = 1; i < n; i += 1) { + const e = i / n; + const w = softness / 2; + out += (lv[i] - lv[i - 1]) * (w > 0 ? smooth(e - w, e + w, ndl) : ndl >= e ? 1 : 0); + } + return out; +} + +const RAD = Math.PI / 180; + +/** The sun in the frame of a column looking at azimuth `columnAzDeg`: along the ray, across it (clockwise, +90 degrees), up. Unit length. */ +export function sunInColumn( + sun: { azimuth: number; elevation: number }, + columnAzDeg: number +): [number, number, number] { + const el = sun.elevation * RAD; + const d = (sun.azimuth - columnAzDeg) * RAD; + return [Math.cos(el) * Math.cos(d), Math.cos(el) * Math.sin(d), Math.sin(el)]; +} + +/** The compass azimuth of ring column `col` of `w` columns (column 0 = north), taken at the column's centre. */ +export const ringAzimuth = (col: number, w: number): number => ((col + 0.5) / w) * 360; + +/** A geometry texel's red and green bytes as the shader reads them: a wall, or the unit normal (along the ray, across it, up). */ +export function decodeNormal( + r8: number, + g8: number +): { wall: true } | { wall: false; n: [number, number, number] } { + const r = (r8 / 255) * 2 - 1; + const t = (g8 / 255) * 2 - 1; + const rt2 = r * r + t * t; + return rt2 > WALL_RT2 + ? { wall: true } + : { wall: false, n: [r, t, Math.sqrt(Math.max(0, 1 - rt2))] }; +} + +/** Everything the lighting reads of the sky and the manifest, as the numbers the shader's uniforms hold. */ +export interface Lighting { + ringW: number; + planeH: number; + logDMin: number; + logDSpan: number; + /** Per km of horizontal path, per channel. */ + extinction: Vec3; + /** Where the key light is (the sun by day and dusk, the moon at night) and what of it reaches the ground. */ + key: KeyLight; + exposure: number; + /** The sky's fitted curve (`toneMap.ts`), applied per channel after ACES. */ + curve: Curve; + /** Weight of the scotopic grade (`toneMap.ts`), applied to the radiance before exposure. */ + grade: number; +} + +/** + * The key light of the ground and what it brings. Day and dusk: the sun, by its transmittance to the ground, cut off below `look.sunCutoffDeg`. + * Night: the moon, by its transmittance times its irradiance relative to the sun's (phase and distance, `nightSky.ts`), faded out over the + * horizon; it is the direction the cel bands are cut by, and what is left of it, the sun's twilight and the airglow, is the ambient. + * `direct` is per unit of sun irradiance, `ambient` the irradiance the sky and the airglow give a horizontal surface. + */ +export interface KeyLight { + azimuth: number; + elevation: number; + direct: Vec3; + ambient: Vec3; +} + +export function keyLight(sky: PhysicalSky, look: RidgeLook = DEFAULT_LOOK): KeyLight { + const ambient = scale3(sky.atm.irradiance.ambient, look.ambientScale); + const glow = [0, 0, 0]; + airglow(0.6, glow); + const base = add3(ambient, scale3([glow[0], glow[1], glow[2]], Math.PI)); + const trans = [0, 0, 0]; + if (sky.state === 'night') { + const m = sky.night.moon; + if (!m) return { azimuth: sky.moon.azimuth, elevation: sky.moon.elevation, direct: [0, 0, 0], ambient: base }; + m.atm.transmittanceToSpace(Math.max(Math.sin(m.elevation * RAD), 0), trans); + const fade = smooth(-0.5, 1.5, m.elevation) * m.ratio; + return { + azimuth: m.azimuth, + elevation: m.elevation, + direct: [trans[0] * fade, trans[1] * fade, trans[2] * fade], + ambient: add3(base, scale3(scale3(m.atm.irradiance.ambient, look.ambientScale), m.ratio)), + }; + } + sky.atm.transmittanceToSpace(Math.max(Math.sin(sky.sun.elevation * RAD), 0), trans); + const lit = sky.sun.elevation > look.sunCutoffDeg; + return { + azimuth: sky.sun.azimuth, + elevation: sky.sun.elevation, + direct: lit ? [trans[0], trans[1], trans[2]] : [0, 0, 0], + ambient: base, + }; +} + +const scale3 = (v: Vec3, k: number): Vec3 => [v[0] * k, v[1] * k, v[2] * k]; +const add3 = (a: Vec3, b: Vec3): Vec3 => [a[0] + b[0], a[1] + b[1], a[2] + b[2]]; + +export function lightingOf( + manifest: RidgeManifest, + sky: PhysicalSky, + look: RidgeLook = DEFAULT_LOOK +): Lighting { + return { + ringW: manifest.view.ringW, + planeH: manifest.view.planeH, + logDMin: manifest.encoding.logDMin, + logDSpan: manifest.encoding.logDMax - manifest.encoding.logDMin, + extinction: scale3(extinctionAt(sky.atm.observerKm, sky.atm.mieScale), look.hazeScale), + key: keyLight(sky, look), + exposure: sky.fit.display.exposure, + curve: sky.fit.display.curve, + grade: sky.fit.display.grade ?? 0, + }; +} + +/** The sun in every column's frame, RGBA32F texels (a, b, c, 0), one row of `ringW`: absolute azimuth, so every tile reads the same table. */ +export function sunColumns(view: View, sun: { azimuth: number; elevation: number }): Float32Array { + const out = new Float32Array(view.ringW * 4); + for (let x = 0; x < view.ringW; x += 1) { + const [r, t, u] = sunInColumn(sun, ringAzimuth(x, view.ringW)); + out.set([r, t, u, 0], x * 4); + } + return out; +} + +/** + * The sky's radiance (per unit of sun irradiance) as the haze needs it: a small grid over the ring's azimuths and the plane's rows, the view + * direction of each texel's centre. Rows below the horizon take the horizon's radiance (the haze in front of a ridge is the air at its foot). + */ +export function skyLut(sky: PhysicalSky, view: View, w: number, h: number): Float32Array { + const out = new Float32Array(w * h * 4); + const rgb = [0, 0, 0]; + for (let j = 0; j < h; j += 1) { + const elDeg = Math.max(0, (view.horizonRow - ((j + 0.5) / h) * view.planeH) / view.pxPerDegV); + for (let i = 0; i < w; i += 1) { + const az = ((i + 0.5) / w) * 360; + sky.atm.radiance(Math.sin(elDeg * RAD), Math.cos((az - sky.sun.azimuth) * RAD), rgb); + addNightRadiance(sky.night, Math.sin(elDeg * RAD), az * RAD, rgb); + out.set([rgb[0], rgb[1], rgb[2], 0], (j * w + i) * 4); + } + } + return out; +} + +const glsl = (n: number): string => (Number.isInteger(n) ? `${n}.0` : String(n)); + +/** The fragment shader. `ACES_IN` and `ACES_OUT` are written as rows and applied with `dot`, so no transposition is in play. */ +export const FRAGMENT = `#version 300 es +precision highp float; +precision highp int; +precision highp sampler2D; +uniform sampler2D uColour; +uniform sampler2D uGeo; +uniform sampler2D uSun; +uniform sampler2D uSky; +uniform ivec2 uSize; +uniform ivec2 uSkySize; +uniform int uTop; +uniform int uCol0; // the ring column of the file's first texel (a tile's first column less its apron; may be below 0) +uniform int uRingW; +uniform float uPlaneH; +uniform vec2 uLogD; +uniform vec3 uExt; +uniform vec3 uTSun; +uniform vec3 uAmbient; +uniform float uExposure; +uniform float uGrade; +uniform vec3 uScotTint; +uniform float uCx[${KNOTS}]; +uniform float uCy[${KNOTS}]; +uniform float uCm[${KNOTS}]; +uniform vec2 uInkGeometry; // occludeLogD, creaseCos +uniform vec3 uInkKeep; // edge, occlude, crease +uniform float uInkScale; +uniform vec2 uRelief; // weight, mix toward the fixed light +uniform vec3 uFixedLight; // in the column frame +uniform vec3 uHazeTint; +uniform vec2 uDist; // nearWarm, contrastByDistance +uniform vec2 uCard; // value of this card, gradient +uniform vec2 uGround; // groundNoise, cloudShadows +uniform vec4 uCel; // bands (0 = Lambert), softness, ambientAway, ambientEdge +uniform float uBandLevels[${CEL_MAX}]; +out vec4 outColor; + +const float PI = 3.14159265358979; +const vec3 NEAR_WARM = vec3(1.0, 0.82, 0.62); +const vec3 LUMA = vec3(0.2126, 0.7152, 0.0722); +const float WALL_RT2 = ${glsl(WALL_RT2)}; +${[0, 1, 2] + .map((i) => `const vec3 IN_R${i} = vec3(${ACES_IN[i].map(glsl).join(', ')});`) + .join('\n')} +${[0, 1, 2] + .map((i) => `const vec3 OUT_R${i} = vec3(${ACES_OUT[i].map(glsl).join(', ')});`) + .join('\n')} +const vec3 FIT_AB = vec3(${glsl(ACES_FIT[0])}, ${glsl(ACES_FIT[1])}, 0.0); +const vec3 FIT_CDE = vec3(${glsl(ACES_FIT[2])}, ${glsl(ACES_FIT[3])}, ${glsl(ACES_FIT[4])}); + +// toneMap.ts scotopic: toward the rods' luminance (Jensen et al. 2001) in a blue-shifted grey, at weight w. +float scotLum(vec3 c) { + float X = dot(vec3(0.4124, 0.3576, 0.1805), c); + float Y = dot(vec3(0.2126, 0.7152, 0.0722), c); + float Z = dot(vec3(0.0193, 0.1192, 0.9505), c); + return max(0.0, Y * (1.33 * (1.0 + (Y + Z) / max(X, 1e-30)) - 1.68)); +} +vec3 scotopic(vec3 c, float w) { + if (w <= 0.0) return c; + float k = scotLum(c) / scotLum(vec3(1.0)); + return mix(c, k * uScotTint, w); +} + +vec3 toLinear(vec3 c) { + return mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), step(vec3(0.04045), c)); +} +vec3 toSrgb(vec3 c) { + c = clamp(c, 0.0, 1.0); + return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(vec3(0.0031308), c)); +} +vec3 fit(vec3 v) { + return (v * (v + FIT_AB.x) - FIT_AB.y) / (v * (FIT_CDE.x * v + FIT_CDE.y) + FIT_CDE.z); +} +vec3 aces(vec3 x) { + vec3 p = fit(max(vec3(dot(IN_R0, x), dot(IN_R1, x), dot(IN_R2, x)), 0.0)); + return clamp(vec3(dot(OUT_R0, p), dot(OUT_R1, p), dot(OUT_R2, p)), 0.0, 1.0); +} + +// toneMap.ts applyCurve: the monotone cubic Hermite through the sky's five knots. +float curve1(float v) { + float x = clamp(v, 0.0, 1.0); + int k = 0; + for (int i = 1; i < ${KNOTS - 1}; i++) if (x > uCx[i]) k = i; + float h = uCx[k + 1] - uCx[k]; + float t = (x - uCx[k]) / h; + float t2 = t * t; + float t3 = t2 * t; + return (2.0 * t3 - 3.0 * t2 + 1.0) * uCy[k] + (t3 - 2.0 * t2 + t) * h * uCm[k] + + (-2.0 * t3 + 3.0 * t2) * uCy[k + 1] + (t3 - t2) * h * uCm[k + 1]; +} +vec3 curve(vec3 c) { return vec3(curve1(c.r), curve1(c.g), curve1(c.b)); } + +// lightCards.ts celShade: flat bands of n.s, edges at i / bands. +float cel(float x) { + int n = int(uCel.x); + float w = uCel.y * 0.5; + float l = uBandLevels[0]; + for (int i = 1; i < ${CEL_MAX}; i++) { + if (i >= n) break; + float e = float(i) / float(n); + l += (uBandLevels[i] - uBandLevels[i - 1]) * (w > 0.0 ? smoothstep(e - w, e + w, x) : step(e, x)); + } + return l; +} + +// The sky's table spans the ring: it wraps in azimuth (x) and clamps in elevation (y). +vec3 skyAt(vec2 uv) { + vec2 f = uv * vec2(uSkySize) - 0.5; + vec2 b = floor(f); + vec2 t = f - b; + int w = uSkySize.x; + ivec2 lo = ivec2((int(b.x) % w + w) % w, clamp(int(b.y), 0, uSkySize.y - 1)); + ivec2 hi = ivec2((int(b.x) + 1) % w, clamp(int(b.y) + 1, 0, uSkySize.y - 1)); + vec3 a = mix(texelFetch(uSky, ivec2(lo.x, lo.y), 0).rgb, texelFetch(uSky, ivec2(hi.x, lo.y), 0).rgb, t.x); + vec3 c = mix(texelFetch(uSky, ivec2(lo.x, hi.y), 0).rgb, texelFetch(uSky, ivec2(hi.x, hi.y), 0).rgb, t.x); + return mix(a, c, t.y); +} + +float hash2(vec2 p) { + p = fract(p * vec2(123.34, 456.21)); + p += dot(p, p + 45.32); + return fract(p.x * p.y); +} +float vnoise(vec2 p) { + vec2 i = floor(p); + vec2 f = fract(p); + f = f * f * (3.0 - 2.0 * f); + return mix(mix(hash2(i), hash2(i + vec2(1.0, 0.0)), f.x), mix(hash2(i + vec2(0.0, 1.0)), hash2(i + vec2(1.0, 1.0)), f.x), f.y); +} +float fbm(vec2 p) { + float a = 0.5; + float sum = 0.0; + for (int i = 0; i < 4; i++) { sum += a * vnoise(p); p *= 2.03; a *= 0.5; } + return sum / 0.9375; +} + +struct Geo { vec3 n; float logD; bool wall; }; +Geo geoAt(ivec2 p) { + vec4 g = texelFetch(uGeo, p, 0); + vec2 rt = g.rg * 2.0 - 1.0; + float rt2 = dot(rt, rt); + Geo o; + o.wall = rt2 > WALL_RT2; + o.logD = uLogD.x + g.b * uLogD.y; + o.n = o.wall ? vec3(0.0, 0.0, 1.0) : vec3(rt, sqrt(max(0.0, 1.0 - rt2))); + return o; +} + +void main() { + ivec2 p = ivec2(int(gl_FragCoord.x), uSize.y - 1 - int(gl_FragCoord.y)); + vec4 c = texelFetch(uColour, p, 0); + if (c.a <= 0.0) { outColor = vec4(0.0); return; } + Geo g = geoAt(p); + + int col = ((uCol0 + p.x) % uRingW + uRingW) % uRingW; + vec3 s = texelFetch(uSun, ivec2(col, 0), 0).xyz; + if (uRelief.y > 0.0) s = normalize(mix(s, uFixedLight, uRelief.y)); + float dist = exp(g.logD); + // The ground's noise is a function of the ground point, dist x (sin psi, cos psi) for the column's absolute azimuth psi, so it is periodic over the wrap. + float psi = (float(col) + 0.5) / float(uRingW) * 2.0 * PI; + vec2 world = vec2(sin(psi), cos(psi)) * dist; + vec3 albedo = toLinear(c.rgb); + if (uGround.x > 0.0) albedo *= max(1.0 + uGround.x * (2.0 * fbm(world / 250.0) - 1.0), 0.0); + float cloud = uGround.y > 0.0 ? 1.0 - uGround.y * smoothstep(0.5, 0.72, fbm(world / 4000.0 + 17.0)) : 1.0; + float lit = uCel.x > 0.5 ? cel(dot(g.n, s)) : max(dot(g.n, s), 0.0); + float ndl = mix(max(s.z, 0.0), lit, uRelief.x); + float ambStep = uCel.x > 0.5 ? mix(uCel.z, 1.0, smoothstep(uCel.w - uCel.y * 0.5, uCel.w + uCel.y * 0.5 + 1e-4, g.n.z)) : 1.0; + vec3 radiance = albedo * (uTSun * ndl * cloud + uAmbient * mix(1.0, ambStep, uRelief.x)) / PI; + float dn = clamp((g.logD - uLogD.x) / uLogD.y, 0.0, 1.0); + if (uDist.y != 0.0) { + vec3 flatTone = albedo * (uTSun * max(s.z, 0.0) * cloud + uAmbient) / PI; + radiance = flatTone + (radiance - flatTone) * exp(uDist.y * (1.0 - 2.0 * dn)); + } + radiance *= mix(vec3(1.0), NEAR_WARM, uDist.x * (1.0 - dn)); + vec3 T = exp(-uExt * (dist / 1000.0)); + vec2 uv = vec2((float(col) + 0.5) / float(uRingW), (float(uTop + p.y) + 0.5) / uPlaneH); + vec3 haze = skyAt(uv); + haze += uHazeTint * dot(haze, LUMA); + radiance = radiance * T + haze * (1.0 - T); + radiance *= max(uCard.x * (1.0 + uCard.y * ((float(p.y) + 0.5) / float(uSize.y) - 0.5)), 0.0); + + float keep = 1.0; + ivec2 dirs[4] = ivec2[4](ivec2(1, 0), ivec2(-1, 0), ivec2(0, 1), ivec2(0, -1)); + for (int k = 0; k < 4; k++) { + ivec2 q = p + dirs[k]; + if (q.x < 0 || q.y < 0 || q.x >= uSize.x || q.y >= uSize.y) continue; + float an = texelFetch(uColour, q, 0).a; + Geo gn = geoAt(q); + if (c.a >= 0.5 && an < 0.5) keep = min(keep, uInkKeep.x); + else if (an >= 0.5 && gn.logD - g.logD > uInkGeometry.x) keep = min(keep, uInkKeep.y); + else if (an >= 0.5 && !g.wall && !gn.wall && dot(g.n, gn.n) < uInkGeometry.y) keep = min(keep, uInkKeep.z); + } + radiance *= 1.0 - (1.0 - keep) * uInkScale; + + vec3 rgb = toSrgb(curve(aces(scotopic(radiance, uGrade) * uExposure))); + outColor = vec4(rgb * c.a, c.a); +} +`; + +const VERTEX = `#version 300 es +void main() { + vec2 p = vec2(float((gl_VertexID << 1) & 2), float(gl_VertexID & 2)); + gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0); +} +`; + +function compile(gl: WebGL2RenderingContext, type: number, source: string): WebGLShader { + const sh = gl.createShader(type); + if (!sh) throw new Error('ridge: no shader'); + gl.shaderSource(sh, source); + gl.compileShader(sh); + if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) + throw new Error(`ridge: shader did not compile: ${gl.getShaderInfoLog(sh) ?? ''}`); + return sh; +} + +function program(gl: WebGL2RenderingContext): WebGLProgram { + const p = gl.createProgram(); + if (!p) throw new Error('ridge: no program'); + gl.attachShader(p, compile(gl, gl.VERTEX_SHADER, VERTEX)); + gl.attachShader(p, compile(gl, gl.FRAGMENT_SHADER, FRAGMENT)); + gl.linkProgram(p); + if (!gl.getProgramParameter(p, gl.LINK_STATUS)) + throw new Error(`ridge: shader did not link: ${gl.getProgramInfoLog(p) ?? ''}`); + return p; +} + +function texture(gl: WebGL2RenderingContext, unit: number): WebGLTexture { + const t = gl.createTexture(); + if (!t) throw new Error('ridge: no texture'); + gl.activeTexture(gl.TEXTURE0 + unit); + gl.bindTexture(gl.TEXTURE_2D, t); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + return t; +} + +function floatTexture( + gl: WebGL2RenderingContext, + unit: number, + w: number, + h: number, + data: Float32Array +): WebGLTexture { + const t = texture(gl, unit); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, w, h, 0, gl.RGBA, gl.FLOAT, data); + return t; +} + +function bitmapTexture(gl: WebGL2RenderingContext, unit: number, bmp: ImageBitmap): WebGLTexture { + const t = texture(gl, unit); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, gl.RGBA, gl.UNSIGNED_BYTE, bmp); + return t; +} + +/** A tile of a card as its two files decoded: the colour with straight alpha and the geometry, each tileW + 2 apron columns by the band's rows. */ +export interface CardBitmaps { + colour: ImageBitmap; + geometry: ImageBitmap; +} + +/** One sky's lighting of the ring's tiles. */ +export interface Lighter { + /** + * Light card `card` of tile `tile` from its decoded files: a 2D canvas of the tile's interior columns plus one overlap column each side (the apron is + * read and dropped; the overlap hides the hairline between adjacent canvases at a fractional scale), premultiplied by the card's alpha. The bitmaps + * stay the caller's to close. Throws when the context is lost or the tile holds no such card. + */ + light(bitmaps: CardBitmaps, tile: number, card: number): HTMLCanvasElement; + /** True once the GL context was lost: this lighter is spent and the next ensure makes another. */ + readonly lost: boolean; + /** Let go of the GL context and its tables. */ + release(): void; +} + +/** + * The lighter for `sky`: one WebGL2 context on a canvas of its own, the program, the ring-wide sun columns and the sky's lookup uploaded once, a tile lit + * per call. Throws without WebGL2 or when the shader will not link; the caller (`Backdrop.ts`) turns any throw into the sky alone. + */ +export function createLighter( + manifest: RidgeManifest, + sky: PhysicalSky, + look: RidgeLook = DEFAULT_LOOK +): Lighter { + const glCanvas = document.createElement('canvas'); + const gl = glCanvas.getContext('webgl2', { + alpha: true, + premultipliedAlpha: true, + antialias: false, + depth: false, + stencil: false, + }); + if (!gl) throw new Error('ridge: no WebGL2'); + let lost = false; + let released = false; + const release = () => { + if (released) return; + released = true; + gl.getExtension('WEBGL_lose_context')?.loseContext(); + }; + glCanvas.addEventListener?.('webglcontextlost', () => { + lost = true; + }); + const { view } = manifest; + const litW = view.tileW + 2; + try { + const lit = lightingOf(manifest, sky, look); + const prog = program(gl); + gl.useProgram(prog); + const u = (name: string) => gl.getUniformLocation(prog, name); + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); + gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE); + gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); + ['uColour', 'uGeo', 'uSun', 'uSky'].forEach((n, i) => gl.uniform1i(u(n), i)); + gl.uniform1i(u('uRingW'), lit.ringW); + gl.uniform1f(u('uPlaneH'), lit.planeH); + gl.uniform2f(u('uLogD'), lit.logDMin, lit.logDSpan); + gl.uniform3f(u('uExt'), ...lit.extinction); + gl.uniform3f(u('uTSun'), ...lit.key.direct); + gl.uniform3f(u('uAmbient'), ...lit.key.ambient); + gl.uniform1f(u('uGrade'), lit.grade); + gl.uniform3f(u('uScotTint'), ...SCOTOPIC.tint); + gl.uniform1f(u('uExposure'), lit.exposure); + gl.uniform1fv(u('uCx'), lit.curve.x); + gl.uniform1fv(u('uCy'), lit.curve.y); + gl.uniform1fv(u('uCm'), lit.curve.m); + gl.uniform2f(u('uInkGeometry'), look.occludeLogD, look.creaseCos); + gl.uniform3f(u('uInkKeep'), look.inkKeep.edge, look.inkKeep.occlude, look.inkKeep.crease); + gl.uniform1f(u('uInkScale'), look.inkScale); + gl.uniform2f(u('uRelief'), look.reliefWeight, look.reliefLight.mix); + const fl = look.reliefLight; + gl.uniform3f( + u('uFixedLight'), + Math.cos(fl.elevationDeg * RAD) * Math.cos(fl.azimuthDeg * RAD), + Math.cos(fl.elevationDeg * RAD) * Math.sin(fl.azimuthDeg * RAD), + Math.sin(fl.elevationDeg * RAD) + ); + gl.uniform3f(u('uHazeTint'), ...look.hazeTint); + gl.uniform2f(u('uDist'), look.nearWarm, look.contrastByDistance); + gl.uniform2f(u('uGround'), look.groundNoise, look.cloudShadows); + gl.uniform4f(u('uCel'), look.celBands, look.celSoftness, look.celAmbientAway, look.celAmbientEdge); + gl.uniform1fv(u('uBandLevels'), celLevels(look.celBands, look.celBandLevels)); + gl.uniform2i(u('uSkySize'), SKY_LUT.w, SKY_LUT.h); + floatTexture(gl, 2, lit.ringW, 1, sunColumns(view, lit.key)); + floatTexture(gl, 3, SKY_LUT.w, SKY_LUT.h, skyLut(sky, view, SKY_LUT.w, SKY_LUT.h)); + return { + get lost() { + return lost; + }, + release, + light(bitmaps, tile, card) { + const entry = manifest.tiles[tile]?.[card]; + if (!entry) throw new Error(`ridge: tile ${tile} holds no card ${card}`); + if (lost || released) throw new Error('ridge: the lighting context is gone'); + const { colour, geometry } = bitmaps; + glCanvas.width = colour.width; + glCanvas.height = colour.height; + gl.viewport(0, 0, colour.width, colour.height); + const colourTex = bitmapTexture(gl, 0, colour); + const geoTex = bitmapTexture(gl, 1, geometry); + gl.uniform2i(u('uSize'), colour.width, colour.height); + gl.uniform1i(u('uTop'), entry.top); + gl.uniform1i(u('uCol0'), tile * view.tileW - view.apron); + gl.uniform2f( + u('uCard'), + 1 + look.cardToneStep * (card - (manifest.cards.length - 1) / 2), + look.cardGradient + ); + gl.clearColor(0, 0, 0, 0); + gl.clear(gl.COLOR_BUFFER_BIT); + gl.drawArrays(gl.TRIANGLES, 0, 3); + const canvas = document.createElement('canvas'); + canvas.width = litW; + canvas.height = colour.height; + const ctx = canvas.getContext('2d'); + if (!ctx) throw new Error('ridge: no 2D context for a lit tile'); + // The file's columns apron - 1 .. apron + tileW (inclusive): the interior and one overlap column each side. + ctx.drawImage(glCanvas, view.apron - 1, 0, litW, colour.height, 0, 0, litW, colour.height); + gl.deleteTexture(colourTex); + gl.deleteTexture(geoTex); + return canvas; + }, + }; + } catch (e) { + release(); + throw e; + } +} diff --git a/src/app/features/scene/ridge/manifest.fixture.ts b/src/app/features/scene/ridge/manifest.fixture.ts new file mode 100644 index 00000000..673b1bd3 --- /dev/null +++ b/src/app/features/scene/ridge/manifest.fixture.ts @@ -0,0 +1,93 @@ +// A hand-written manifest schema 3 and index v1 (wire form, as export.py writes them): the runtime's tests need no real bake and no decoder. The ring is +// four tiles of 90 degrees, so a tile is a quarter of the compass and wrap-around at north is easy to meet. +import type { View } from './view'; + +/** A card's distance in each of the fixture's four tiles, metres, nearest card first; null where the tile holds no such card (the third card is absent over the south). */ +export const DISTANCES: (number | null)[][] = [ + [1000, 1200, 1400, 1100], + [10000, 12000, 14000, 11000], + [40000, 41000, null, 39000], +]; + +/** A schema 3 manifest of `k` cards (1 to 3, nearest first), each a band of the 600-row plane, over `tiles` tiles (4 by default, 32 as the baker cuts) whose distances repeat the four above. */ +export const wireManifest = ( + over: Record = {}, + k = 3, + tiles = 4 +): Record => ({ + schema: 3, + baker_version: 4, + bake_id: 'abc123abc123', + place: { + id: 'vienna', + name: 'Vienna', + lat: 48.19, + lon: 16.35, + altitude_km: 0.183, + tz: 'Europe/Vienna', + eye_m: 1.7, + }, + view: { + look_az_deg: 214, + plane_h: 600, + px_per_deg_h: 6400 / 360, + px_per_deg_v: 171.7, + exaggeration: 10, + horizon_row: 357, + sky_row: 24, + near_row: 396, + ring_w: 6400, + tile_w: 6400 / tiles, + tiles, + apron: 2, + }, + curvature: { r_earth_m: 6371000, k_ref: 0.13 }, + encoding: { log_d_min: 4.6, log_d_max: 11.5, normal: 'rt8' }, + camera: { r_max_m: 100, r_max_forward_m: 180 }, + cards: Array.from({ length: k }, (_, i) => ({ + near_m: i ? 1000 * 10 ** (i - 1) * 4 : null, + far_m: i < k - 1 ? 4000 * 10 ** i : null, + })), + tiles: Array.from({ length: tiles }, (_, t) => + Array.from({ length: k }, (_, i) => { + const d = DISTANCES[i][t % 4]; + return d === null + ? null + : { + top: 100 * i, + h: 600 - 100 * i, + distance_m: d, + colour: { file: `card-${i}-t${String(t).padStart(2, '0')}-colour.webp`, bytes: 1 }, + geometry: { file: `card-${i}-t${String(t).padStart(2, '0')}-geometry.webp`, bytes: 1 }, + }; + }) + ), + bytes: 0, + attribution: { + credit_line: 'credit', + licence: 'licence', + dem_source: 'dem', + url: 'https://example.test', + }, + ...over, +}); + +export const wireIndex = { + schema: 1, + default: 'vienna', + places: { vienna: 'vienna-abc123abc123', graz: 'graz-def456def456' }, +}; + +/** A View that differs from FALLBACK_VIEW in every field the sky reads (place, altitude, look azimuth, horizon row), so a test can tell the two apart. */ +export const ELSEWHERE_VIEW: View = { + place: { id: 'elsewhere', lat: -33.9, lon: 151.2, altitudeKm: 1.5, tz: 'Australia/Sydney' }, + lookAzDeg: 20, + ringW: 3600, + tileW: 900, + tiles: 4, + apron: 2, + planeH: 700, + pxPerDegH: 10, + pxPerDegV: 100, + horizonRow: 250, +}; diff --git a/src/app/features/scene/ridge/manifest.test.ts b/src/app/features/scene/ridge/manifest.test.ts new file mode 100644 index 00000000..de49fe37 --- /dev/null +++ b/src/app/features/scene/ridge/manifest.test.ts @@ -0,0 +1,195 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { forgetManifests, loadManifest, parseManifest } from './manifest'; +import { wireIndex, wireManifest } from './manifest.fixture'; + +describe('parseManifest', () => { + it('reads a schema 3 manifest into the View the sky and cards share, the offset bound, and the cards by tile', () => { + const m = parseManifest(wireManifest(), '/public/ridge/v/'); + expect(m.dir).toBe('/public/ridge/v/'); + expect(m.view).toMatchObject({ + lookAzDeg: 214, + ringW: 6400, + tileW: 1600, + tiles: 4, + apron: 2, + planeH: 600, + pxPerDegH: 6400 / 360, + pxPerDegV: 171.7, // not px_per_deg_h: a real bake's two differ 10x + horizonRow: 357, + }); + 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.camera).toEqual({ rMaxM: 100, rMaxForwardM: 180 }); + expect(m.cards).toEqual([ + { nearM: null, farM: 4000 }, + { nearM: 4000, farM: 40000 }, + { nearM: 40000, farM: null }, + ]); + expect(m.tiles).toHaveLength(4); + expect(m.tiles[1][1]).toEqual({ + top: 100, + h: 500, + distanceM: 12000, + colour: 'card-1-t01-colour.webp', + geometry: 'card-1-t01-geometry.webp', + }); + expect(m.tiles[2][2]).toBeNull(); // the third card holds nothing over the south + expect(m.attribution.creditLine).toBe('credit'); + }); + + it.each([1, 2, 3])('parses a bake of %i cards', (k) => { + const m = parseManifest(wireManifest({}, k), '/'); + expect(m.cards).toHaveLength(k); + m.tiles.forEach((row) => expect(row).toHaveLength(k)); + }); + + it('refuses schema 2 naming the stale deploy, and any other schema', () => { + const w = wireManifest() as any; + expect(() => parseManifest({ ...w, schema: 2 }, '/')).toThrow(/stale ridge bake/); + expect(() => parseManifest({ ...w, schema: 1 }, '/')).toThrow(/schema/); + }); + + it('refuses no cards, seven cards, a ring that is not tiles x tile_w, a tile row of the wrong length, a card in no tile, a band past the plane', () => { + const w = wireManifest() as any; + expect(() => parseManifest({ ...w, cards: [] }, '/')).toThrow(/cards/); + expect(() => parseManifest({ ...w, cards: Array(7).fill({ near_m: null, far_m: null }) }, '/')).toThrow(/cards/); + expect(() => parseManifest({ ...w, view: { ...w.view, ring_w: 6401 } }, '/')).toThrow(/ring_w/); + expect(() => parseManifest({ ...w, tiles: w.tiles.slice(1) }, '/')).toThrow(/tiles/); + expect(() => parseManifest({ ...w, tiles: w.tiles.map((r: unknown[]) => r.slice(1)) }, '/')).toThrow(/entries/); + expect(() => + parseManifest({ ...w, tiles: w.tiles.map((r: unknown[]) => [r[0], r[1], null]) }, '/') + ).toThrow(/null in every tile/); + const withTile = (e: unknown) => ({ ...w, tiles: [[e, w.tiles[0][1], w.tiles[0][2]], ...w.tiles.slice(1)] }); + const t = w.tiles[0][0]; + expect(() => parseManifest(withTile({ ...t, top: 300, h: 301 }), '/')).toThrow(/rows/); + expect(() => parseManifest(withTile({ ...t, top: -1 }), '/')).toThrow(/rows/); + expect(() => parseManifest(withTile({ ...t, distance_m: 0 }), '/')).toThrow(/distance/); + expect(() => parseManifest(withTile({ ...t, distance_m: Infinity }), '/')).toThrow(/distance/); + expect(() => parseManifest({ ...w, camera: undefined }, '/')).toThrow(/camera/); + expect(() => parseManifest({ ...w, camera: { r_max_m: 0, r_max_forward_m: 0 } }, '/')).toThrow(/r_max_m/); + expect(() => parseManifest({ ...w, camera: { r_max_m: 100 } }, '/')).toThrow(/r_max_forward_m/); + expect(() => parseManifest({ ...w, camera: { r_max_m: 100, r_max_forward_m: 99 } }, '/')).toThrow(/r_max_forward_m/); + }); + + it('rejects a missing field, a normal that is not rt8 and a backwards encoding', () => { + const w = wireManifest() as any; + expect(() => parseManifest({ ...w, bake_id: undefined }, '/')).toThrow(/bake_id/); + expect(() => parseManifest({ ...w, view: { ...w.view, horizon_row: 'x' } }, '/')).toThrow( + /horizon_row/ + ); + expect(() => parseManifest({ ...w, encoding: { ...w.encoding, normal: 'oct' } }, '/')).toThrow( + /normal/ + ); + expect(() => + parseManifest({ ...w, encoding: { ...w.encoding, log_d_max: w.encoding.log_d_min } }, '/') + ).toThrow(/encoding/); + 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('refuses a plane that leaves fewer rows under the horizon than the runtime needs to reach the viewport bottom, and takes exactly that many', () => { + const w = wireManifest() as any; + const at = (row: number) => ({ ...w, view: { ...w.view, horizon_row: row } }); + expect(() => parseManifest(at(451), '/')).toThrow(/short plane.*150/); + expect(parseManifest(at(450), '/').view.horizonRow).toBe(450); + expect(parseManifest(at(357), '/').view.horizonRow).toBe(357); + }); + + it('never echoes a value it refused', () => { + const w = wireManifest() as any; + const refusal = (bad: unknown) => { + try { + parseManifest(bad, '/'); + } catch (e) { + return String(e); + } + return ''; + }; + for (const bad of [ + { ...w, schema: 'SECRET-VALUE-42' }, + { ...w, camera: { r_max_m: 'SECRET-VALUE-42', r_max_forward_m: 180 } }, + { ...w, camera: { r_max_m: 100, r_max_forward_m: 'SECRET-VALUE-42' } }, + { ...w, tiles: [[{ ...w.tiles[0][0], distance_m: 'SECRET-VALUE-42' }, ...w.tiles[0].slice(1)], ...w.tiles.slice(1)] }, + ]) { + const msg = refusal(bad); + expect(msg).not.toBe(''); + expect(msg).not.toContain('SECRET-VALUE-42'); + } + }); +}); + +const serve = (files: Record) => { + const f = vi.fn(async (url: string) => + url in files + ? { ok: true, status: 200, json: async () => files[url] } + : { ok: false, status: 404, json: async () => ({}) } + ); + vi.stubGlobal('fetch', f); + return f; +}; +const files = () => ({ + '/b/public/ridge/index.json': wireIndex, + '/b/public/ridge/vienna-abc123abc123/manifest.json': wireManifest(), + '/b/public/ridge/graz-def456def456/manifest.json': wireManifest({ + place: { ...(wireManifest() as any).place, id: 'graz', name: 'Graz' }, + }), +}); + +describe('loadManifest', () => { + afterEach(() => { + forgetManifests(); + vi.unstubAllGlobals(); + }); + + it('reads the index then the default place, with its directory', async () => { + const f = serve(files()); + const m = await loadManifest('/b/'); + expect(m.view.place.id).toBe('vienna'); + expect(m.dir).toBe('/b/public/ridge/vienna-abc123abc123/'); + expect(f.mock.calls.map((c) => c[0])).toEqual([ + '/b/public/ridge/index.json', + '/b/public/ridge/vienna-abc123abc123/manifest.json', + ]); + }); + + it('revalidates the index, the one mutable pointer, and leaves the content-addressed manifest to the cache', async () => { + const f = serve(files()); + await loadManifest('/b/'); + expect(f.mock.calls).toEqual([ + ['/b/public/ridge/index.json', { cache: 'no-cache' }], + ['/b/public/ridge/vienna-abc123abc123/manifest.json', undefined], + ]); + }); + + it('place picks the index entry; an unknown id falls back to the default', async () => { + serve(files()); + expect((await loadManifest('/b/', 'graz')).view.place.id).toBe('graz'); + expect((await loadManifest('/b/', 'nowhere')).view.place.id).toBe('vienna'); + }); + + it('is memoised per URL and place', async () => { + const f = serve(files()); + await loadManifest('/b/'); + await loadManifest('/b/'); + expect(f).toHaveBeenCalledTimes(2); + }); + + it('rejects on a 404 and does not remember the failure', async () => { + serve({}); + await expect(loadManifest('/b/')).rejects.toThrow(/404/); + serve(files()); + await expect(loadManifest('/b/')).resolves.toBeTruthy(); + }); +}); diff --git a/src/app/features/scene/ridge/manifest.ts b/src/app/features/scene/ridge/manifest.ts new file mode 100644 index 00000000..49fd26db --- /dev/null +++ b/src/app/features/scene/ridge/manifest.ts @@ -0,0 +1,272 @@ +// The ridge backdrop's one JSON boundary: a static asset between the offline Python baker (scripts/ridge-bake/export.py, whose SCHEMA is the +// contract) and the page; no daemon state. Main-chunk safe: types, a parser and fetch only. Wire names are snake_case; the parsed manifest is +// camelCase and its `view` is the View (`view.ts`) the sky and the cards share. Schema 3: the whole 360 degree ring, K G-buffer cards cut into +// azimuth tiles, each tile two files. +import { groundRowsNeeded, type Place, type View } from './view'; + +/** As export.py MAX_CARDS: the decode budget holds this many. */ +export const MAX_CARDS = 6; + +/** One card's tile: its rows of the plane, the card's distance there, and its two files (names inside the manifest's directory). */ +export interface TileCard { + /** First row of the card's band in the plane, and its height in rows. */ + top: number; + h: number; + /** exp(median ln d) of the card's solid pixels in the tile's interior, metres. */ + distanceM: number; + colour: string; + geometry: string; +} + +/** A card as the bake lists it: the median seam depths over the ring, null at the ends. */ +export interface CardEntry { + nearM: number | null; + farM: number | null; +} + +export interface RidgeManifest { + bakeId: string; + /** Absolute-or-rooted URL of the bake's directory, with a trailing slash. */ + dir: string; + /** Display name of the place. */ + name: string; + view: View; + /** How the geometry file's blue channel maps to ln metres: `logD = logDMin + b x (logDMax - logDMin)`, b in 0..1. The red and green channels are the 'rt8' normal. */ + encoding: { logDMin: number; logDMax: number }; + /** + * The largest camera offset from the bake centre the cards' linear slide fits, metres (ruling ridge-offset-range-fit): `rMaxM` over every angle of the camera + * on its circle (the offset-only rotation mode), `rMaxForwardM` with the camera pushed forward along the view direction alone (the modes where the offset + * turns with the view), so never below `rMaxM`. + */ + camera: { rMaxM: number; rMaxForwardM: number }; + /** Nearest first. */ + cards: CardEntry[]; + /** `tiles[t][i]` is card i in tile t, or null where the card holds nothing there. */ + tiles: (TileCard | null)[][]; + attribution: { creditLine: string; licence: string; demSource: string; url: string }; +} + +export interface RidgeIndex { + default: string; + places: Record; +} + +type Rec = Record; +const fail = (path: string, why: string): never => { + throw new Error(`ridge manifest ${path}: ${why}`); +}; +const rec = (x: unknown, path: string): Rec => + typeof x === 'object' && x !== null && !Array.isArray(x) + ? (x as Rec) + : fail(path, 'not an object'); +const num = (x: unknown, path: string): number => + typeof x === 'number' && Number.isFinite(x) ? x : fail(path, 'not a number'); +const str = (x: unknown, path: string): string => + typeof x === 'string' ? x : fail(path, 'not a string'); +const numOrNull = (x: unknown, path: string): number | null => (x === null ? null : num(x, path)); + +/** 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 { + const r = rec(raw, 'index'); + if (r.schema !== 1) fail('index.schema', 'must be 1'); + const places = rec(r.places, 'index.places'); + const out = Object.fromEntries( + Object.entries(places).map(([k, v]) => [k, str(v, `index.places.${k}`)]) + ); + return { default: str(r.default, 'index.default'), places: out }; +} + +/** `dir` is the URL of the directory the manifest was read from; the tile files are read relative to it. */ +export function parseManifest(raw: unknown, dir: string): RidgeManifest { + const r = rec(raw, 'manifest'); + if (r.schema !== 3) { + fail( + 'schema', + `must be 3: this build reads ring bakes only, so the deploy holds a stale ridge bake (rebake the place, or redeploy a matching build)` + ); + } + const p = rec(r.place, 'place'); + const v = rec(r.view, 'view'); + const ringW = num(v.ring_w, 'view.ring_w'); + const tileW = num(v.tile_w, 'view.tile_w'); + const tiles = num(v.tiles, 'view.tiles'); + if (!Number.isInteger(tiles) || tiles < 1) fail('view.tiles', 'not a count'); + if (ringW !== tiles * tileW) fail('view.ring_w', 'is not tiles x tile_w'); + const planeH = num(v.plane_h, 'view.plane_h'); + const horizonRow = num(v.horizon_row, 'view.horizon_row'); + const ground = groundRowsNeeded(planeH); + if (planeH - horizonRow < ground - 1e-6) { + fail( + 'view.horizon_row', + `short plane: ${(planeH - horizonRow).toFixed(1)} rows under the horizon, the runtime needs ${Math.round(ground)} to reach the viewport bottom (the baker refuses such a bake: rebake the place)` + ); + } + if (!Array.isArray(r.cards) || r.cards.length < 1) fail('cards', 'none'); + const k = (r.cards as unknown[]).length; + if (k > MAX_CARDS) fail('cards', `more than ${MAX_CARDS}`); + const cards = (r.cards as unknown[]).map((x, i): CardEntry => { + const c = rec(x, `cards[${i}]`); + return { + nearM: numOrNull(c.near_m, `cards[${i}].near_m`), + farM: numOrNull(c.far_m, `cards[${i}].far_m`), + }; + }); + if (!Array.isArray(r.tiles) || r.tiles.length !== tiles) fail('tiles', `not ${tiles} tiles`); + const grid = (r.tiles as unknown[]).map((row, t) => { + if (!Array.isArray(row) || row.length !== k) fail(`tiles[${t}]`, `not ${k} entries`); + return (row as unknown[]).map((x, i): TileCard | null => { + if (x === null) return null; + const path = `tiles[${t}][${i}]`; + const e = rec(x, path); + const top = num(e.top, `${path}.top`); + const h = num(e.h, `${path}.h`); + if (top < 0 || h < 1 || top + h > planeH) fail(path, 'outside the plane rows'); + const distanceM = num(e.distance_m, `${path}.distance_m`); + if (!(distanceM > 0)) fail(`${path}.distance_m`, 'not above 0'); + return { + top, + h, + distanceM, + colour: str(rec(e.colour, `${path}.colour`).file, `${path}.colour.file`), + geometry: str(rec(e.geometry, `${path}.geometry`).file, `${path}.geometry.file`), + }; + }); + }); + for (let i = 0; i < k; i += 1) { + if (grid.every((row) => row[i] === null)) fail(`cards[${i}]`, 'is null in every tile'); + } + const e = rec(r.encoding, 'encoding'); + if (e.normal !== 'rt8') fail('encoding.normal', "must be 'rt8'"); + const logDMin = num(e.log_d_min, 'encoding.log_d_min'); + const logDMax = num(e.log_d_max, 'encoding.log_d_max'); + if (!(logDMax > logDMin)) fail('encoding', 'log_d_max not above log_d_min'); + const cam = rec(r.camera, 'camera'); + const rMaxM = num(cam.r_max_m, 'camera.r_max_m'); + if (!(rMaxM > 0)) fail('camera.r_max_m', 'not above 0'); + const rMaxForwardM = num(cam.r_max_forward_m, 'camera.r_max_forward_m'); + if (!(rMaxForwardM >= rMaxM)) fail('camera.r_max_forward_m', 'below camera.r_max_m'); + const a = rec(r.attribution, 'attribution'); + const id = str(p.id, 'place.id'); + return { + bakeId: str(r.bake_id, 'bake_id'), + dir, + name: str(p.name, 'place.name'), + view: { + place: { + id, + lat: num(p.lat, 'place.lat'), + lon: num(p.lon, 'place.lon'), + altitudeKm: num(p.altitude_km, 'place.altitude_km'), + tz: zone(p.tz, 'place.tz'), + }, + lookAzDeg: num(v.look_az_deg, 'view.look_az_deg'), + ringW, + tileW, + tiles, + apron: num(v.apron, 'view.apron'), + planeH, + pxPerDegH: num(v.px_per_deg_h, 'view.px_per_deg_h'), + pxPerDegV: num(v.px_per_deg_v, 'view.px_per_deg_v'), + horizonRow, + }, + encoding: { logDMin, logDMax }, + camera: { rMaxM, rMaxForwardM }, + cards, + tiles: grid, + attribution: { + creditLine: str(a.credit_line, 'attribution.credit_line'), + licence: str(a.licence, 'attribution.licence'), + demSource: str(a.dem_source, 'attribution.dem_source'), + url: str(a.url, 'attribution.url'), + }, + }; +} + +async function getJson(url: string, init?: RequestInit): Promise { + const res = await fetch(url, init); + if (!res.ok) throw new Error(`ridge: ${url} answered ${res.status}`); + return res.json(); +} + +/** A baked place as the Place submenu lists it: the manifest's own name and place (its card reads the moment drawn there, in its zone). */ +export interface PlaceListing { + id: string; + name: string; + place: Place; +} + +const memo = new Map>(); +const indexMemo = new Map>(); +const listMemo = new Map>(); + +/** The baked places' index (`${baseUrl}public/ridge/index.json`), memoised per URL; a failure is not remembered. */ +export function loadIndex(baseUrl: string): Promise { + const root = `${baseUrl}public/ridge/`; + const hit = indexMemo.get(root); + if (hit) return hit; + // The index is the one mutable pointer (a rebake deletes the old directory it named); the manifest and tiles are content-addressed. + const p = getJson(`${root}index.json`, { cache: 'no-cache' }).then(parseIndex); + indexMemo.set(root, p); + p.catch(() => indexMemo.delete(root)); + return p; +} + +/** + * The manifest of a baked place: the index names each place's directory, then `/manifest.json` is read. + * `placeId` picks the entry (unknown or absent: the index's default). Memoised per index URL and place; a failure is not remembered. + * Rejects on any failure: the caller degrades to the sky-only scene. + */ +export function loadManifest(baseUrl: string, placeId?: string): Promise { + const root = `${baseUrl}public/ridge/`; + const key = `${root}|${placeId ?? ''}`; + const hit = memo.get(key); + if (hit) return hit; + const p = (async () => { + const index = await loadIndex(baseUrl); + const id = placeId !== undefined && placeId in index.places ? placeId : index.default; + const name = index.places[id]; + if (name === undefined) throw new Error(`ridge: index has no place ${id}`); + const dir = `${root}${name}/`; + return parseManifest(await getJson(`${dir}manifest.json`), dir); + })(); + memo.set(key, p); + p.catch(() => memo.delete(key)); + return p; +} + +/** The baked places in the index's order, named by their manifests; a place whose manifest fails to load is left out. Memoised per index URL; a failure is not remembered. */ +export function listPlaces(baseUrl: string): Promise { + const root = `${baseUrl}public/ridge/`; + const hit = listMemo.get(root); + if (hit) return hit; + const p = (async () => { + const index = await loadIndex(baseUrl); + const found = await Promise.allSettled( + Object.keys(index.places).map(async (id): Promise => { + const m = await loadManifest(baseUrl, id); + return { id, name: m.name, place: m.view.place }; + }) + ); + return found.flatMap((f) => (f.status === 'fulfilled' ? [f.value] : [])); + })(); + listMemo.set(root, p); + p.catch(() => listMemo.delete(root)); + return p; +} + +/** For tests: forget every memoised manifest. */ +export const forgetManifests = (): void => { + memo.clear(); + indexMemo.clear(); + listMemo.clear(); +}; diff --git a/src/app/features/scene/ridge/nightBodies.test.ts b/src/app/features/scene/ridge/nightBodies.test.ts new file mode 100644 index 00000000..c0c2ac50 --- /dev/null +++ b/src/app/features/scene/ridge/nightBodies.test.ts @@ -0,0 +1,155 @@ +import { describe, expect, it } from 'vitest'; +import { limbAngle, nightBodies, onScreen, paintNightBodies } from './nightBodies'; +import { makePhysicalSky, paintSky } from './physicalSky'; +import { sunAt } from './sunAt'; +import { FALLBACK_VIEW } from './view'; +import type { Camera } from './view'; +import { MAG_LIMIT, starsAt } from './starCatalogue'; +import { moonAt } from './nightSky'; + +const P = FALLBACK_VIEW.place; +// A camera that sees most of the sky, so the moon of any hour is in it (the app's own window looks 72 degrees wide over the south-west). +const camera: Camera = { azimuthDeg: 180, hfovDeg: 340, vfovDeg: 170, horizonAt: 0.92 }; + +const sky = (iso: string, state: 'day' | 'dusk' | 'night' = 'night') => { + const t = new Date(iso); + return makePhysicalSky(sunAt(P, t), 0, FALLBACK_VIEW); +}; +const bodies = (iso: string, state: 'day' | 'dusk' | 'night' = 'night', lines = false) => { + const p = sky(iso, state); + return { p, nb: nightBodies(p, paintSky(p, 640, 360, camera), lines) }; +}; + +// 2026-11-24 22:00 UTC: full moon high in the south over Vienna. 2026-12-09 20:00 UTC: new moon. 2026-12-04 00:00 UTC: no moon up. +const FULL = '2026-11-24T22:00:00Z'; +const NEW = '2026-12-09T20:00:00Z'; +const MOONLESS = '2026-12-04T00:00:00Z'; + +describe('the stars of a night sky', () => { + it('are the catalogue stars of the sky\'s own moment inside the camera, brightest drawn largest', () => { + const { nb } = bodies(MOONLESS); + expect(nb.stars.length).toBeGreaterThan(300); + const inView = starsAt(new Date(MOONLESS), P.lat, P.lon, MAG_LIMIT, -0.5).filter((s) => { + const a = onScreen(camera, s.azimuth, s.elevation); + return a.x > -0.02 && a.x < 1.02 && a.y > -0.02 && a.y < 1.02; + }); + expect(nb.stars.length).toBeLessThanOrEqual(inView.length); + const radii = nb.stars.map((s) => s.r); + expect(Math.max(...radii)).toBeGreaterThan(1.2 * Math.min(...radii)); + }); + + it('are hidden by the twilight that exposes the sky: none at dusk, none by day, more on a moonless night than a full-moon one', () => { + expect(bodies('2026-06-21T10:40:00Z', 'day').nb.stars).toHaveLength(0); + expect(bodies('2026-12-04T15:20:00Z', 'dusk').nb.stars.length).toBeLessThan(5); + expect(bodies(MOONLESS).nb.stars.length).toBeGreaterThan(bodies(FULL).nb.stars.length); + }); + + it('move with the clock: three hours later the field is a different one, rotated by 45 degrees about the pole', () => { + const a = bodies('2026-12-04T00:00:00Z').nb.stars.slice(0, 20).map((s) => s.x.toFixed(3)).join(); + const b = bodies('2026-12-04T03:00:00Z').nb.stars.slice(0, 20).map((s) => s.x.toFixed(3)).join(); + expect(a).not.toBe(b); + }); + + it('twinkle by flux: a star dimmed by its gain is closer to the sky behind it, brightened is lighter, base is its fill', () => { + const { nb } = bodies(MOONLESS); + const s = nb.stars[0]; + const lum = (c: string) => c.match(/\d+/g)!.map(Number).reduce((a, b) => a + b, 0); + expect(s.shade(1)).toBe(s.fill); + expect(lum(s.shade(0.35))).toBeLessThanOrEqual(lum(s.fill)); + expect(lum(s.shade(1.15))).toBeGreaterThanOrEqual(lum(s.fill)); + expect(lum(s.cover)).toBeLessThan(lum(s.fill)); + }); +}); + +describe('the moon of a night sky', () => { + it('is drawn where the ephemeris puts it, with the real phase', () => { + const { p, nb } = bodies(FULL); + expect(nb.moon).toBeDefined(); + expect(nb.moon!.illuminated).toBeGreaterThan(0.99); + const at = onScreen(camera, p.moon.azimuth, p.moon.elevation); + expect(nb.moon!.x).toBeCloseTo(at.x, 9); + expect(nb.moon!.y).toBeCloseTo(at.y, 9); + // 0.52 degrees across, vertical field of view a few tens of degrees + expect(nb.moon!.radius * camera.vfovDeg).toBeCloseTo((p.moon.radius * 180) / Math.PI, 6); + }); + + it('is a thin sliver near new moon and not drawn when it is below the horizon', () => { + expect(moonAt(P, new Date(NEW)).illuminated).toBeLessThan(0.05); + expect(bodies(MOONLESS).nb.moon).toBeUndefined(); + }); + + it('points its bright limb at the sun: down and toward the sun at moonrise after sunset, up at moonset in the morning', () => { + // A moon due south at 30 degrees with the sun at the horizon due west: the limb leans to the right (east is left on screen looking south, west right). + const a = limbAngle({ azimuth: 180, elevation: 30 }, { azimuth: 270, elevation: 0 }); + expect(Math.cos(a)).toBeGreaterThan(0.5); + expect(Math.sin(a)).toBeLessThan(0); + // Sun straight below the moon: the limb points down the screen. + expect(Math.sin(limbAngle({ azimuth: 180, elevation: 30 }, { azimuth: 180, elevation: -30 }))).toBeLessThan(-0.99); + }); + + it('is lighter than the sky around it, and its dark side lighter than the sky', () => { + const { nb } = bodies(FULL); + const lum = (c: string) => c.match(/\d+/g)!.map(Number).reduce((a, b) => a + b, 0); + expect(lum(nb.moon!.lit)).toBeGreaterThan(lum(nb.moon!.dark)); + expect(lum(nb.moon!.lit)).toBeGreaterThan(450); + }); +}); + +describe('the constellation lines', () => { + it('are absent unless asked for, and present for a night sky when they are', () => { + expect(bodies(MOONLESS, 'night', false).nb.lines).toHaveLength(0); + const on = bodies(MOONLESS, 'night', true).nb.lines; + expect(on.length).toBeGreaterThan(20); + expect(on.every((l) => l.points.length > 1)).toBe(true); + }); + + it('are not drawn in a day or dusk sky even when asked for', () => { + expect(bodies('2026-06-21T10:40:00Z', 'day', true).nb.lines).toHaveLength(0); + expect(bodies('2026-12-04T15:20:00Z', 'dusk', true).nb.lines).toHaveLength(0); + }); +}); + +describe('painting', () => { + it('draws lines, stars and the moon in that order and builds the terminator from an ellipse', () => { + const calls: string[] = []; + const ctx = new Proxy( + {}, + { + get: (_t, k) => (k === 'save' ? () => 0 : () => calls.push(String(k))), + set: () => true, + } + ) as unknown as CanvasRenderingContext2D; + const { nb } = bodies(FULL, 'night', true); + paintNightBodies(ctx, nb, 1280, 720, 2); + expect(calls.indexOf('stroke')).toBeGreaterThanOrEqual(0); + expect(calls.indexOf('stroke')).toBeLessThan(calls.indexOf('arc')); + expect(calls).toContain('ellipse'); + expect(calls.filter((c) => c === 'arc').length).toBeGreaterThanOrEqual(nb.stars.length + 2); + }); +}); + +describe('the stars under the figures', () => { + it('carry every constellation-line vertex in the sky strip that the moon does not cover, even under a full moon, at the app framing', async () => { + const { windowFor } = await import('./view'); + const { linesAt } = await import('./starCatalogue'); + const cam = windowFor(FALLBACK_VIEW, 1100, 619).camera; + const t = new Date('2026-11-25T00:00:00Z'); // full moon, high in the south + const p = makePhysicalSky(sunAt(P, t), 0, FALLBACK_VIEW); + const nb = nightBodies(p, paintSky(p, 1100, 619, cam), false); + let vertices = 0; + let carried = 0; + linesAt(t, P.lat, P.lon).forEach((chain) => + chain.forEach((q) => { + const a = onScreen(cam, q.azimuth, q.elevation); + if (a.x < 0 || a.x > 1 || a.y < 0 || a.y > 0.8) return; + // The moon is drawn over the stars, and a star inside its disc is not placed. + if (nb.moon && Math.hypot((nb.moon.x - a.x) * 1100, (nb.moon.y - a.y) * 619) < Math.max(2, nb.moon.radius * 619)) return; + vertices += 1; + // Placement only: a catalogue star is drawn within a few px of the vertex. How bright it is is the look's. + if (nb.stars.some((s) => Math.hypot((s.x - a.x) * 1100, (s.y - a.y) * 619) < 4)) carried += 1; + }) + ); + expect(vertices).toBeGreaterThan(20); + expect(carried).toBe(vertices); + }); +}); diff --git a/src/app/features/scene/ridge/nightBodies.ts b/src/app/features/scene/ridge/nightBodies.ts new file mode 100644 index 00000000..bf313a4a --- /dev/null +++ b/src/app/features/scene/ridge/nightBodies.ts @@ -0,0 +1,269 @@ +// The night's bodies on the sky canvas: the real stars (`starCatalogue.ts`, for the place and the moment the sky state draws, `sun.time`), +// the moon with its phase, and the constellation lines. Each body's radiance (`nightSky.ts`) is added to the sky's own radiance behind it +// (the dome's grid, `skyDome.ts`) and goes through the sky's display (exposure, scotopic grade, ACES, curve), so the twilight that brightens the sky +// hides them, as a camera's exposure would, and the cards share the display. A body's contrast is compressed (`NIGHT_LOOK`): see there. +import { display8 } from './toneMap'; +import { blackbodyRgb, compressed, extinguished, NIGHT_LOOK, moonSurface, starRadiance, temperatureOfBV } from './nightSky'; +import type { Dome } from './skyDome'; +import type { PhysicalSky, SkyPixels } from './physicalSky'; +import { linesAt, MAG_LIMIT, starsAt } from './starCatalogue'; +import type { Star } from './stars'; + +const RAD = Math.PI / 180; +const luma = (c: ArrayLike): number => 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]; +const css = (c: ArrayLike): string => `rgb(${c[0]},${c[1]},${c[2]})`; +const wrap180 = (d: number): number => ((((d + 180) % 360) + 360) % 360) - 180; + +/** Where a direction is on the image (the camera's angle-linear mapping, `view.ts`), as fractions of its width and height (y down). */ +export function onScreen( + camera: SkyPixels['camera'], + azimuth: number, + elevation: number +): { x: number; y: number } { + return { + x: 0.5 + wrap180(azimuth - camera.azimuthDeg) / camera.hfovDeg, + y: camera.horizonAt - elevation / camera.vfovDeg, + }; +} + +/** The dome's radiance behind a point of the image (fractions), bilinear between texel centres. */ +export function domeAt(dome: Dome, x: number, y: number, out: number[]): void { + const fx = Math.min(dome.w - 1, Math.max(0, x * dome.w - 0.5)); + const fy = Math.min(dome.h - 1, Math.max(0, y * dome.h - 0.5)); + const i0 = Math.floor(fx); + const j0 = Math.floor(fy); + const i1 = Math.min(dome.w - 1, i0 + 1); + const j1 = Math.min(dome.h - 1, j0 + 1); + const tx = fx - i0; + const ty = fy - j0; + for (let k = 0; k < 3; k += 1) { + const at = (i: number, j: number) => dome.hdr[(j * dome.w + i) * 3 + k]; + out[k] = + (at(i0, j0) * (1 - tx) + at(i1, j0) * tx) * (1 - ty) + (at(i0, j1) * (1 - tx) + at(i1, j1) * tx) * ty; + } +} + +/** `bg` plus a body of radiance `add` on it, the contrast compressed to the power `exp` (1 physical), as linear rgb into `out`. */ +function composite(bg: number[], add: number[], exp: number, out: number[]): void { + const total = luma(bg) + luma(add); + const k = total > 0 ? compressed(luma(bg), luma(add), exp) / total : 1; + for (let i = 0; i < 3; i += 1) out[i] = (bg[i] + add[i]) * k; +} + +export interface MoonDraw { + x: number; + y: number; + /** Radius as a fraction of the image height. */ + radius: number; + /** Lit fraction of the disc and the phase angle (0 full) in radians. */ + illuminated: number; + phaseAngle: number; + /** Direction of the bright limb on the image, radians counter-clockwise from the right. */ + limb: number; + lit: string; + dark: string; +} + +export interface LineDraw { + /** Polyline in image fractions. */ + points: { x: number; y: number }[]; +} + +export interface NightBodies { + stars: Star[]; + moon?: MoonDraw; + lines: LineDraw[]; +} + +/** Unit vector (east, north, up) of a direction. */ +const vec = (az: number, el: number): [number, number, number] => [ + Math.cos(el * RAD) * Math.sin(az * RAD), + Math.cos(el * RAD) * Math.cos(az * RAD), + Math.sin(el * RAD), +]; + +/** The screen direction (radians, counter-clockwise from the right) from the moon toward `toward`, by the tangent of the great circle at the moon. */ +export function limbAngle(moon: { azimuth: number; elevation: number }, toward: { azimuth: number; elevation: number }): number { + const m = vec(moon.azimuth, moon.elevation); + const s = vec(toward.azimuth, toward.elevation); + const d = m[0] * s[0] + m[1] * s[1] + m[2] * s[2]; + const t = [s[0] - d * m[0], s[1] - d * m[1], s[2] - d * m[2]]; + const az = moon.azimuth * RAD; + const el = moon.elevation * RAD; + const east = [Math.cos(az), -Math.sin(az), 0]; + const up = [-Math.sin(el) * Math.sin(az), -Math.sin(el) * Math.cos(az), Math.cos(el)]; + return Math.atan2(t[0] * up[0] + t[1] * up[1] + t[2] * up[2], t[0] * east[0] + t[1] * east[1] + t[2] * east[2]); +} + +/** Great-circle subdivision of a chain's legs, as az/el. */ +function slerp(a: { azimuth: number; elevation: number }, b: { azimuth: number; elevation: number }, n: number) { + const u = vec(a.azimuth, a.elevation); + const v = vec(b.azimuth, b.elevation); + const w = Math.acos(Math.min(1, Math.max(-1, u[0] * v[0] + u[1] * v[1] + u[2] * v[2]))); + if (w < 1e-6) return [a]; + return Array.from({ length: n + 1 }, (_, i) => { + const t = i / n; + const s0 = Math.sin((1 - t) * w) / Math.sin(w); + const s1 = Math.sin(t * w) / Math.sin(w); + const p = [0, 1, 2].map((k) => s0 * u[k] + s1 * v[k]); + return { + azimuth: ((Math.atan2(p[0], p[1]) / RAD) % 360 + 360) % 360, + elevation: Math.asin(Math.min(1, Math.max(-1, p[2]))) / RAD, + }; + }); +} + +/** + * The stars, moon and (when asked, and only in the night state) constellation lines of a physical sky as seen through the camera of `px` + * (`paintSky`'s grid and the dome behind it). The moment is the sky's own, `p.sun.time`, so the bodies agree with the light. + */ +export function nightBodies(p: PhysicalSky, px: SkyPixels, withLines: boolean): NightBodies { + const { place } = p.view; + const { camera, dome } = px; + const display = p.fit.display; + const bg = [0, 0, 0]; + const add = [0, 0, 0]; + const tot = [0, 0, 0]; + const out = [0, 0, 0]; + let moon: MoonDraw | undefined; + const mo = p.moon; + const mAt = onScreen(camera, mo.azimuth, mo.elevation); + if (mo.elevation > -1 && mAt.x > -0.05 && mAt.x < 1.05 && mAt.y > -0.05 && mAt.y < 1.05) { + domeAt(dome, mAt.x, mAt.y, bg); + const trans = [0, 0, 0]; + p.atm.transmittanceToSpace(Math.max(Math.sin(mo.elevation * RAD), 0), trans); + const top = Math.max(...trans, 1e-9); + const tint = [1, 0.96, 0.88]; + const surface = moonSurface(mo); + for (let i = 0; i < 3; i += 1) add[i] = surface * tint[i] * (trans[i] / top) ** 0.6; + composite(bg, add, NIGHT_LOOK.moonContrastExp, tot); + display8(tot[0], tot[1], tot[2], display, out); + const lit = css(out); + // Earthshine: a fraction of the full moon's surface, the more the thinner the crescent. + const full = moonSurface({ ...mo, ratio: mo.ratio / Math.max(mo.illuminated, 0.02), illuminated: 1 }); + for (let i = 0; i < 3; i += 1) add[i] = NIGHT_LOOK.earthshine * full * (1.1 - mo.illuminated) * [0.9, 1, 1.15][i]; + composite(bg, add, NIGHT_LOOK.moonContrastExp, tot); + display8(tot[0], tot[1], tot[2], display, out); + moon = { + x: mAt.x, + y: mAt.y, + radius: ((mo.radius / RAD) * NIGHT_LOOK.moonScale) / camera.vfovDeg, + illuminated: mo.illuminated, + phaseAngle: mo.phaseAngleDeg * RAD, + limb: limbAngle(mo, p.sun), + lit, + dark: css(out), + }; + } + + const stars: Star[] = []; + for (const s of starsAt(p.sun.time, place.lat, place.lon, MAG_LIMIT, -0.5)) { + const at = onScreen(camera, s.azimuth, s.elevation); + if (at.x < -0.02 || at.x > 1.02 || at.y < -0.02 || at.y > 1.02) continue; + // The moon is painted over the stars: one inside its disc is never seen, and its twinkle would be painted over the moon. + if (moon && Math.hypot((at.x - moon.x) * px.w, (at.y - moon.y) * px.h) < Math.max(2, moon.radius * px.h)) continue; + const back = [0, 0, 0]; + domeAt(dome, at.x, at.y, back); + const m = extinguished(s.mag, s.elevation); + const rgb = blackbodyRgb(temperatureOfBV(s.bv)); + const lum = starRadiance(m); + // Each star owns its own scratch: `shade` outlives this loop. + const hdr = (gain: number, o: number[]) => { + const a = [rgb[0] * lum * gain, rgb[1] * lum * gain, rgb[2] * lum * gain]; + const t = [0, 0, 0]; + composite(back, a, NIGHT_LOOK.starContrastExp, t); + display8(t[0], t[1], t[2], display, o); + }; + const base = [0, 0, 0]; + hdr(1, base); + display8(back[0], back[1], back[2], display, out); + // A star the sky hides (within three 8-bit steps of it in every channel) is not drawn. + if (Math.max(Math.abs(base[0] - out[0]), Math.abs(base[1] - out[1]), Math.abs(base[2] - out[2])) < 3) continue; + const { base: r0, perMag } = NIGHT_LOOK.starRadius; + stars.push({ + id: s.index, + x: at.x, + y: at.y, + r: r0 + perMag * Math.max(0, MAG_LIMIT - m), + fill: css(base), + cover: css(out), + shade: (gain) => { + const o = [0, 0, 0]; + hdr(gain, o); + return css(o); + }, + }); + } + + const lines: LineDraw[] = []; + if (withLines && p.state === 'night') { + for (const chain of linesAt(p.sun.time, place.lat, place.lon)) { + const points: { x: number; y: number }[] = []; + const flush = () => { + if (points.length > 1) lines.push({ points: points.slice() }); + points.length = 0; + }; + chain.forEach((v, i) => { + const legs = i === 0 ? [v] : slerp(chain[i - 1], v, 6).slice(1); + legs.forEach((q) => { + const a = onScreen(camera, q.azimuth, q.elevation); + const prev = points[points.length - 1]; + if (prev && Math.abs(a.x - prev.x) > 0.5) flush(); + points.push(a); + }); + }); + flush(); + } + } + return { stars, moon, lines }; +} + +/** Paint the lines, the stars and the moon onto the canvas (`w` x `h` device px, `scale` device px per CSS px), in that order. */ +export function paintNightBodies( + ctx: CanvasRenderingContext2D, + nb: NightBodies, + w: number, + h: number, + scale: number +): void { + if (nb.lines.length) { + const [r, g, b] = NIGHT_LOOK.lines.rgb; + ctx.save(); + ctx.strokeStyle = `rgba(${r},${g},${b},${NIGHT_LOOK.lines.alpha})`; + ctx.lineWidth = NIGHT_LOOK.lines.widthPx * scale; + ctx.lineJoin = 'round'; + nb.lines.forEach((l) => { + ctx.beginPath(); + l.points.forEach((q, i) => (i ? ctx.lineTo(q.x * w, q.y * h) : ctx.moveTo(q.x * w, q.y * h))); + ctx.stroke(); + }); + ctx.restore(); + } + nb.stars.forEach((s) => { + ctx.fillStyle = s.fill; + ctx.beginPath(); + ctx.arc(s.x * w, s.y * h, s.r * scale, 0, 2 * Math.PI); + ctx.fill(); + }); + const m = nb.moon; + if (!m) return; + const R = Math.max(2 * scale, m.radius * h); + ctx.save(); + ctx.translate(m.x * w, m.y * h); + ctx.rotate(-m.limb); // the bright limb to +x; canvas rotation is clockwise, `limb` counter-clockwise + ctx.fillStyle = m.dark; + ctx.beginPath(); + ctx.arc(0, 0, R, 0, 2 * Math.PI); + ctx.fill(); + if (m.illuminated > 0.004) { + // Lit: the half toward the sun, plus or minus the half-ellipse of the terminator, whose semi-axis along x is R |cos i|. + const cosI = Math.cos(m.phaseAngle); + ctx.fillStyle = m.lit; + ctx.beginPath(); + ctx.arc(0, 0, R, -Math.PI / 2, Math.PI / 2, false); + ctx.ellipse(0, 0, Math.max(R * Math.abs(cosI), 1e-3), R, 0, Math.PI / 2, cosI > 0 ? (3 * Math.PI) / 2 : -Math.PI / 2, cosI <= 0); + ctx.closePath(); + ctx.fill(); + } + ctx.restore(); +} diff --git a/src/app/features/scene/ridge/nightSky.ts b/src/app/features/scene/ridge/nightSky.ts new file mode 100644 index 00000000..c7146fb0 --- /dev/null +++ b/src/app/features/scene/ridge/nightSky.ts @@ -0,0 +1,190 @@ +// The night's light and bodies, in the units of the day sky: radiance per unit of the sun's irradiance (`skyDome.ts`). The sun is 1; the moon +// is its brightness by phase (Krisciunas & Schaefer 1991) times the atmosphere's response to a light at the moon's elevation +// (`earthAtmosphere.ts`, the same sky-view LUT, baked for the moon instead of the sun); the airglow is a floor; a star is its illuminance +// over the point spread it is drawn with. Everything marked EYEBALLED is a knob of the look, tuned by eye, not a measurement. +import { moonPhase, moonPosition } from '../../../../sky/moon.js'; +import type { Atmosphere, Vec3 } from './earthAtmosphere'; +import type { Place } from './view'; + +const RAD = Math.PI / 180; +const clamp = (x: number, lo: number, hi: number): number => Math.min(hi, Math.max(lo, x)); + +/** Illuminance in lux of a source of apparent visual magnitude `m` above the atmosphere (V = 0 is 2.13e-6 lux; the sun, V = -26.74, 1.06e5). */ +export const luxOfMagnitude = (m: number): number => 10 ** (-0.4 * (m + 14.18)); +export const SUN_V = -26.74; +/** The sun's illuminance, the unit of every radiance of the ridge sky. */ +export const SUN_LUX = luxOfMagnitude(SUN_V); + +/** The look of the night's bodies. EYEBALLED knobs: the operator tunes these by eye. */ +export const NIGHT_LOOK = { + /** Radius of the point spread a star's light is spread over, arcminutes: smaller is brighter and more of them saturate. */ + starPsfArcmin: 1.5, + /** Atmospheric extinction in magnitudes per air mass (V band, a clean low site is 0.2). */ + extinctionPerAirmass: 0.2, + /** + * Display contrast of a star over its sky is the physical contrast to this power (1 = physical): the eye and a camera cannot show a + * mag 0 star at the 1e4:1 it has over a dark sky. Brightest stars still saturate; the faintest keep a little. + */ + starContrastExp: 0.8, + /** The same for the moon's disc (physical contrast is 1e7 and more). */ + moonContrastExp: 0.3, + /** Visible radius of a star, CSS px: `base` for the faintest, plus `perMag` for each magnitude brighter than 5.5. */ + starRadius: { base: 0.65, perMag: 0.22 }, + /** The moon's disc, as a multiple of its true angular size (1 is true; a viewer's eye sees it larger than a lens does). */ + moonScale: 1, + /** Earthshine on the unlit part of the disc, as a fraction of the lit surface's radiance. */ + earthshine: 4e-5, + /** Constellation lines: opacity of the stroke (a pale blue-white) and its width in CSS px. */ + lines: { alpha: 0.22, widthPx: 0.9, rgb: [160, 185, 235] as const }, +}; + +// ---- Airglow ---------------------------------------------------------------------------------- + +/** Natural night-sky radiance at the zenith without moon or town, cd/m^2 (about 22 V mag/arcsec^2: 2.5e-4). */ +export const AIRGLOW_CD = 2.5e-4; +/** Its colour, linear, luminance 1 (a faint cool grey). EYEBALLED. */ +const AIRGLOW_TINT: Vec3 = [0.95, 1, 1.1]; +const AIRGLOW_NORM = 0.2126 * 0.95 + 0.7152 + 0.0722 * 1.1; + +/** The airglow floor, per unit of sun irradiance, at view elevation sine `vz` (brighter toward the horizon, van Rhijn). */ +export function airglow(vz: number, out: number[]): void { + const k = ((AIRGLOW_CD / SUN_LUX) * (0.6 + 1.4 * (1 - clamp(vz, 0, 1)))) / AIRGLOW_NORM; + out[0] += AIRGLOW_TINT[0] * k; + out[1] += AIRGLOW_TINT[1] * k; + out[2] += AIRGLOW_TINT[2] * k; +} + +// ---- Moon -------------------------------------------------------------------------------------- + +/** The moon over a place at a moment, with its light. */ +export interface MoonSample { + /** Degrees clockwise from north, and above the horizon (topocentric, no refraction). */ + azimuth: number; + elevation: number; + time: Date; + /** Lit fraction of the disc, and the sun-moon-earth angle in degrees (0 full, 180 new). */ + illuminated: number; + phaseAngleDeg: number; + waxing: boolean; + distanceKm: number; + /** Angular radius in radians. */ + radius: number; + /** The moon's illuminance relative to the sun's: its light on the ground per unit of the sun's. */ + ratio: number; +} + +/** The moon's visual magnitude at phase angle `alphaDeg`: Krisciunas & Schaefer 1991 (the Allen / Lane & Irvine fit) plus the distance. */ +export const moonMagnitude = (alphaDeg: number, distanceKm: number): number => { + const a = Math.abs(alphaDeg); + return -12.73 + 0.026 * a + 4e-9 * a ** 4 + 5 * Math.log10(distanceKm / 384400); +}; + +/** The moon's illuminance over the sun's. At full moon about 2.5e-6. */ +export const moonIrradianceRatio = (alphaDeg: number, distanceKm: number): number => + 10 ** (-0.4 * (moonMagnitude(alphaDeg, distanceKm) - SUN_V)); + +export function moonAt(place: Place, time: Date): MoonSample { + const p = moonPosition(time, place.lat, place.lon) as { elevation: number; azimuth: number }; + const ph = moonPhase(time) as { + illuminated: number; + phaseAngleDeg: number; + waxing: boolean; + distanceKm: number; + }; + return { + ...p, + time, + illuminated: ph.illuminated, + phaseAngleDeg: ph.phaseAngleDeg, + waxing: ph.waxing, + distanceKm: ph.distanceKm, + radius: Math.asin(1737.4 / ph.distanceKm), + ratio: moonIrradianceRatio(ph.phaseAngleDeg, ph.distanceKm), + }; +} + +/** + * The radiance of the moon's lit surface per unit of sun irradiance: its flux over the lit area of the disc. About 4000 cd/m^2 at full moon. + * `lit` is the lit fraction (at least a sliver, so a thin crescent's surface brightness stays finite). + */ +export const moonSurface = (m: MoonSample): number => + m.ratio / (Math.max(m.illuminated, 0.02) * Math.PI * m.radius * m.radius); + +// ---- The night's light, as the dome and the cards read it ------------------------------------ + +/** What lights the sky besides the sun: the moon (its own atmosphere bake, scaled by `ratio`) and the airglow. */ +export interface NightLight { + moon?: { azimuth: number; elevation: number; atm: Atmosphere; ratio: number }; +} + +/** + * Add the night's radiance (the moon's scattered light and the airglow, per unit of sun irradiance) for a view ray: `vz` the sine of its + * elevation, `azRad` its azimuth in radians, written onto `out`. + */ +export function addNightRadiance( + n: NightLight | undefined, + vz: number, + azRad: number, + out: number[] +): void { + airglow(vz, out); + if (!n?.moon) return; + const m = n.moon; + const tmp = [0, 0, 0]; + m.atm.radiance(vz, Math.cos(azRad - m.azimuth * RAD), tmp); + out[0] += tmp[0] * m.ratio; + out[1] += tmp[1] * m.ratio; + out[2] += tmp[2] * m.ratio; +} + +// ---- Stars ------------------------------------------------------------------------------------- + +/** Relative air mass, Kasten & Young 1989. Elevation in degrees. */ +export const airMass = (elDeg: number): number => + 1 / (Math.sin(Math.max(elDeg, 0) * RAD) + 0.50572 * Math.pow(Math.max(elDeg, 0) + 6.07995, -1.6364)); + +/** A star's magnitude after the air: extinction per air mass along its elevation. */ +export const extinguished = (mag: number, elDeg: number): number => + mag + NIGHT_LOOK.extinctionPerAirmass * airMass(elDeg); + +/** Linear sRGB colour of a black body of temperature `t` kelvin at luminance 1 (Kim et al. 2002 Planckian locus, sRGB primaries). */ +export function blackbodyRgb(t: number): Vec3 { + const T = clamp(t, 1700, 24000); + const x = + T <= 4000 + ? -0.2661239e9 / T ** 3 - 0.2343589e6 / T ** 2 + 0.8776956e3 / T + 0.17991 + : -3.0258469e9 / T ** 3 + 2.1070379e6 / T ** 2 + 0.2226347e3 / T + 0.24039; + const y = + T <= 2222 + ? -1.1063814 * x ** 3 - 1.3481102 * x ** 2 + 2.18555832 * x - 0.20219683 + : T <= 4000 + ? -0.9549476 * x ** 3 - 1.37418593 * x ** 2 + 2.09137015 * x - 0.16748867 + : 3.081758 * x ** 3 - 5.8733867 * x ** 2 + 3.75112997 * x - 0.37001483; + const X = x / y; + const Z = (1 - x - y) / y; + const rgb = [ + 3.2406 * X - 1.5372 - 0.4986 * Z, + -0.9689 * X + 1.8758 + 0.0415 * Z, + 0.0557 * X - 0.204 + 1.057 * Z, + ].map((c) => Math.max(0, c)); + const lum = 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]; + return [rgb[0] / lum, rgb[1] / lum, rgb[2] / lum]; +} + +/** Effective temperature of a star from its B-V colour index (Ballesteros 2012). */ +export const temperatureOfBV = (bv: number): number => { + const c = clamp(bv, -0.4, 2); + return 4600 * (1 / (0.92 * c + 1.7) + 1 / (0.92 * c + 0.62)); +}; + +/** A star's radiance when seen through the point spread, per unit of sun irradiance: its illuminance over the spread's solid angle. */ +export const starRadiance = (mag: number): number => { + const r = (NIGHT_LOOK.starPsfArcmin / 60) * RAD; + return luxOfMagnitude(mag) / (Math.PI * r * r) / SUN_LUX; +}; + +/** Perceptual compression of a body's contrast over the sky behind it: `bg` the sky's radiance, `add` the body's on top; the exponent 1 is physical. */ +export const compressed = (bg: number, add: number, exp: number): number => { + const b = Math.max(bg, 1e-30); + return b * ((b + add) / b) ** exp; +}; diff --git a/src/app/features/scene/ridge/nightSkyData.ts b/src/app/features/scene/ridge/nightSkyData.ts new file mode 100644 index 00000000..d24cb3e8 --- /dev/null +++ b/src/app/features/scene/ridge/nightSkyData.ts @@ -0,0 +1,271 @@ +/* eslint-disable */ +// GENERATED by scripts/ridge-sky/build-night-sky.py: do not edit. The night sky's data, J2000. +// Stars: Yale Bright Star Catalogue, 5th revised ed. (Hoffleit & Warren 1991; public domain), Vmag <= 5.5, 2887 stars. +// source http://tdc-www.harvard.edu/catalogs/bsc5.dat.gz (copy of CDS/VizieR V/50), sha256 0471ced07fc241e625613baa689b2fa5f4b59fd733f731003e57d2d436036cdb +// Constellation lines: d3-celestial constellations.lines.json (Olaf Frohn, BSD-3-Clause), 150 chains. +// source https://github.com/ofrohn/d3-celestial/blob/master/data/constellations.lines.json, sha256 294f66bef5d5cf50b1e17f16d2efa1d97a15131612c68dd935adef6e7373e13c +// Layout: see the generator's docstring. Stars are sorted brightest first. + +export const STAR_COUNT = 2887; +export const STARS_B64 = ` +B0g5aAsZQkQONRogHphImydWX5x6KSg8kcYotykZTThrwSpB6zdVdCoYp1FuhzAuXxGZLjERJD+IijJ2A5YjKjQOstOcjDckDTF6lzlm5a9oWj +t0JY8gcDwOuVLbpz9L6vTfVT8efIgcK0EOs9xlwEEeu4RCJkMNYJx6KUNFKGwFkUMUbErLVkYPioXFLkloT7s7S0kOzTkHiUkOAjqvqEkSWWLZ +HEoZxTtKfkoQu4RCJksMIew2PUsSm4mWz0sYB1etPEwOUyTpxkwx/3XS10xOKUx2Wk07TMQZT00YVlldK01ZHpMixk0Q+LvZQk0t6z/sv04aUb +PUHU5htEZSl08Z5dlPL08PSF0xMk8bCUR2ZlAO0VBarVAa52Svc1BhnBZeoVBSlKrdpFAe/Rrz/lA308mZWlAOwAdrZlFMlDw8fVEPfgFfqVEU +ZgyoslFo0z0/clEQhZZGTFFMWZ526VJii7vckVIgQfJSPVJpdCE/ulIWDn65lFMeYYdeOlMYSdlAuVQ7bGE6QlRsNAdo0FVUBjuTf1UOK6b+pV +UYZr86yVVl+FUbR1UMCmOyK1UiBxYzvFVeogEf1FUq7I4dzlUalrM6T1ZSwpH1M1YOypyaPFYPpZsLRFYQuqrTX1YTqXUv0FcYrATVQ1hQ2+cL +jlhm47x9SFgOAfbwp1hsLreiaVkc535dzFkZTuMC2Vkk805TVlkVjN1QsFlMFQpZ1lkSLvaflVoX7mPDMVoQaCDQhVtripS/PFsO13cwnVsfRr +H4cFsaJzunZlwkz4INZ1wUfIHcN1wTIsuBVVwdOG44nFxSBqOnclwU8z/stFwVoqvVY1wWYRSXnV0gYjyKT10THYa5Xl1G36cjiV1UQg+q1V4g +Y5Qqml42vZ+nQl4OzDQrr15m+3K3OV5GnIasHV4Pzbr1Sl4Ot009S15qVZ2Bpl5KvMOUVV5e5NIYj15lOK2+el9o7658119GVI7JS18bYZ4vaV +8gTnJrJF8OojuYd18NCrCQnl9IEL1+hl9TP6ZzRWAPuzbEeGAgvrpiymBKlAQhEmA4sYJyLGAOrVZvXWAuArLyrGA5+cTYW2BNDLHeV2AMWgKY +lWEODouWj2FIWzp5YmFCoClYrWEfzqnJJWEo1bkGMWFiHRVvKGEn9e1MKmFecShIomEUqtIvwGEYXegQaWEoFUQEoGJr0VBarWIbSSrnuGIQXa +NSHmIZdqrcWmIQb66aW2IgZ8wZYmIqfk/Ki2IU9ol/tmITnOUTeGJC2iAYzGM84UgEOGNVUPL7qmNEUSrJbGNoT4WCaGMW/roQOWMQsuuLf2NK +z0e9o2RfJ2jPoWRBrzVTvmQ0CMG7VGRLocu3k2QaCBfCsWQgBzwRnmQQzYHUX2RcCI4LX2RHoif2w2QSYGh0I2QnDXdJv2RSluncSmQTnEM+VW +QQNEsaXmQVCZt7tmUiy73uRmUyxhjDe2VgfZOXQ2UQo24Fu2VoOogiH2UQr6Mp5mUc5sw64GVL47PjSWYPIdDDp2ZSEtn6amZALl90iGZLfXP4 +aGZYIsO3S2ZnA9y9PGZLZT4hTWZTvmPpsGdmjWXiLmdmsntfJmcX2p8eRGcPF7VeMGdp3F9TxGciAbhTo2cdArhZtGdhfjakumcQt0aRQmcU12 +V+yWcw5bZ13WcTHsidWWcUhzPmiWgwTjYvYGhi5JyXI2gl67RVjWhSTeL9qmhKMr5RS2hUVPxo7mhMzaMwRmgOWNfUfmkWGOVa5GkOsR+tRmkg +ZihqFmlq7a1TeWlJe8p9rmkW3U9qQmlkysPge2lI/gbjq2lZtjC3MWkUkUjoJ2kkd5YNWmlRP7lyXGkOYvR/aWkcpUICoGppuaALXGpub6Tc02 +pTwAuOPWpGojfzaGoUvoIc0WodHG1kHGoVXHBFKGoU58ulWGpUfreBQmstblOkXGtX3XfxlWsY2bnRL2sS1L8ZcmtKOy0mJ2tGmezG0mtorzmX +fGsQDUhXkmsut1pa1mtDM89uhGsp1pAnf2seCKRxQGsQVhSN2mwSpl0hiWw744nUhGxo7CA9t2xswy+SlmwitG3FKGxmCvJnj2wUtg9kQmxoGh +QRqmwyeJO2RGwOL6LnNWxHsKpkSWwOmL1sp2w+U93YIWwhY93y121Huwg50m0182EjLG0Qom1NoW0ox8sOeW0UMgyEcW1TtW0IvW0a58hyr20Z +CB2ahG0eyirDkW0T+UpFWG1ww1SmNG0QwqJhr21IHdW4m21onngRr25f8Ld3lG5hjvP9om5ITPMEN24dgBJVaW49WaBxuW5KzMSfPm4QQ8r7YW +5URVgQjW5jUWcRjm4y+GvXl24YgPMm3m5OwS9Hm29MP05Dn28q0qgfe28XS7Jat29He+zQiG8dsCcdcm9HlTsgjm8QHGpkMm8VM3uxUm9IBLwZ +am8mrj3ram8eyJh/Pm8QdANzc29WRRi9Nm8T2S3uT28Txnj7am9R4KNtTG9m4tbgIW8/bBEoxW9ZkVKyom9I+LPuSW8PvsNw528yi9gobm9I4k +2Gl3Ae/poxq3Balab8V3BezIMYKnBg8A5cdHBOaSTXjHBGdzhEdnAUPT0SYHAwYklMsHAepWAQw3AZdWVyRnArtlIASnBwjWxubnBMWX6CgnA0 +RBDTlXBKf1y8NHAQEos+GnBUX7TAQ3Be3bqyKXAUd73zI3BUrfUyvHAUOB7FpnEUvSg1onEUAtzBlHEvcX0ZIXEhLy45lnFKaIfwfXErHZaO23 +EWFN/dLHFYkwamzHEP36amVXEQLsHCOHEVA/fjYXFWm2Wv2XEqNqjulXEcFV3NUHIQaIfwfXI58qRkqXInIedNaHIpeCMOYXJqxTP4h3IQC2gZ +J3JWY/irhHJHnRSaNnJE+idLonIUmr+YqXJIXD/Za3IqhX3zw3JUCalehnIggNQciXJEUDR4g3IQ6j80zXJLjp2xgnIY4OB5vnJsoeIbtnIs0R +NNcXNS2yWMcnNF81NLRnNNT8GajXMf1STXjXMUvuQgYHNLBfQ4dXNrxjVrunNWvWAEPXNVkK49m3Mm2b3Zg3Mb2b7i0HNU2u8U03M3WR5+z3Nt +vi7ymHNKUDsgJ3NChLMILHNoYOfvEXNL6usLpHMvCSiOvHMu6VnwIXNSgMsUYXNMtc3my3NJYdyhlnMWz91+cnMZO/CDx3MaOUy8G3RNLXRMLH +RIZktBnXRAPk+Ip3RM88+RyXQgwtd5wnRZsCHLv3RKEWn203QoOG43nHQ5MKb8jnQmMKb9jnQmWbxuwXQQOTxNfHQNdT5OYnRKTm8OaHRj/TCI +VHRKWmNXtHQcn291LHQoKrDSgnQaF9NbmnRgA/wSwnRM4SfrrXUcJXSpsHVNB5UfRHUP152VD3VgV8HnqHUYO9Pv43VGvy+zlnVIjlynPXU8H1 +/AKXUUTHFpO3Uo63qa4nVqmadlpXUZN8T1nnVUhO4GfnUW3CfUI3VSvT1fN3Ui7kNyUHVFTU3sWXUQSW0YRHUcgHA8jXUSCapGlnUxaa1tJXVQ +QsZGdHVcKC3ZQ3VQtIb2OnUcVb/6tHVccsIMYnUkFwrBtnUgJSLGVnUzJiinonUWdDGoa3VQ4jqNTXVSoEmbXXVwxoVpGXUS9IVA43USGZVHQH +UPH6KvOnUWrAHwPnZMjmJKg3YWYWn8pHZWMJD0R3ZU/Zzzd3YsHapzVnYPXR9Yc3ZQEXmAMnYSioMNf3YaLa7dwXYSnbDKD3ZGrdTlsXZM5Vlx +enYY/9NugXZGLfemP3ZMOiuEiHYahF2EPnYZFmdffnZb3HYgLHZW/ISPOHYQUab3anZMKAxtMXYVY7X7q3YY0OJ2h3Y0IDE7e3cPAFJqcndMhc +6eZnckqQTgQXciR13RmXdPlnn5jnctf9+MuncaORA1OndK+x4Jy3c+hUadZHdOGlK9GHdN7I4czncgD6ksUHcX8PKDoXdO8S6eT3dk2T8bQ3dS +3EjEUXcOdFLSVnciEoKFNXcS4KuaYncXcNVOGHcYfT6tt3dSdlzITXdIHWBsu3cvAWJfJ3cQHcArhHca6s48RncU3+8jQndMa/lpY3dQ8hX/5n +gYpEITd3hbqU1ZH3hAFdjcw3hlb/gtLXgtVhUFYnho6h4LOXiCb2CSIXggAW+2Fngqy5w/SngQaRgjsHgaUV6XWHhYJ480znghAatK03gzzaxS +ZHgbp8dqGnhSsc7FQHgUj9owq3gtfPOrbHho4f/CiXguwTJfe3gSo13nqHhMf4HUXHgpMq6rOHhPmspulXhP98rWd3hQC+bXwHhG9PDVf3gU8T +X21XlHfH1JiXlktYmuLnkQ+MCOg3lEPdsTkHkSfCrmsnkaNSzbw3kYxyxGdnkqR4P5JHkQ1smAvnlonSGPxnk2F3mTiHkW/ZgeSnkY0Jm+yXky +Epy0OXkSGJ35TXlckqGaP3kQagiDonlRDlFApnlmQrVlNHlibhIWyHkXWhx3gHkOsDQ4k3lSokngbnlgoViaEnksOl1YQ3lEdpN3lnllHaNfLH +keD+F9Z3kYIGbDK3oaS3X5ZXpQwnnZZnokLph3d3oz7eMqnHpQvOeY03qONRHjuno0MxlaHnoabSBmXnoh5Ts2jXpIqqjNmXpqkBxRR3pMXxzp +HnoWfSVmknpRbFMMPnoQ+XA0EHpomn39KHpGIINYH3poh6avIXpUWswXSnobc8wMSHpVjN63WXpr9e/HQXpoMR0DxnoybEC4jXohVkvEaXoTJ2 +nianpH7YBrjHpKffX5NHpKIMU2OntMftR0RHtP8Od4pHsuge2vtXticPwAiHsyUS3ZxHtIlznldHtJB1zcQnse26WZrHsSh90PXHsuhPwNv3sV +JkW+nHsSx0xMf3sYOYEbJHsqkqk1aHtMPao5pntW2/JCDHsj3gWA2XsgvEAVoXtCB1wciHsZIrHcTXtoqe3udHtKyyiETHtIBbqeXXsn5fGJWX +sUPCgPonwW2E80rXwpP5iLwXwddZMBT3xkoJdjcXxcHsg4nXwwV+0g0Xwn+PJPkXwyzjp1iHwSxlR1X3w9u7BavHwYKyU/1XwtlDw8fXw5oG80 +tHxGnfS4UXxKKfgTc3xQLS+0n3wgscN05XwUY8g/eXxQSMmOJ3wSmNqX2Xwjc92wq3xOs+QJI3wy4fdld3xnkQO8I302VB5/tn0qfSaKxH0WVC +jvXn0uypIBUX0s16uoS30QP7CkTn0R17Ks9H1GqNPPrn10GeMGuH0fUuggxn0TJVSWO30SU7LBEX1Oedg1bn1OOQys+n1WWwwww30WIRonPH0S +LR1KbH0ShC3GNn0oMDGvun1WATFzjn0iZVlsvX1mu1/dkH0gfm/QU31iOpqn631hvRIGjX1J/T9UwX1vQ4MzD30TAIbRun02x4ylp301oJUygn +0eOqzov30WsrywbX0dUx1ijn0oiyO/Qn08AiY7YX0UczHKkX0f9jaMc30QBVeqPH0OgInbRn0k5YsGOX0QS6PpO30Vod3uln1N0OtGbH0WMQs4 +i35JVxoIjH4WjiaSgH42WC9yoH4mLTKmoH4SXlIUqX5RqHHrMH5NvX7GT34UNLBfaH5H9OMOaH5GjvYaQn4uTvoSiX5O1iucx34abi2ljH4WMy +9/mX4cRzRa3n4a0DhCbX4MmGap835jMrqFVX4t1bsNSX5Qy85JQH4qFOjt1n4zV+vp234qcewvr34wRPD/UX4aHfyJvX4UCSjMon4UBV3VhH4P +53vUfn5Lscl6tH5tt9dz0H4eawo/Vn4RpGWqoH5mtIX3aH4sW6QotX4o2zEFZH5qrE+xjH5glF27bH5GK35HJX4SHpoBCX5ahJ4GQn4S1aej7n +4b/KtSYn5DJtxtfn5IpAxvzn8ishXug38aqkWxXn8NjlwBK38UioD0JX8mcYlkOn9e8pjOL38fxKZ1Q39gCbm6bX8aiMNKs39U3FbBe39K4WIq +Ln9qpJUkP383LKMfVX9QDLrjhX9k/ucHUX8W6uesmH9UsR+tRn8dESIOnH9MSz2CIn8kvELzqX9ML0oW039EvlZpHn8UAVnNEX9TjGbOOX8i/Z +l2P38uhsFzJX8kjwb0r38StQdGLn8ZcCVCxH9cgCtnn39OqjOojH8asDeYbX8UkD/RTX8Q8l1NiH8XyoQ0qH9SaZZvRX8Qj8GanX8RD7sk+38a +IcSLKH9j9sd7tX8iXMjbmX8glM07tn9YMtErfn8V6+/Zw39tnAV2Jn8W2wavqX9EpReUjH9G8UIFTn9L+0m+Z38WEmw3jn9izNGemX9A99HamH +9OSdXUTX8SMvs2Sn8UDztxmoCAcIwfeIAYRbR1joAVEjQ+eIAmOEaoNIAYvFVRg4BYXHXyQ4AeEbn5YYAsHc2st4AS6taF7oAWiOP7M4AihPjw +coAS9/mkYoBi3Ui9M4BH/k2CXIAS8FahZIAShKD5goBNTOrKMYAn2PlJoYA3NBQmPoBohjt+jYARAD/WnIA2pkwDq4BYBVX2OYAQkXjXrIA2Rp +48WIBfzLoipYBhvL/vqoAsvfY364BBrvi7UYBSWQByd4BqLApNoYBINCjJboBqWUEAlYAQv3WznIAcbpnOR4AQIps9OIAQea/AZYAn0t3ZeIBs +y+/4f4AsqAjJioFkYi0ddYFCvEYQZoFSppyGk4EcQqh1ioE3k9nHrYFcD91wlYEpL+OhsYEU2+5HyoFMmgISZYFsCBLNh4FdmS2pK4FPOkSIho +Ei1VedRoFUOVzAhIFWIMphIIE8xc8Uo4Fk4TF2RIEqhTceb4EUuFBKYIEyWlenR4FqoljcS4EkBGBURYE5/nAkLoFqznJ0DYEQYbB4YYEgUMDb +gYEabs1T6IFYutB+ioFUDx7pUYFKsjcRhIFUYmQ8pYFWbX7BP4FagJtNqoErwevCR4Fe3/H4voFcAfQ+UYEXWh2WZYExniNQqYFmzigw3YF32j +RyzIEYEzVwgoFfgkhug4FQTHjOeoEkcIHzN4ESgK9ePIEWhfY7XoFGH0I1lIIQfUPs04IaAkWqUYIQlGFkyYIm6mC+GII3/WsgsoIiaHeJX4Ia +JdFsx4Ish++aI4IYWi82loIm0kfQkoJT5kx/PYIpB1S6SIIQo11DL4IQFGx4f4IXgJ/ReYIpk+I7joIyIu17uIJe7vxQa4IX2UVtioIZkVHhWY +IQN1McW4IWMWYHyoIaYm5LMIITjnQyo4IaEpPTmIIx9K6AY4JMROFvXIJqKOwVUYIcz/yIgoIj/P+8IoIVvQzLqoJQ2h2YqYJQ0yqYJ4JsoDCq +VYJKMT4eMIJQM2XeTIJhKKSiK4Ii1tWH4IJbKt0oNoImZd3j0YI0teHTb4JIG+X8YIJGFvBUvYIUQgNQtIIcgBrc34IfEz65t4JI/2bHKIIWu5 +j7bIIgY6f5m4Ibi7nUtIIYytRbWYJiI9iOp4JYlPZhjYJokPdExoIo2whsuoMSfh7csYNnA0Cge4NWT1FEToMU3X3BnIM0sY5DKYMS7443JINE +/8GkPoNMw93ls4MUBvZuhYMTnAVzJoMg8werxIMWrhXY5IMhUSW804M1kTh2r4NYO0ZWX4MW908TkYNZu5enyYMjyqBTpoNXLKLaY4MVHqSUS4 +MSYaYPQIMQEbrEeIMsyr1rWINBAP/G0YNWHjaJTYNVrkp67YNdFmbDs4NHeJ4qm4M/Vq6gXYNDLOHDw4NohPolkoNIqgBYZ4MWciqtKINqKWGv +toNNIWZQ44NA4ZMTUYMS+5mvP4MSdOdr5YNQTTzchYMUsGVQfoMeJ268MYNqaHLcKYNuL6/1k4MZcMGHV4NIU+WeoYNqaO4vwoMUBu9dxoMeCP +7+V4MamCa4RoRN0D5Fp4QYbmE5W4RoMGnMPYRVyryc5oQuLNQ/ooQWztWXWIRsWQd1PoRKnSfuSoRVGzpnhIQPoDseeYQQaFKXV4RqQ2njzIQa +iKn6W4QW26xIWIQRrLvcPYQYvMk0oIRAJ8xnRoRQV8513YQamt6JpoRCy+/4f4Q5H0X/dYQUe1x824RUL2UPfIQwlGtrbYQUwHQuS4RMk3c3Ko +Q02ozHKoQVYJ0gmIRKkp/E3YRogaTpSIQZMdGcXIQWAfnDoYQi8wDhd4RNCgMDt4Qc6S2Hx4QbT1XVZYQdf3Y4J4RMh85PaYQeXNsisoRpMBSI +hIRIAzuddYQMklHhWYQ5GV22dYRDzWLKSoQwg3vTMoQVt4nhK4QSE6avcYRMXalfvIQ1ELx0dIQeFsDAeoQs/8n6hYQiEwoq1IVJ3B9ZnoUb3B +9ZnoUbAiJVuIVQ9Chy5YUaskCknIUnGlRwOYUOOnZuioUqCXjYoIVs0agTpYVBS6vULYUlnK8YdIUiUPFOyYUl4jW0noUhnU1YWIVpak/9xYUY +9VCnV4UUF4chR4UVU6d7QIUtEKlgW4UWDMA2hoUYTcFrjIVJlMVtJ4UU9cXSQ4VMh9V4p4UiHA32ooVNjCn+XIUSrzAclYUmbTRvjoUe9D5FJo +VOt0m9koUoIFD3U4VIP4ipL4UR9pLaNoVJz5MM3IVoPav8OYVHh7OqcIUwergJtYUcNsOKWYVsFPYvx4VOtAzqnYVMDx1np4USpyrYXYUSSUcS +joUMM02FWoUQ7E3BS4UUB12InoUaim8GLoUyjnHUK4VjKIBoiYUg+oagdIVWkoeTOoVQ6ZHEzYVrGsl21IVUYs97gIU3Ke/1gYUYmv/Bo4Voex +PNcIUqOSVpxoUUGEHCaoUc8WFU2oUqEqcPT4VKA8DSl4VYO+AfUoVGfOfNyIUTJTbolYYW40lcY4YsjVUFfoZk1machoZbSa4UEIZuNcRLc4ZI +a9AS44ZAnNvelIYemOZQZIYQbxTKH4ZIIhZVVoYQZi/slIZKpjGjloYgWV8ENYYTIGT+VoZH22Q4YIZSHYhFKYZOWZAad4Zq5cDuVYZAq9Hiqo +ZK1+FojoYmtubUdIYiROs9L4ZOQuvvfIYWavI4ZYZeGfcPYIY5yB9ouIYc8x+rjIYTelHtW4YUtGpwi4Zp23sPcoYVe3yWToYWy5C1xYYfMcVI +a4YcmNSYWoY+sxA91IZL4xmBx4ZmUC2TuYZMvDgHuYY4+DjLYYYWnzpyfoZoQ1MLPYZOAWGtG4YSjXF5rYZCQ3RsvYYWyIsTO4YS6pRsJYZQUN +QIjIZOMOM+UoYcV/T194ZgQPtBYoYakvtkQ4YdOSV9JoYtUDZDLoYzVledbYZI0mMSW4Zq6X35IIZmxYAqJoYV6aAVPYYS0qvBP4YkhMcgc4Yq +pgWKzYcUcSXIeIcUpCh+SocYNDl0f4cQS33mZYdKyY2zuYcoIJSXUocSRLTAQ4cySbhdf4dSst45c4cpvuZL2IcolecrZYdF2efgqIcxRw/k4I +dOAjRElId1aD4OtYdqRm8QsIcmD3CcGYcbqXV3fIdqr4NOmYdM8I31ZYc84JP8sIdsdacDZIdoUdD/sIcS+N+Vw4cWHPNC9odYEPxMP4cdLxRw +m4cXChtRaocwaRz/QoccaB4gYodGTx49FYdcXlfdQocik3B+uYckGZf/M4dINZgNyYcjl6eiTocSOMshRIcYpfje4IdD2wfpcIdMIQ7Gpoca/C +Cl0IdMJzvIrYcqRU1ZO4cU71bQKIcudGAu4IdmjI9IaYdQrKDGw4c5HanVnYdmKqt5wYcUQ6zls4dM978gXocXAtnabYcWqdvXKYcnmfY4pIdc +lgWXOocabAlffodoakhui4dfqVy0PIcfV2dyXocTuXq6e4dmBJm8P4cocJmHWIdacavTb4cwhLy4OYcty8Uh0Yc3jc1rnocW99UKSodgGjAHl4 +giBjQytIhgkDt2d4gMqD6jgoheu1fxTIgUvHhOtogfeorCmIhn661OV4gaPrmdH4hWDNhlpIgQd9qqZogszd4gv4gSSQBlEohY9xSOoYgnpynM +e4hIUjUrbogm/kZtvIhWn03XXohu61TbVIgghGP4bohI3GeBWIgyLW6xm4gwqolvcohpCbBIXIgUFMi9I4gjaezi5ohHce0yRYhBn++thohOF/ +KuqYgYmQK8nIhoegfWx4gU0SJ0c4gkLygW2ohB8y7PmIggPzy9dYggWkOW4oga2WF634gypGNocohIRYRUyYhE8YtJp4hjYY1wH4gVzI3Hh4hs +57vJ4YguuP8VyYh09wQOUYhrlzXMdYgQ1UHSMYgOuWM/J4hIPGZZuIhKAITCpIgyMoYuoIgZiJiAsohOWZrUfIg8Dp26pYhsYKCRo4hk67rrXY +gZQb77RogmgsTJYohaf9gXtogude5KqIgZifDZJ4hqbwnu1og02BbXtYgfVCOrsIhkDzculogppT/ppIgW/Ebha4hkZVWYJYgQV1kJO4gSWHH2 +bIifLXJQJIgSgnIIJYgSt4TTNogSVJGes4gk6JZJ7ohd6aAVPYg5SKK2QIgQHKm2sohLl652gYgqa7NlwYgehrX+eYhjargTr4gQn8Q+3YhUrM +lm5YhSLtwmnogYseP1RYgaHfDQcIgWwvypZohCxwnf04lWlQ+TwIkuLxRxm4k51BSbPIlFrxfovoljcSPLhIk7cThfTolLxzdyIIlZhUk8Y4kP +PkyZR4kQI1n9UIli4WLUzIkio27DRIlRtXmOcIlnL5evo4k0ppyGk4k5E6tuoIkd8bHb24lWE77pUokXMcjrpYlVocmmX4lgJcqvd4lPJtW+Wo +lGs9eUwokeCBC8iIleBxYzvIkaXhwdb4kwbh3VH4kcjiNe3YkSJS0sjYlBrlGESYkQ1lZAyYkcHXCdz4kz6HCt64lJb3UlhYlTd7BWkIlkCd6V +wYktyODDY4kiresxh4lhvhT2X4lggC4hwokY+U9BX4kk/3JvJIkSYn2+i4kiTIuPOYkaz4w8Sok8mK7vq4lKuLLB0Iksbs0UXIk1ZvIZRYlMx/ +LpM4lUgvaB1IkYffi1xYlseA0LHokwthv0h4lEuDe7tokirTyDl4kSDD7woolMnVt/LYlL4Fx2NIkQQWxQNokTt4Q6JokT2Jgxl4lWvZybi4lL +I6OIJYlYbr/vQIlWtsPNhIlG6dLlY4lIxP/xeolIXRissIk3HyLN6YkaOi1pcYlUxz7tT4kSOEiJ1IkdkXjXrIk5uo0FIYlkMbZ4T4kmErt3zo +knDr0pYYkw4cdPTYkQZcq1NIkWcco5S4kts/1q04lQow7AwIpPRCP7X4pGijNQtYphPzoyn4oS3lJTmopiwFxTaYpOo2keW4pWcoeOjooeWKqx +a4oUDrt7zoomnL+rRIpsBNx9KIoupvGJt4oP0/9Lz4oWAQIAaooyrwh8yIoU8hmFbooYpiLtnYoYBE29P4oYZVz1VYpGNF+hWIoePnCbM4oySX +EDWYpqRqsZSYoSobSi3IoxitIgtYpI3dtffIppId5BPoplOQ88a4pWWhvZV4oWjkPPe4ppPkoiwIoavUzrt4pioVEvsYotjX5DI4oUeok2nopG +t4rIq4pUjrGVxYpmvcc7dIpR7dCXO4pQN971T4pLL+bNtopPfPSJjIoZ2BwpuYo2VTDwf4pbljV7Y4oW4jwYgopUJD7+kYoWbUQYxop7h3H/Z4 +pHmn1mRoo673/AEIoWA4mlT4oXgZM9nopgQ5fQaIpvk5jKDIommaIsU4osuq9THIo0SrYekoofm9rle4pSUN3wo4pUEup92opyrPpE04oTfEz5 +eYpMdl/DK4oQM43xK4oxG40auYpOW5nbLIpEVZ3zTYoaLKDic4oZoqvWY4oYdskeyIpGjtSUyoofud3jsIpbeOy1UYox1R8JsotWmCxGRIsqTC +4psYtI40COaIsl3kZrO4tEXEt7OYsgSVXEeotWMF6QP4scL3DdF4ttdYcdK4sXzIoq0IsrTKFeo4suq8q3rYtiz8tJS4szAtdktIsSJ/3CqYtI +ugfgwosi4hG1uYsUiBcYq4tAvC1EnYsmNDXjtYsbwzhsn4tIAlFJNYtf2VFKaotn9VWHp4tRx2IlSYtQgmf8XYs0wWn2ZItoSHYuWYsrmnyyJ4 +tSLYaV44taMYkrp4s6vJA0hYsak5xZl4sYg53QW4sqZ566fItKTaRRcYsvEK1NMotNzayvcYseurBbQYscmdS8tosVptbKNItq6/OZvYtnH/rJ +gYsazQANcYtqGBKavIs40COfvYsbSS7lpotSvDmggosPmDxkfosPVEDtcIsTJULwlosSAUq1OotuTXoPhItL6IIOootKsoTHposmWoVq4otqR4 +wfX4tORqrdzYsmx62964ssnMM7n4toOtEBdosZv9MnoIsS39edlYsdrdqexYsUs/S7xotyhP0EwotQXg0+P4s2MVA09Ytsnk70ZIsXnoO2hItT +KacgXotclqUB7otoD7LEZotQRcC2nosfpcWzPosUzc0LZYtMnNSw04toiSdOsIsY5ioiKYtguS9El4tSMz80S4tQrVBYa4tgLVQQposeEGE9h4 +tWrmUSkItO9W4/3YsWNn4fHItf84/jXotpiJM1ZotOWJoOVosWHsKqrIts9c4gqosU69dYtIsgPQ7R0ow7qhEgv4xGAhfkpIwq/STGxYwUL0N8 +14x0/E0SXYwSc1xBboxguY+Yk4w82pDhtIwt5LUKlIxpFsJKXoxOQMSg04wdAMr5hYwjtPhUcowYwPmU2IxtX/uNrIxeQxLAeoxenxSv4YwUyR +/gJIwgtzkrtYxgrTm4mIw0FT85z4wcC0kfT4xeL0v4eYwPOk8xjYxMUFJ/04wdtFeLaYxOklpkQIwRwG7aIIwSd3WtiIwhZHnXvYxKBoigwIyY +lKqhRIxL7Kp0qowWsa3KOIxBzMnBX4xcz8tJS4wzJM0R0oxT7NL3r4wwGtZoUoxWKuyVT4xjgyeTUowRKCro1oxihTZhyYwqqDaEmow5ZTkKhY +wS+kkGbIxUC037loxs+GEwQIwknma4iYxOU3I94oxednmRTIxi74IFr4xSYIOTMYxozIQmpowd8KPWO4wyQ6s2W4xWGqw+mIxIpK/N4YwW8riu +mYxqVMHPvYxG0dAfnIwUYNM5m4weSON/vowYWfX80IxgaPzGa4wlkv+OJIwcZhlCF4xQlTHCbowdzUJ9bIwVAEK3Ioxq90+zp4xQ9VOkTowvgl +v4OIxc52X4YYxMEmYaN4wQF5JnMowWEZKfc4xquZQZp4xgg5dtg4wT7MrAwowiUs5MeIxHCN/np4xjkuZ5uYwifegOVIwbfu5bkYwSagC7VYwS +uDWhWoxOEzh9rowkV0EES4wUqUdSv4xjBklru4xYhnAmPYxNmIR+t4xJP4YimoxSCqMl5oxegKUSuoxopqUquowdN6+nXowlD744yIwa+Mfugo +wW+NT3aYwcX+JEHIxo1gGGwY0tFwx+vo0egBY1oI0etBi8qI0b4SJxyI1SZiM+x40WNSqz2Y0Uyy+Oko0klzPvaI1KNzZ9OY1k5DhLsI0m1j9n +co0iqE31S40Q106go41Gk3Snr41QEn0gJ41Bu548So0Re6lRY40Yq7VJUo0Upbhzj41meMKV240sKc8kXY0kHtAIfI1wq9Ncy41ZieoT6I0vYf +H8eY1S3RLhM40bvhV9zY0VlECeWo1c7EJ0kY0u1lJJa40qL3vJU41o2YAsE41kz4z2aI0wwq+Qu41l3rMQo41YIL507Y0yQMF3q40zlMf8zo0U +L9xMoo0SPd6pvo0j3ejpqo0Yt+x/1I0mlf31hI2b2v1v4I0YwzF9y41OJTIsS40sWDmu8I0wQUGaJ41YHEKvdo0P9k1Zxo0d4k/9p40er1EjmY +1nhVafP41kSlzFX40+Vml5dI0bPXV/uY03Io9+FY1QBLvm4I1P1cPcxY1su86ZMo0ak9VCx41QStxYjo09fd6aNo1S8/inh41V/QRymY1sRSJM +fo01dSsh1I0yNDnEXI06jkEXHo0V+EQ6eY0QY0p8T40RTlLBP41AKmeda40S5o87N40dUJkRDo0Ub6OCgo00E8GZn41o4sdruI0hOtIRaY0q7d +G+wI0tVPgCdY1pC/2xjo1ttQgXmI0yowhxFY1elSjZj40SJjARQI0QoTF4lo0gZTV5841ZEjiuWY0UQDoIsY1fd0gzc41z3lHC+41ql1ivIo1S +r2XRjY1e/pfPLo0VAKcatI0TcavTb405ELgqWo1EssXsPo0Sj9aVoY0QbQYJzY4UbTbe044VsDm7fo5JoDtMeI4UGVM6SY4U0VdXTI4Q4Wj1Po +4UxGuhPI5Ft3A6Xo5p2nDjiY5IIHFJK45UY3L6oI4bfHXEt44lanpPQ44Ympc6WY5TG7FEy44XPbehQI5ECLf+uY5ZMsqfYo4geum6bI4sb+ne +pI4QB/G86I4sgfJ5u45Ju/jbbI5BcPmDkY5aqv4xm45p0gVbJo4bDCR/nY5XVSXdzo4cvyhToo4V0kGvFY4921REQY4QPlp/NI4mo2hzwY44DX +AYf44SfXlKZY4uUI91R45VA6NOKY4W3qluHo5S6Mu+j44WAOgVc45Q3RRXmY5Hfyfo2Y5qdCzF8o41zTPLmo4k+0VDfo4SE02DQI5nkU4TnY5l +W09xN45OUl7TPY4PMXShzY5d2IIwlY4cq40xU45JoplGiI4flMGCnI4g98MFSY5kusnPaY4i982LgY5SQNZunI5OdNw0Zo5sCOcwg45NOu6ZDY +5il+3MRI5HzPXPvI4eUwCxe44TVRSPQ44WhR9qrY4YpCAKK44qzygQr44diimaTo4SvzBLdI5uND7aII4S+02+S44RLFXZXo5RrWQVNI4UBmbi +DI4SfXmeI44VAH70WY5pa5+2Jo4ZRKZ6t45rHamae44fELgqWo5EItDFp44UvdPQjo40XduwQI5M9N1wQY4qJeeLvY5pleuT2I4d9PWUTo4omf +5aC45HkgLvdI5q3wN5Y4507g89YY4a6S50jY4diTZheY4W4japeY4vjEn54Y4SPFaoko4a6mILQY5sAGZOOo4TIHJ23Y5VS4iTl45cfZkDjI4Y +VZ2Bpo45HaqxT44f46pXmY5KDbnXoo4Yo7kxQY4WA75wpI5TvMMPqY4jT8QvuI4avszd0I5M6dD7cI5SqNMSt45udNzjKY40B/dXjI5iigZFv4 +9pOg27dI8wmztVeI8aUEuTj49elk5HtI9PS1Eneo8vwFcrPY8S8VnCio9IjWJb148223bmJ48k+3p2K49PW4aoRY8kmqLH3480oawpVo9R97KO +II8Vycd/SY8eTMzi7I8opdWOK49mge5IYY9Oz//8NI9SoxVoQI9kURrpT48eaCUfkI8YAzo2LI9LnUABnI8UJUMVaI9aD0kZ4I8Q30i0PY8w0k +rlNo9qlkxoOo9XHVOGr49p3FODgo8T51i1po8wfmEb349kqmFan49KQWpjuo8wK4Ji7o8quIO1bI9Oz5jHfI9MYa2gPI8Sl8XTZY8ZO8ZjcI9H +5MdWuI8ia8phKo9eJNTP0Y8SoN3ulo8yvesFwI9oChtos49iUCNtx48WlEVgbo9YkV4wvo9KoXZbQ48a/XpbK48y6nvXKI9RHHwSKI8Yp4CmQ4 +8t74P4H48i6Y2oxo8WA5NxTI8YZJTcfY9PEpV8XI8UWJ4/aY8t8qCYRY9MKKYcWI9a0bI0jI9mLr1INo88G81Dg48WUc+ms48TF9hvoY9Ny9wN +IY8W1+B0Eo8ypAyxrI8k1Q0jhY8dGByP549FDFiFJo8eGV0kOY8P5V/4K48uEm2aIY8k63Au0Y8qJYovN48W26L9RI82z77muI9U1r/5VI9ywc +WIR48dy8uPNY80G8/8kI9AMs8onI9KV9yxgI9O7uAqMo9WEuSviY8c/PP8jY8xa/dmjI8gBQUjv48aIwwbzo88Txlsz48sZh+4eo8d4C6seo8d +gz0NUo8LYT7kNY9Ko0poH49fb0tKL48Xb1LIRY9Q31M7bI839FQtP49YRFXVKY9w31luNo8Ro2fB5o9N6HkEJY8yW3z9Io9BtomxLo8T26DvJI +9IlqTxlY9sF6Wego8kIKbwco8UXcnkNY9ILtGQv49IotGth48aptjAsY85ON+Dk49RqOfa5o9OwQP/tZAu0wPIVpBLTRJw5JAXVB2zkZAlajfR +lpBkZjzUpJASGUtwopBI9lJbtZBogFN/Z5BZzV/SPJAmaXK2wZAqaHjcgpBlS3+bZ5AYZIHQFJBaUoQepZAdRMC2npBIu85ZpZAT3dfPqJAiJO +EAUpBQcuNC3JAXY+cFbJA5vP2ROJAQd/4bZZASZwUrXpAf6QjccJAyrBkex5BKpC0/zJAcaDRAkJAfADttE5BSdUf2cpBm9U7YuZBWcFyLNJAS +Eoy5cJBSTKgH2ZAbUtWutJAQivFu2pAcRAbjepA1VxkgXpA31ytAp5ASrjbVJZBsGz8s1ZAapEI+m5Av10RsgJBU50a/uJAW6EfPU5ATA0vcd5 +BtY0vJQ5Ajf03R1JBOIVkcTJAQgFy8RpAYSFzlG5Aag1/KlZAg618brpBIRmg/0ZBqvnuX4pBMN5+BKpBTLqHhaJBoA6mFlZA5pK4RsJBpJbBY +KJBWibh1XZBQccjid5Bi79qZ6pAd1vCMYpAvXPmcapAjDgz/RJAhkBxrMpAtwEB1dpAWxEQU05BmikcYmZAcClc/QZAQMl5hUZBE6G8afJAWYI +A4vZAmqINnYJAUh5CLcZBJsZ2ANZBK1sRHgJAyOuEat5BUifHG0JBoAwl8N5ArURZA7JBIGR7WmJAWQy08jpAUyz/JgJAaTESab5BXPUUkL5BQ +eUhjxZBRmU9/npAsO1+3p5BL3Xm2TJBKwXzHUZBjHIjpipAqcYzumJAwcYzumJA5go2jY5BMpo1njZA2Ia0qb5Bg1bNcRZAdI8rKrpA2RMyjiJ +AqsdV3o5ArUdy7apAT5frNt5BMWwVQqpElbA7fqJFeshXug5E5xR8KfJEZYyTa25GBdCYoZ5ES6is+qZEqWjF7fJEnNjl0u5ESp0VrkJEgHlO2 +PZESEFfSO5EPylxqP5EkT2DHNZETd2r0TJEo73KaJJEWBHNHL5EVmne8JJEW3ZjbKJEo8agfg5FMmK8xdZFv9bn9N5FOjrv/15E3gcpfk5E0/c +s5rpEq1t8bhpEw9AezYJEqHA3GipEpORLTnJFDPSMaJ5E3eSgLXpEdjy7aJZFJwUVjSpFLPVUcSJEsYWEsj5EU+GL2dpFUzW2GdJEo0nKiq5EW +LXRbY5Ew3YkR3ZEne5e/4pFo0p3lWpFIOqWJPZFwuqZjuZFFlafGSpFKKbN2h5EYjMBddJEsfciIRpFA1MgYY5FgV9houZFsx+KhYpFUPOUwwp +FKeOfqXpFIxOzW0JEy9/WV35FYMf0BZpEVFgIITpEvKgJ8ZpFjKRIGUpFO7xo5g5FY6idYfpEUgzkxbJEPT0j5vZE19008SJEap0/fiZEkX1C5 +gpEkpFCClpEckGKFQpES0mY6uZEkAXSXLpEhuHs+PJEmsIvpspEVsYxSQpFOa4/tbZFl7ZPkNJEUz5ZWxpFsHqGXzZFJi65J4pFRGbAgnZFaX7 +Q/d5FPnrW9r5EaeLl9PJEUG7x9MpEjUsREQZEQDsRamZFY3shLrpEdMdoZZpEWCvI1uZESRRXn25EaDR6tJpEewiAwdZEj8ihhpJEkVC53lZEk +vzA+c5FirDsYeZEla0gOSpEVmlsxLZESOGNlN5EWWmqykZEXMXBq9ZEslnxenpFKJ4AKZJEPk6J6qZEafaY8jpFI0tQ6LJEYUuLtR5EvH/MbZJ +FIBRDawpFLnBcqnpEuKiFXd5FpVy6k3JFCjTIMK5Ej3j0tiZEkgUPfdJEQTUWMOJEtQkbap5EYuEYBUpFUKknynpEYgFK6x5EZEVyoWpEX0WKy +0JFni2L3MJFK6GnaxpEdrX0dz5FYvpZevpFoTa4eEJFgo6/lJJEracPEopFmI8hd6ZFHoMpOpZFXPNLRkJE1mNUw3JFnj+tL2ZFgAu12+pEYyQ +EPC5JOhBHg55JJoRdNVJIYKxhxr5IYPBmQgJJs9xp9D5JKKCB0ypIWxiMTnpIWECoZyJIt8CrLfZISLy+Sn5ImTy+2rJJKgTnW0ZIYBU4wWpJJ +ylnNXZJjN2xlIpJKDG0iN5ImwIih9pIYvcloA5JZbcChnZIUCsYLUZIU98tXs5IU1s19kJIjqtQ/kJIYyNjPZJJfzeJsapJr4vwHapJekAzR4Z +IYVxoyqpI5IST9xZIWEy35ipIrSzKsvZIZ2DyyTpIW0T3Ek5IQFT8kNZIof0attpKcVEh7a5IXClUpg5JHQlmcF5IavF1NfZIbGWN8FZIazW+7 +JJJ2d30FP5IThoOqxZJsJIXapJIW+ZddjpJLbLGqz5JP5bVJNJIxHLrNPpIWteVvRZJQDelbCpI+MeijoJJg6uiVmJIsW+vE2ZJoC+88GZI5hP +1vZZInwxhiw5IY6xu6sJJmkRx8ppIeMzO40JImuTYJnZIe4zh8bpITvkL1lpIS60lfX5IQG0+YkJIe5FJQj5Iat1axnpI4D3oUKZIV4nzs3pJZ +D39uW5JF/p70XJJbT9WnTpIih+AOSZIthuHbYZIag+cTiJJrheu1fpIkS/zHx5IWsP6Rj5Ii9gn5b5JlyBJeXJIswRegyJJI/BtFNZImxCWAwZ +ItSTFrgZITRTI0OJJK0TWTGpJLCzwyV5IwmD26PZJNXkG+ZJJt2UxnRpIcglKrpJJmGFaHUZJ4HF4ae5IUdmzFbZIrgHrxt5Iaf4L4PpJgnodR +JpImJ49JJJItGp7ga5Idvbp9fpI9q9XKIJJWdNmZh5JKsd/An5Jf3eTJtJISxuR0xZIdj/xiUpJKeyARdZJISUJ23ZJcLUj0apIdnFdi4ZJNdG +J2vZISPWeJLZIjOWmxopIkJ3jtkpJV2n26i5IaMoSiTZIV8okqL5Iap4q23pJavpm4XJJJPp/ZT5IbFbQWrZIoU9eoTJJEUdgWo5JINe0HYpJB +Gu/MLZI6O/k+rZIUSfv/n5JpTwceuJNG4h6GtpMtVSu6h5MVKDSRg5NraTQQi5NWzULZkZMYcEmM1JM5DU/1aJMW6lAIrJNMYlORXJM/gVrVO5 +MSJlsSnZNY6F5qPJMmBGP2R5NU2G7xSZMmonyksJM9MI2nY5NEvI1zk5Nas6IGh5NQbqdFkpMbqa5/OZMXTbCHRJMqjbcNj5NoC8NSMJMWbMyv +HpNG4tNKR5MW8ew3sZNSsvb4wZNgrQuKnpMY2BLYd5NlGC4KQZNPvDYWjJMqvzixg5MtSztbfpMQMzunJJNNtWI/lZNb5G3EVpMl5XI/JJMUbH +P/jpMad4G/OpMYoJ/4EpNigsB3XZMzEsTZS5MShsUVUZMh7My1dJMgHOUmHZNmp+3AbZNSufxcZpNojhVUVZNFwhk5KpMsDRuHfpNMshtVsZNs +HyiaiJMTHy4RnpMVxjEMzJMpJTu8fZMQdz5OdZMPyUJU1ZNcU0hO0ZNJN01shJNUEE/CUpNOkFRHnJMXy1QiQpMQ81q7mZNnU14BIZMuv2UwRp +NGxmfxk5Nqjm2vqZMa04DSHpMYU4UQ05MjvaMEgZNU8687PpM1g7Q3mpNgfLn5V5NmPshI65Mc1dBRvJMcNNPXL5Mj4N5hR5Nbzuxp1pNUoPMM +DpMSGQd9npNTKwsDPpNGaCsFhJMybTtbhZMcLEG6tpMmxkHR05NQ30MFzJMuWkOlcpNXZU1bVJMQ/U+kxpMwY1fydJNGS2QaDZMw2WpmrZM6kX +crOpMiLHyRi5NoUpIIhZNQYp2TJpMoCcZ1ypNQAcpBQ5NLoNSol5M6d9Yos5NEqQOli5Nc9wskKJNF8ykVxJMVUiyyaJMSri5zpJMW2TKlkJMi +xVJmT5M321hKGpMWoFwvwZNKm2XssZNm/n8yhZMZwo7GZpNKu5qSOZMc4aPWrpMWZqSGR5MUtqlavZNsa6wRe5Ni2LsZxZNSCceUQpNtPcgnYJ +Nr5MdWuJM5WNXpmJNsNuCkwZMPb+yfT5Ml6u27M5M3Qu7gdJMWTu47iJMYKfZAM5NiywXcnJRPRwgClpRsVg9Em5QsPxbo7ZQoRCOtfpRNIiue +f5QyJy73npQSVi6lYpQYTjVncZRB1TUYOpQuozswopQULkEJepQSh0TiHJRK105qWJRmolbEYpQe8GRdd5Q57XC7R5SpQXLIK5QmWYPk6pQYI5 +JkLJQYV5/kNJQg66aMZJREHayOWpRs67hRpJQatMKFYpQdE8rjSpQSW8qwmJRBtcrex5QQi8vwy5QY3dDnqZQ0XtuGkpQdjQfkIpQyBQlf25Qy +NB5CWJQaiy5g1pRknjExi5QmC0MjjpQetEh2apQU20vvb5QcVk7sNZQW2k4zUpQQ+l59q5ROE2NPHpQum3kAgpRIT3tGRpQfD4T5LZQUCZpYm5 +QkPZwmv5QZlakbXZQYqq7ur5Rmv6/ygJRiw7Ybs5Qo8Ld3lJQ5ArksrpQ4aMNTipROlcN7aZRiR8UtfZRJe8b5jJQsstOxcJQsUtYr2JRU1tyX +x5QUyt2P8pRRHvf4jZQVaATv15QZJBTtuZRboyh+SpQaHDCEk5QmNDG2J5RokTLaj5QmNDxdq5QwQj+xnJRKIEX+dZQWVkgWN5RcJkkTG5QUuo +9B1ZQYMqhvfZQYvK371JRq8K5CSJQ4k81WP5RcrtHlvJQVp+xHyJQg4PYGg5RGDwJ2WJRcfghy6pQVng1xfJRGSxViYpRs5hzAN5Q1mCyppZQq +tjj/r5QQXlUg6ZRgR1+IkJRiGWXawJRKD2XhjJQ3V2btspRAom2Gk5Rqv33xLZRswph+kpQs+JtjPpRM1qe1aZQk2qpdr5Q3brTOnZRKQ7lFHJ +QX8MMdoZRpdNPiGJQkGd4vHpRRTORYYpRT6+RDp5QbqgEyWJQuDQiJzpQbSAo7qZRPDg/9RJRNEBEZapRWSBm9fpQosjqx2ZRuKjqLmZQUA0Z4 +TJRhUlBMmJRSAVIySZQSL1YJ8ZQW8FooZJQWaV8rBpQoAHNmZ5QeyHfmf5QY+4VIr5RLb5ovdpRklqnlXZQXB6+SSpQUg8aZr5QUL8u9epQZjM +tEepRRsNPQK5QdXeK4WJRg0eqIV5QUvfNPSJRgDgU7R5Vn9gYxxpVrNQsfeZVQ5xUugJUgPBw7n5UhLB3/vpVGei/y8pVUiDcq6ZUT/jb6jZUl +qUVldJVewk6ZUpUS10/NSJURGVRITJVTbGEsqpVGNHYUTZUadYj93pVnGZOZZpVqEpgdZpUYcKbbQJVkaqqvXJUU0qzXc5Uf/seOR5VE0c2/oJ +UaM8/rXZVgDtwukJUcMeNrZpUTNu2CWJURhPOBz5VU0PQ9xZUUPfVegZVKQPYOdZUoBP572JU6wSjK5JUegywndpVI7TNR2pVo9UczqZViJ0yo +lpVM43YQWJUdA3wYPJVXsX/nL5UVC4V5SJUViKCTUZUT56aDNZUZtKninJVoy6tw4JUYpK14M5Vwdbp4gJUkicIeYZVlwckqu5VM5toAxpVm8O +QE35UUzfgnxZVMxwkeHZVQiR8QXpUknSON7pUimChPoZUWFS4tx5UkTS2MJ5VQqTGUa5VOxzgHOJUyajyYUZVHOEgo8ZUyrEllfpUiD0oMD5Uc +sUySf5Uou06fzpU5ZU6Ta5VKZVSlw5VidV/OrpUffWDGopUXWWW7NpUUnWasM5UgPWjPEpVGU3F4LJUyOHT4fJVJtIZnWZUpI5NuOJVd26S1S5 +US66n3tZUqGa5PQ5UeRrSKRJUiJb9n5pUohMZ9iZUs19RpuZUU0N5BwJVQtuZ5m5UoXQnbXZVXQBmrcJUq9yeLopUXXiuoi5UsADCG9pVEyjFZ +kZUT4zquhJUQEDtCmJUXsjoLPZU4PEr4XJUrgEzmWJVLjk3VaZUdml2zPpUmtWGAc5VMZHAblJVt+IFuXpUcg4XwopUc9Ib0nZVJxonwBpVMsZ +FDy5Ueh5bBcpUqep5T1JVdbZ/Fb5VkWKP2KZUUrKTVsJVfNa55uJUtML8MpZUq08IhQZVJyMSRO5VDYtFjeZUuW9rM85VMBuoES5UdjuyNb5UT +e++h3JUsxgmaoZVLvxkXj5UUWB5CTZVY+B8ow5VGKiOcvpUWtyVMxJUUcStIopVEejRsFZVlijrEo5UXfj3cxpUaRj4hD5UVKUEhX5UdDE0kyZ +Vs7lkMRJUSfFum3JUi+FucJpVMrlyyD5UU+GKQc5UU3WOj0JVq0mQqGpVPnmUQGJVnt3KODZVIYHW/wJVi1on3QpVtuqp8aJUzIrELQ5Uti7nU +tJU5br8xepVTWcI2RZUQMsRFFZUaj+F8AZUmWdGpa5UysNeQfpVggdxzUJVR6t6Or5Vlw+9YSJVIS++m5JVVpAZYspZFXilgeJYUHjBRlpYm3j +RlmJZalTjbvJZsLTs6SZZWMVOobpYxVlz/M5YRKV6nRpYcUWUvWpZdpGrM0JZi63IwlJZGFXvf1pYyNXw5bZYzlYFcRZYWPIVJopYuoYV8K5Y4 +AYaOcpYY04e3V5ZcVo77NJYSwpX9WJZcT54CtZZMBq0kh5Zil6zp65YU/LL/R5ZK1bSyUJZouLitPZZBbsHFs5ZU1sV0q5YUS8l4npYWzMooz5 +ZEud9qj5ZI/u9NhpYs3RK6N5ZpfR5zlZYUFyHy8JZoCirksZYYxD02mZYoJz5ma5ZF2lJedpZeTVT5TJYQ63LempZRmqWgF5YTJK4LVJYwnbNO +ipYe28HSJ5Y2BsbSXZZyr8jgQZYgVM67fpYXadL/aZYwcNKnpJZIF9UQrJYWbtcgppZgTeSvbZYof+TxepZiqueHupZo4vSJnZY6UvqVA5ZY2/ +0SfJZINgj4X5ZKXAgHkZZKKws7rZYWGgsgU5Ydag9dm5ZQ3BVWr5YaUiQpo5ZUTCzjm5ZOxjaCopYc9DdVh5ZeejjFbJZIRTqTlpYaWj9eU5Y5 +mEEaYJYYZ0EMRJYZP0vWK5YUFlr/kZZpw2aSQpZL8m/S95Y59W70r5ZU6XXsb5ZIjHseOpZN44QaLJZieIaa1JY5R5FS5ZZVBpPQtpZMSJbHEp +ZmsZqLP5YV6qIkYJZeBqRKuJZo2qUIaJYScq0YdJY5xbAKG5ZWSr6zqZZO0cXbapZ7dMvYU5Yakt1ASJYUi+pkSZZLj+y+45Ys++8a8JYc +`; + +export const LINE_CHAINS = 150; +export const LINES_B64 = ` +BAcWM7xmDKiy/gbjq34BX6kHLApNoWoIg6LbBq+p/gbjq44G9K8d/Im9rfUyvAMd/Im9hPwNvwP8EsIFZgyoshcKwLbbCGy6Wwwvw2wRKMUChP +wNv4T9BMIDM2XeTH5v0FPAdC5LBNidlQ9JrhQQU7LBEZ2wyg8Kz91+crLeOXOc5RN4suuLf4TuBn7L7/h/9PDVfwX0OHWE+PByA/fjYQKc5RN4 +0OtGbAKy64t/qe3udALL7/h/Ke/1gQNr+WljhPjwcsL8qWYK5NIYj7LTnIyA1ByJWNfUfv/TboEzz26Eocu3k7LTnIwzz26Ex8sOeQfZudEv3b +qyKYSzCCwXtV4wQrVlNP66EDnVuQYxBDgexaacFl6hYRSXnS8UcJsL6z/sv004a8F+NqS6zTQrrwI6r6jzP+y06z/sv+o/NM1NOGvBrzVTvsY1 +a7oKEpPTmGOUKpoemEeb/poxqwmbe7ZZoHG5wqJhr1WdgaYemEebppyGkwUJm3u2P5iLwbqXp8nQmb3JP5iLwQQmMBFA4TF2RCUyLEseNolNBt +o0cszxNfXVRzRa3vQocuXOKDDdKyU/1QNHNFreWkOW4q5Keu0Eu1/dkEdd0ZkHXYieoV3oqAJHXdGZRVgQjQL1iX22AIbRugcJRHZmB0g5aDRL +Gl4pTHZa+UpFWGxKy1acQz5VAvNOU1YpTHZaBQdIOWj7Sb5nVkvEaaJJ4G77Sb5nAqdRbod+T8mLC3nYNW4S2fpqd9qqZofdD1yM3rdZvuQgYF +3oEGkh501o9OMOaA/hfWd52DVuDbdGkUJCRA41WWLZHBxtZBxOcmskXHBFKLRtxSgKY7IrVlldK8NUpTQHV608SF0xMgpjsisHTnJrJH92OCfb +duYnk3c3Ktx2ICwtdEwsXHBFKAVWFI3aQg+q1RUKWdY0B2jQogEf1AsReYAyfIHcN/yEjzhhh146wpH1M4qUvzx9k5hDeJO2RIWWRkylmwtE2p +8eRAJ4k7ZEVI7JSwNfnHopwpH1MwOWIyoD/ISPOBKChTX7enYrC5jal9lj3fLXTuMC2bznmNNX7SDRmezG0trvFNOA8ybeVPxo7hjlWeRO4wLZ +AhjlWeSA8ybeEAgdmoS2G/SHVxoIjFMdYo7zH6uMaCDQhQgdmoRaHHeAxhjDe9ETTXGAElVpwAdrZnQDc3MyDIRx8A5cdNETTXEGoFiaEvlwNB +C3co4NQ4MzD+9/wBD5cDQQAx2jXyzknJcjKKSiKwTuQ3JQZT4hTWI8ik/iOo1NAmU+IU3ZPxtDA3GM7pjHjKWnyoQ0qAhxyjlLz8tJS1rMF0pz +zAxIJ8xnRjjLIUTRyDpC9cXSQwfbpZms86RkqSum/qWZp2Wl0agTpT2qOabsqnSqBn+B1FzNgdRfz4INZ0+Fg2gdhrlezYHUXwnbew9ytXmOcM +Z4+2pLdfllaHeJX315SmXCedlmS33mZUt/m2cCxnj7asJ52WYCfIgcK7GCciwCu4RCJoqFxi4GTeL9qozdULBJ2UC5qtIvwPPPkcm1zebLBLPc +ZcBJ2UC5rdTlsSHQw6cGPdsTkALcwZRh3KGWoN3ulg/dcJUC3MGUCIQtxja2MLcxUDsgJ0s9giL0PkYmUDsgJ1A2Qy62MLcxDtm+4tBmvzrJvr +piyhK7d87ZvuLQ5sw64LHDdOXltnXd76581wGrStNvpNzTHZaO2/SFQOPrepriArHDdOW+w3DnAubMOuA70+/jA9DidoeT4juO1+Fojhu7NsR4 +wjJfeyAxO3vHLEZ2USrJbDQoym6wJx1y2yWMcl0fWHMtHUpsWh2WZW0gZl54Iw5hAiY7YVQo7179MIhU8S6fT9kt7k/LKIRMmCa4Rosjv0KxH6 +1GkBxRRyEaJzxFGL02nRSaNl8RmS4DJiLGVg8e6VEiFlVWC6VCAqAVRASgz0e9o6ZMA6vRUFmtuVLbpw5RQKY+TkOfZktBnbRGUpcNSFeSAj5O +Q5/iTYaXBn31+TRM8wQ3QfJSPfXvx0Eh7DY9QfJSPQTf7yNCce0yRcHrwkeW6dxKCJCuPZsKsJCeArLyrEuyWre7sFq8La7dwTqs6L9dqV+8Ag +Ky8qxjtfurAkuyWrcCuFm0CFW/+rSLudS0ArhZtGO1+6sBuFOjmL1sp5q/mKlXweeoAvC3d5QKsJCeBigt2UPmHMA3/BtFNZAcazKkIAoryR/g +JBOmXSCJ8l1NiAVd1YQ5XMCEB1wciKZdIIkuX3SIjmJKgxZnX37oZK9zJ2niao1sbm5Obw5ofXP4aDN7sVK9fsZPCI4LX3eWDVpGnjxYBpQEIR +JmKGoWXxzpHjMZWh5vFMofHRVvKAYD3L08Kt0oNhTf3SxM6soxiOP7MwPcvTwJ2+5Hyjvwg8fr79nDaO4vwhbwVL3f8fi+6+/ZwwbvXcbb7kfK +AxbwVL0i7Xu4ge2vtQcobAWR+GvXlzhuN5zXdzCdDn65lN138ZUobAWRBDhuN5yibU2hYWn8pCdoz6EG/WsgskZvELAldKmwoG80tP1rILIWZs +OzCRhBwmpcP9lrrj3raic7p2aiN/NoTjYvYFs6eWI9PRJgdT5OYgOvN5htojfzaNA4Qm0GuaALXGGeL2kGo6dyUab3apWm/FffpqZVAmGeL2lR +pvdqDA+pLFASpw9P4KNtTM2jMEa9n6dCypyaPC+i5zVLo+k7CKRxQD+mc0WwqmRJ16uoSwLNozBGP6ZzRQd9Q+zTL0oW02pP/cVlWWy9HWBsu1 +pjV7S+Y+mwCPbHe7Xkx1a4kcYot/bHe7WxyXq0e8p9rufIcq/2x3u1BNJBrxUAO20TejRsFdE1kxoGN971T/TdcEGx4/VFMOM+UjvgH1I33vVP +BQBSanLcVsF7x0xMfyBF/3WkQhN3BcdMTH+CSG6DOkSIhtlFbYpJRxKOB3F9GSEgg1gfnIasHTqIIh8Siz4axoVpGZyGrB0F0qvBP4CvXjwyrq +s4Pav8OdKrwT8EH5oBCdvyQgxg5+8RH5oBCQrUvxly2b3ZgxC9foaLu9yR67RVjSqw0oI4rb567a1TeUax+HAut6JpBuu0VY1GsfhwNLBfaHmv +wGX0roBjN6+nXgQQvX6GLreiaT+5clwyuoVVCFlBAJUAP9acskCknB9CNZRsQLiNJD+Iis05B4ltNG+OCRM1cIJQNHiDxTP4h4cz5omqM6iMbT +RvjrA0OJMlNuiVDzculgjrN1V0rzmXfAY7k3/NOQeJlTsgjiQ/iIqUPDx90z0/cgOUPDx9xTtKfgY7k38L5dlPL1Pd2CHi1uAhSMmOJyHEiyiH +wXMld73zI6fHahpw1U4YU93YIbPkCSMKcewvr1Dy+6oB9vCnfgFfqVoCmJUu9p+V+PJPkQryZ4977NCI2+cLjgYu9p+VAfbwp47z/aLw8oOh6u +sLpPDneKQT4SfrraApWK18KuaySSrnuAkojryiJ/bDfSaKxFMk6cbaIBjMWR5+z/seCcudIY/GsCHLv3QhP7oCIlW47CA9t8gfaLjxH1u6dCE/ +ugTWK5zHUS3ZxDUs28OiJ/bDA50hj8YxHQPGbhIWyAisBNVDwAuOPbYPZEI5EDU6KAxtMcALjj2sAfA+rATVQwORSOgnMT4eML09XzcXHA32or +0My6ohDsamHA32orQM6p1EENOVvRIGjbMV7oMwFIiECBLNhwgQvIgcDcaKMQs4i6gIyYrh/8KJcPwAiE76Eonz+KeHY/irhB/6yYHP/IiClf31 +hHD8AIgCY/irhAb2boUK5fGJWer031Wd9LhRAfQ+UUXw/1Eo7BVR/ucHUX3oDlQo7BVR5fGJWQm3RpFCt009S/VQp1eSUeFZblOkXMZUdV+tVm +9d+FUbRwdXrTwEblOkXDdTHFt0UtJW9VCnVwT4VRtHdlzITRVdzVBRXpdYBTstJieZLakrciqtKNwn1CM7LSYnA8vRnpkX01yaHdW4mwL30dqY +F9NcmgUiw7dLTMQZT7vDlFX5xNhbcsIMYgWxzsVA6s48RiLLgVUeyJ1Z+cTYWxN+1HRESdXUTZjUmFox0ZxcKc8kXW7NFFzTyZlaHsidWbvDlF +UIwbtUTMQZTyLLgVXny6VY08mZWoDLFGFnzBlizc0LZYXOnmaHzk9pBIDLFGFDyvthocmmX9PJmVoDdqrcWrqq01+iq9VjDLqq019vrppb5a9o +Wgyx31eWszpP47PjSV+0wEN+t4FC+LvZQsu97kbjvH1IT7s7SwRrCj9WCP7+V674u1Ey+zZKBULGRnRjyD95hMcgczHFSGtCxkZ0CTao7pVjp/ +mbqqjNmQmqRpY2qO6VMKb9jt+nI4kJqV6GOK2+egYut6JpBLwZatS/GXKMwF10ysPge//J+oUEFGx4f1ZpeXTobxp8DXAYfwcHPBGeDTF6l8Mv +kpYvLjmWvi7ymMEvR5sCOq+oBC8uOZbKKsOR1STXjTorhIgD1STXjWkk14yOJpKAA//BpD7MxJ8+IMU2OgQaFBGqCBfCsWkYI7AaFBGqBFGz1B +3OqcklXaNSHlGz1B0H9e1MKm/4LS2cBXUmkQO8I/z/vCKH75oj9e1MKgi+ghzR/3XS16l1L9Dnfl3MvoIc0ZuJls/sjh3OHpMixgTnfl3MhX3z +w554Ea+ReNesA4V988MNd0m/o24FuwINd0m/tW0IvQX/ddLXm2Wv2bdaWtYRaffTqXUv0ASpdS/QQ2njzNdlfsncX1PEAqVgEMPXZX7JCNWno+ +7Hrb3rr6Mp5lmedunVp6Pu17Ks9BC7JPv9GvP+CEhdMTLuY8MxHGpkMvtytjlJbRhEdWVyRmxhOkIHV608CHx9SYlZfoKCioMNf2iH8H1wjB94 +JY8gcC6Yd3f9nPN3Aw6Llo/jidSEaIfwfQRwjB941pAnf6CVMoKOnbGCB29gkiHpWfAhvlZpHqlNWR85TLwbvlZpHm9gkiEFjc1rnsXPFKMs1D +6ih9V4pyPYjqc= +`; diff --git a/src/app/features/scene/ridge/physicalSky.test.ts b/src/app/features/scene/ridge/physicalSky.test.ts index be12945e..20d5187e 100644 --- a/src/app/features/scene/ridge/physicalSky.test.ts +++ b/src/app/features/scene/ridge/physicalSky.test.ts @@ -1,10 +1,17 @@ import { describe, expect, it } from 'vitest'; +import { FALLBACK_VIEW } from './view'; +import { ELSEWHERE_VIEW } from './manifest.fixture'; +import { sunAt } from './sunAt'; +import { momentFor } from './skyMoment'; import { makePhysicalSky, paintSky } from './physicalSky'; -import { skyBackdrop } from '../skyState'; -import type { FixedSkyState } from '../skyBand'; +import { sunOfBand } from './skyTestkit'; +import { ridgeDrawn } from '../skyForState'; +import type { FixedSkyState } from './skyMoment'; +import { windowFor } from './view'; +import type { PhysicalSky } from './physicalSky'; // The Aqua method on tonemapped pixels: paint the sky the way the host canvas does and measure the WCAG luminance of every 8-bit -// texel, against the bounds the page text was checked against (`skyBackdrop`, 4.5:1). Over the weather, the day of the year, and +// texel, against the display range the sky was fitted to (`ridgeDrawn`). Over the weather, the day of the year, and // viewports of different shape (the fit is made on one 16:9 grid and the paint on another). const lin = (v: number): number => { const c = v / 255; @@ -13,6 +20,13 @@ const lin = (v: number): number => { const luma = (d: Uint8ClampedArray, i: number): number => 0.2126 * lin(d[i]) + 0.7152 * lin(d[i + 1]) + 0.0722 * lin(d[i + 2]); +const camera = (sky: PhysicalSky, w: number, h: number) => windowFor(sky.view, w, h).camera; +/** The camera of the viewport turned to face the sun, so the disc's colour and floor are measured wherever the sun is. */ +const facingSun = (sky: PhysicalSky, w: number, h: number) => ({ + ...camera(sky, w, h), + azimuthDeg: sky.sun.azimuth, +}); + const DAYS = ['2026-03-20', '2026-06-21', '2026-09-23', '2026-12-21']; const WEATHER = [0, 0.3, 0.55, 0.75, 1]; const VIEWPORTS: [number, number][] = [ @@ -23,17 +37,17 @@ const VIEWPORTS: [number, number][] = [ ]; describe.each(['day', 'dusk', 'night'] as FixedSkyState[])( - 'the %s sky stays inside its backdrop bounds', + 'the %s sky stays inside its fitted display range', (state) => { it('over weather, season and viewport shape', () => { - const b = skyBackdrop(state); + const b = ridgeDrawn(state); let lo = 2; let hi = -1; for (const day of DAYS) { for (const w of WEATHER) { - const sky = makePhysicalSky(state, new Date(`${day}T10:40:00Z`), w); + const sky = makePhysicalSky(sunOfBand(FALLBACK_VIEW.place, state, new Date(`${day}T10:40:00Z`)), w, FALLBACK_VIEW); for (const [vw, vh] of VIEWPORTS) { - const px = paintSky(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) { const l = luma(px.data, i); lo = Math.min(lo, l); @@ -51,8 +65,12 @@ describe.each(['day', 'dusk', 'night'] as FixedSkyState[])( describe('weather in the sky', () => { 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 clear = paintSky(makePhysicalSky('day', at, 0), 640, 360); - const grey = paintSky(makePhysicalSky('day', at, 0.7), 640, 360); + const paint = (w: number) => { + const sky = makePhysicalSky(sunOfBand(FALLBACK_VIEW.place, 'day', at), w, FALLBACK_VIEW); + return paintSky(sky, 640, 360, camera(sky, 640, 360)); + }; + const clear = paint(0); + const grey = paint(0.7); const spread = (p: typeof clear) => { let lo = 2; let hi = -1; @@ -73,44 +91,47 @@ describe('weather in the sky', () => { }); describe('the sun disc', () => { - it('keeps the display floor the dark link was fitted to, at every hour it is drawn', () => { - const lin = (c: number) => - c / 255 <= 0.04045 ? c / 255 / 12.92 : ((c / 255 + 0.055) / 1.055) ** 2.4; - let drawn = 0; - for (const state of ['day', 'dusk'] as FixedSkyState[]) { - for (let m = 0; m < 24 * 60; m += 10) { - const d = paintSky( - makePhysicalSky(state, new Date(Date.UTC(2026, 10, 11, 0, m)), 0), - 1280, - 720 - ).sunDisc; - if (!d) continue; - drawn += 1; - expect( - 0.2126 * lin(d.rgb[0]) + 0.7152 * lin(d.rgb[1]) + 0.0722 * lin(d.rgb[2]) - ).toBeGreaterThanOrEqual(0.4744); - } - } - expect(drawn).toBeGreaterThan(0); - }); - const noon = new Date('2026-11-11T10:40:00Z'); // 21 degrees: in June the noon sun is above the top of the image + 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 it('is drawn by the host, in a clear sky by day, white with the sun high', () => { - const d = paintSky(makePhysicalSky('day', noon, 0), 1280, 720).sunDisc; + const sky = makePhysicalSky(sunOfBand(FALLBACK_VIEW.place, 'day', noon), 0, FALLBACK_VIEW); + const d = disc(sky).sunDisc; expect(d).toBeDefined(); expect(d!.x).toBeGreaterThan(0); expect(d!.x).toBeLessThan(1); expect(d!.y).toBeGreaterThan(0); - expect(d!.y).toBeLessThan(0.78); // above the horizon line + expect(d!.y).toBeLessThan(camera(sky, 1280, 720).horizonAt); // above the horizon line expect(d!.alpha).toBe(1); expect(Math.min(...d!.rgb)).toBeGreaterThan(150); // a warm white at 21 degrees }); it('is hidden by overcast and absent at night', () => { - expect(paintSky(makePhysicalSky('day', noon, 0.7), 1280, 720).sunDisc).toBeUndefined(); - expect(paintSky(makePhysicalSky('night', noon, 0), 1280, 720).sunDisc).toBeUndefined(); + expect(disc(makePhysicalSky(sunOfBand(FALLBACK_VIEW.place, 'day', noon), 0.7, 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', () => { - const d = paintSky(makePhysicalSky('dusk', noon, 0), 1280, 720).sunDisc; + it('is orange-tinted low in the sky (golden hour, 4 degrees up)', () => { + 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!.rgb[0]).toBeGreaterThan(d!.rgb[2]); }); }); + +describe('the sky is made from the View it is given', () => { + const NOW = new Date('2026-06-21T10:40:00Z'); + 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", () => { + const sky = makePhysicalSky(sunOfBand(ELSEWHERE_VIEW.place, 'day', NOW), 0, ELSEWHERE_VIEW); + expect(sky.view).toBe(ELSEWHERE_VIEW); + expect(sky.sun).toEqual(sunOfBand(ELSEWHERE_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); + }); + + 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(sunOfBand(FALLBACK_VIEW.place, 'day', NOW), 0, FALLBACK_VIEW); + const b = makePhysicalSky(sunOfBand(sameSpotOtherCamera.place, 'day', NOW), 0, sameSpotOtherCamera); + expect(b.sun).toEqual(a.sun); + expect(b.stops).not.toEqual(a.stops); + }); +}); diff --git a/src/app/features/scene/ridge/physicalSky.ts b/src/app/features/scene/ridge/physicalSky.ts index 0e034416..7f8f5f24 100644 --- a/src/app/features/scene/ridge/physicalSky.ts +++ b/src/app/features/scene/ridge/physicalSky.ts @@ -1,30 +1,32 @@ -// The ridge scene's sky: Vienna'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 // grid, so resizing the window repaints the same sky. `paintSky` is per-texel lookups only. -import type { FixedSkyState } from '../skyBand'; +import { skyBand } from './skyMoment'; +import type { FixedSkyState } from './skyMoment'; import { bakeAtmosphere } from './earthAtmosphere'; import type { Atmosphere } from './earthAtmosphere'; -import { - domeSize, - HORIZON_AT, - renderDome, - SUN_RADIUS, - sunOnScreen, - viewFor, - VFOV_DEG, -} from './skyDome'; -import type { Dome, DomeView } from './skyDome'; +import { domeSize, renderDome, SUN_RADIUS, sunOnScreen } from './skyDome'; +import type { Dome } from './skyDome'; import type { Srgb } from './skyColour'; -import { display8, fitDisplay, holdBudget, MARGIN } from './toneMap'; +import { display8, fitDisplay } from './toneMap'; import type { Display, Fit } from './toneMap'; -import { sunForState, VIENNA } from './vienna'; -import type { SunSample } from './vienna'; +import { moonAt } from './nightSky'; +import type { MoonSample, NightLight } from './nightSky'; +import type { SunSample } from './sunAt'; +import { windowFor } from './view'; +import type { Camera, View } from './view'; import { weatherOf } from './weather'; import type { Weather } from './weather'; export interface PhysicalSky { state: FixedSkyState; + /** Where the observer stands and where the planes look: the camera of any viewport is `windowFor(view, w, h).camera`. */ + view: View; sun: SunSample; + /** The moon over the place at the sun's moment (`sun.time`): the night's key light, and a body in any sky it is above the horizon of. */ + moon: MoonSample; + /** What lights the sky besides the sun: at night, the moon above the horizon with its own atmosphere bake. */ + night: NightLight; weather: Weather; atm: Atmosphere; /** The display fitted to this sky's budget. */ @@ -35,7 +37,7 @@ export interface PhysicalSky { bakeMs: number; } -const CANON = { w: 64, h: 36, aspect: 16 / 9 }; +const CANON = { w: 64, h: 36 }; const clock = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now()); @@ -53,29 +55,49 @@ 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)]; } -export function makePhysicalSky( - state: FixedSkyState, - now: Date, - weatherValue: number -): PhysicalSky { +/** 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. */ +export function makePhysicalSky(sun: SunSample, weatherValue: number, view: View): PhysicalSky { const t0 = clock(); - const sun = sunForState(state, now); + const state = skyBand(sun.elevation); const weather = weatherOf(weatherValue); const atm = bakeAtmosphere({ sunElevationDeg: sun.elevation, mieScale: weather.mieScale, - observerKm: VIENNA.altitudeKm, + observerKm: view.place.altitudeKm, }); - const dome = renderDome(atm, sun, viewFor(sun, CANON.aspect), CANON.w, CANON.h, weather.cover); + // A 16:9 viewport: the camera's fov and horizon fraction do not depend on its size, only on its shape. + const { camera } = windowFor(view, CANON.w, CANON.h); + // The moon is the night's light: its own bake of the same atmosphere, for a light at its elevation (the transmittance and the + // multiple-scattering tables do not depend on it, but the bake is one function). Only in the night state, and only above -2 degrees. + const moon = moonAt(view.place, sun.time); + const night: NightLight = + state === 'night' && moon.elevation > -2 + ? { + moon: { + azimuth: moon.azimuth, + elevation: moon.elevation, + ratio: moon.ratio, + atm: bakeAtmosphere({ + sunElevationDeg: moon.elevation, + mieScale: weather.mieScale, + observerKm: view.place.altitudeKm, + }), + }, + } + : {}; + const dome = renderDome(atm, sun, camera, CANON.w, CANON.h, weather.cover, night); const fit = fitDisplay(state, dome.hdr, dome.meanLuma); const at = (f: number) => rowMean(dome, fit.display, Math.round(f * CANON.h)); return { state, + view, sun, + moon, + night, weather, atm, fit, - stops: { top: at(0.02), mid: at(0.5), horizon: at(HORIZON_AT) }, + stops: { top: at(0.02), mid: at(0.5), horizon: at(camera.horizonAt) }, bakeMs: clock() - t0, }; } @@ -86,19 +108,18 @@ export interface SkyPixels { /** RGBA, 8 bit. */ data: Uint8ClampedArray; dome: Dome; - view: DomeView; + camera: Camera; /** The sun's disc for the host to draw on the upscaled canvas (it is smaller than a texel): place as fractions of the image, colour, radius in fractions of the height, opacity after the cloud. */ sunDisc?: { x: number; y: number; rgb: Srgb; radius: number; alpha: number }; } -/** The sky for a viewport, as a small RGBA grid the host canvas upscales smoothly. */ -export function paintSky(p: PhysicalSky, cssW: number, cssH: number): SkyPixels { +/** The sky for a viewport seen through `camera` (`windowFor(p.view, cssW, cssH).camera`), as a small RGBA grid the host canvas upscales smoothly. */ +export function paintSky(p: PhysicalSky, cssW: number, cssH: number, camera: Camera): SkyPixels { const { w, h } = domeSize(cssW, cssH); - const view = viewFor(p.sun, cssW / cssH); - const dome = renderDome(p.atm, p.sun, view, w, h, p.weather.cover); + const dome = renderDome(p.atm, p.sun, camera, w, h, p.weather.cover, p.night); const data = new Uint8ClampedArray(w * h * 4); const out = [0, 0, 0]; - const display = holdBudget(p.state, dome.hdr, p.fit.display); + const display = p.fit.display; for (let i = 0; i < w * h; i += 1) { display8(dome.hdr[i * 3], dome.hdr[i * 3 + 1], dome.hdr[i * 3 + 2], display, out); data[i * 4] = out[0]; @@ -106,11 +127,9 @@ export function paintSky(p: PhysicalSky, cssW: number, cssH: number): SkyPixels data[i * 4 + 2] = out[2]; data[i * 4 + 3] = 255; } - return { w, h, data, dome, view, sunDisc: sunDisc(p, view) }; + return { w, h, data, dome, camera, sunDisc: sunDisc(p, camera) }; } -/** The luma the disc must keep: the day/dusk floor of toneMap's budget. */ -const DISC_FLOOR = 0.4744 + MARGIN; const smooth01 = (a: number, b: number, v: number): number => { const t = Math.min(1, Math.max(0, (v - a) / (b - a))); return t * t * (3 - 2 * t); @@ -120,25 +139,18 @@ const smooth01 = (a: number, b: number, v: number): number => { * The sun's disc: always brighter than the display's white, so what is left of it is its colour, the air's transmittance to the sun * normalised to its strongest channel (white high up, orange near the horizon). Thick cloud hides it. */ -function sunDisc(p: PhysicalSky, view: DomeView): SkyPixels['sunDisc'] { - const at = sunOnScreen(p.sun, view); +function sunDisc(p: PhysicalSky, camera: Camera): SkyPixels['sunDisc'] { + const at = sunOnScreen(p.sun, camera); const alpha = 1 - smooth01(0.1, 0.6, p.weather.cover); if (!at || alpha <= 0) return undefined; const trans = [0, 0, 0]; p.atm.transmittanceToSpace(Math.max(Math.sin((p.sun.elevation * Math.PI) / 180), 0), trans); const top = Math.max(...trans, 1e-9); const rgb = trans.map((t) => Math.round(255 * (t / top) ** 0.6)); - // The disc sits on the sky, so it keeps the display floor the dark link was fitted to: mix toward white until it does. - const lin = (c: number): number => - c / 255 <= 0.04045 ? c / 255 / 12.92 : ((c / 255 + 0.055) / 1.055) ** 2.4; - const luma = (c: number[]): number => - 0.2126 * lin(c[0]) + 0.7152 * lin(c[1]) + 0.0722 * lin(c[2]); - for (let m = 0; luma(rgb) < DISC_FLOOR && m < 40; m += 1) - for (let i = 0; i < 3; i += 1) rgb[i] = Math.round(rgb[i] + (255 - rgb[i]) * 0.1); return { ...at, rgb: rgb as unknown as Srgb, - radius: (SUN_RADIUS * 180) / Math.PI / VFOV_DEG, + radius: (SUN_RADIUS * 180) / Math.PI / camera.vfovDeg, alpha, }; } diff --git a/src/app/features/scene/ridge/ridgeAssets.test.ts b/src/app/features/scene/ridge/ridgeAssets.test.ts new file mode 100644 index 00000000..4003f9ea --- /dev/null +++ b/src/app/features/scene/ridge/ridgeAssets.test.ts @@ -0,0 +1,317 @@ +// The committed baked set under public/ridge: what the baker wrote is what ships, within the budget the baker itself refuses on (export.py MAX_CARDS, +// TILE_BYTES_MAX, PLACE_BYTES_MAX, RESIDENT_BYTES_MAX). Reads with node fs. The gate reads each tile file's own bytes, not the manifest's claims about +// them: the WebP container is walked and its stated dimensions (VP8X canvas, VP8 / VP8L frame header) must equal the tile's width (tile_w + 2 apron) and +// its band height, which the resident budget is computed from; and the bake id is re-derived from the tile bytes as the baker derives it (tile-major, then +// card, colour then geometry), so any corruption of a tile, same length or not, fails. No pixel decoder is in the tree; the baker's own check decodes pixels. +import { execFileSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'; +import { join, sep } from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { MAX_CARDS, parseIndex, parseManifest } from './manifest'; +import { runTiles } from './ring'; +import { groundRowsNeeded, HFOV_MAX_DEG } from './view'; + +/** The same constants as scripts/ridge-bake/export.py. */ +export const TILE_BYTES_MAX = 235_000; +export const PLACE_BYTES_MAX = 7_500_000; +export const RESIDENT_BYTES_MAX = 20_000_000; +/** As ridge.py NEAR_CLIP_M: the far march's first sample; card 0's distance_m is measured at or beyond it (the near ground under it is not measured). */ +export const NEAR_CLIP_M = 500; + +interface WireFile { + file: string; + bytes: number; +} +interface WireTile { + top: number; + h: number; + distance_m: number; + colour: WireFile; + geometry: WireFile; +} +export interface WireManifest { + schema: number; + bake_id: string; + view: { ring_w: number; tile_w: number; tiles: number; apron: number; plane_h: number; horizon_row: number }; + camera: { r_max_m: number; r_max_forward_m: number }; + cards: unknown[]; + tiles: (WireTile | null)[][]; +} + +const files = (e: WireTile | null): WireFile[] => (e ? [e.colour, e.geometry] : []); +const bytesOf = (row: (WireTile | null)[]): number => + row.flatMap(files).reduce((a, f) => a + f.bytes, 0); + +/** + * N and the lit bytes of the worst run of N consecutive tiles (4 bytes x (tile_w + 2) x band rows, per card), cyclic: the same N and the same sum as + * export.py `run_tiles` and `resident_bytes`, recomputed from the manifest alone, at the larger of the two offsets the bake ships. The nearest distance is card 0's smallest over the tiles. + */ +export function residentBytes(m: WireManifest): { n: number; bytes: number } { + const { tiles, tile_w } = m.view; + const rmin = Math.min(...m.tiles.flatMap((row) => (row[0] ? [row[0].distance_m] : []))); + const n = runTiles({ tiles }, HFOV_MAX_DEG, Math.max(m.camera.r_max_m, m.camera.r_max_forward_m), rmin); + const per = m.tiles.map((row) => row.reduce((a, e) => a + (e ? 4 * (tile_w + 2) * e.h : 0), 0)); + let worst = 0; + for (let t = 0; t < tiles; t += 1) { + let sum = 0; + for (let k = 0; k < n; k += 1) sum += per[(t + k) % tiles]; + worst = Math.max(worst, sum); + } + return { n, bytes: worst }; +} + +/** Why a manifest breaks the size gate, or undefined: too many cards, a tile or the place too many bytes, or the resident run lit past the budget. */ +export function sizeGate(m: WireManifest): string | undefined { + if (m.cards.length > MAX_CARDS) return `${m.cards.length} cards, above ${MAX_CARDS}`; + const tileBytes = m.tiles.map(bytesOf); + const worst = tileBytes.findIndex((b) => b > TILE_BYTES_MAX); + if (worst >= 0) return `tile ${worst} is ${tileBytes[worst]} bytes, above ${TILE_BYTES_MAX}`; + const total = tileBytes.reduce((a, b) => a + b, 0); + if (total > PLACE_BYTES_MAX) return `the place is ${total} bytes, above ${PLACE_BYTES_MAX}`; + const res = residentBytes(m); + return res.bytes > RESIDENT_BYTES_MAX + ? `${res.n} consecutive tiles light to ${res.bytes} bytes, above ${RESIDENT_BYTES_MAX}` + : undefined; +} + +/** Why `b` is not the WebP of `w` x `h` pixels, or undefined: the RIFF container is walked, so a cut or padded file and a changed frame header fail. */ +export function webpFault(b: Uint8Array, w: number, h: number): string | undefined { + const u32 = (o: number) => (b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)) >>> 0; + const u24 = (o: number) => b[o] | (b[o + 1] << 8) | (b[o + 2] << 16); + const tag = (o: number) => String.fromCharCode(b[o], b[o + 1], b[o + 2], b[o + 3]); + if (b.length < 20 || tag(0) !== 'RIFF' || tag(8) !== 'WEBP') return 'not a RIFF WEBP'; + if (u32(4) + 8 !== b.length) return `RIFF size ${u32(4)} does not fit a ${b.length} byte file`; + const dims: string[] = []; + let seen = 0; + let o = 12; + while (o < b.length) { + if (o + 8 > b.length) return 'a chunk header runs past the file'; + const id = tag(o); + const len = u32(o + 4); + const body = o + 8; + if (body + len > b.length) return `chunk ${id} runs past the file`; + if (id === 'VP8X') dims.push(`${u24(body + 4) + 1}x${u24(body + 7) + 1}`); + if (id === 'VP8 ') { + if (b[body + 3] !== 0x9d || b[body + 4] !== 0x01 || b[body + 5] !== 0x2a) + return 'VP8 start code missing'; + dims.push( + `${(b[body + 6] | (b[body + 7] << 8)) & 0x3fff}x${ + (b[body + 8] | (b[body + 9] << 8)) & 0x3fff + }` + ); + seen += 1; + } + if (id === 'VP8L') { + if (b[body] !== 0x2f) return 'VP8L signature missing'; + const bits = u32(body + 1); + dims.push(`${(bits & 0x3fff) + 1}x${((bits >>> 14) & 0x3fff) + 1}`); + seen += 1; + } + o = body + len + (len & 1); + } + if (o !== b.length) return 'the chunks do not tile the file'; + if (seen !== 1) return `${seen} bitstream chunks`; + const bad = dims.find((d) => d !== `${w}x${h}`); + return bad ? `states ${bad}, the manifest ${w}x${h}` : undefined; +} + +const BLANK_ID = '0'.repeat(12); + +/** The manifest text as the baker hashed it: the bytes as committed, with the bake_id value blanked (an id cannot hash itself). */ +export function blankedManifest(text: string, bakeId: string): string { + return text.replace(`"bake_id": "${bakeId}"`, `"bake_id": "${BLANK_ID}"`); +} + +/** The baker's bake id (export.py `bake_id`): first 12 hex of sha256 over the blanked manifest text, then the tile files, tile-major then card, colour then geometry (a card absent from a tile writes none): the id addresses the whole bake. */ +export function bakeIdOf(blankManifest: string, tileFiles: Uint8Array[]): string { + const h = createHash('sha256'); + h.update(blankManifest, 'utf8'); + tileFiles.forEach((b) => h.update(b)); + return h.digest('hex').slice(0, 12); +} + +const ROOT = join(process.cwd(), 'public', 'ridge'); +const readJson = (p: string): unknown => JSON.parse(readFileSync(p, 'utf8')); +const index = parseIndex(readJson(join(ROOT, 'index.json'))); +const dirs = Object.entries(index.places); + +describe('the committed ridge assets', () => { + it('ship at least one place, and the index default is one of them', () => { + expect(dirs.length).toBeGreaterThan(0); + expect(index.places[index.default]).toBeDefined(); + }); + + dirs.forEach(([id, dir]) => { + describe(`${id} (${dir})`, () => { + const raw = readJson(join(ROOT, dir, 'manifest.json')) as WireManifest; + const read = (f: WireFile) => readFileSync(join(ROOT, dir, f.file)); + const all = raw.tiles.flatMap((row) => row.flatMap(files)); + + it('is schema 3, parses, and its directory ends in its bake id', () => { + expect(raw.schema).toBe(3); + expect(() => parseManifest(raw, `${dir}/`)).not.toThrow(); + 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 tile file, at the length the manifest states', () => { + all.forEach((f) => { + expect(statSync(join(ROOT, dir, f.file)).size, f.file).toBe(f.bytes); + }); + }); + + it('decodes every tile file as the WebP of tile_w + 2 apron columns by the band height the manifest states', () => { + const w = raw.view.tile_w + 2 * raw.view.apron; + raw.tiles.forEach((row) => + row.forEach((e) => + files(e).forEach((f) => { + expect(webpFault(read(f), w, (e as WireTile).h), f.file).toBeUndefined(); + }) + ) + ); + }); + + it('holds the manifest and the bytes its bake id was made from', () => { + const ordered = raw.tiles.flatMap((row) => row.flatMap(files)).map(read); + const text = blankedManifest(readFileSync(join(ROOT, dir, 'manifest.json'), 'utf8'), raw.bake_id); + expect(text).toContain(`"bake_id": "${BLANK_ID}"`); + expect(bakeIdOf(text, ordered)).toBe(raw.bake_id); + expect(bakeIdOf(text.replace('"r_max_forward_m"', '"r_max_forward_m "'), ordered), 'a changed manifest keeps its id').not.toBe(raw.bake_id); + }); + + it('is checked out as committed: git converts no line end of the manifest, the index or a tile, so the bytes served are the bytes the id was made from', () => { + const attr = (file: string) => + execFileSync('git', ['check-attr', 'text', 'eol', '--', file], { encoding: 'utf8' }).replace(/\r/g, '').trim().split('\n'); + const tile = files(raw.tiles[0].find((e) => e)!)[0].file; + [`public/ridge/${dir}/manifest.json`, 'public/ridge/index.json', `public/ridge/${dir}/${tile}`].forEach((f) => + expect(attr(f), f).toEqual([`${f}: text: unset`, `${f}: eol: unspecified`]) + ); + expect(readFileSync(join(ROOT, dir, 'manifest.json'), 'utf8')).not.toContain('\r'); + }); + + it('keeps the place inside the tile, place and resident budgets, computed from the manifest alone', () => { + expect(sizeGate(raw)).toBeUndefined(); + expect(residentBytes(raw).n).toBeLessThanOrEqual(raw.view.tiles); + }); + + it('keeps the ground rows the runtime needs under the horizon and nothing nearer than the near clip: card 0 stands at or beyond 500 m in every tile', () => { + expect(raw.view.plane_h - raw.view.horizon_row).toBeGreaterThanOrEqual(groundRowsNeeded(raw.view.plane_h) - 1e-6); + raw.tiles.forEach((row) => row[0] && expect(row[0].distance_m).toBeGreaterThanOrEqual(NEAR_CLIP_M)); + }); + + it('carries the offset bound and a distance for every tile a card holds', () => { + expect(raw.camera.r_max_m).toBeGreaterThan(0); + expect(raw.camera.r_max_forward_m).toBeGreaterThanOrEqual(raw.camera.r_max_m); + raw.tiles.forEach((row) => row.forEach((e) => e && expect(e.distance_m).toBeGreaterThan(0))); + raw.cards.forEach((_, i) => expect(raw.tiles.some((row) => row[i] !== null)).toBe(true)); + }); + }); + }); + + it('holds no file a manifest does not name', () => { + const named = new Set(['index.json']); + dirs.forEach(([, dir]) => { + named.add(`${dir}/manifest.json`); + (readJson(join(ROOT, dir, 'manifest.json')) as WireManifest).tiles + .flatMap((row) => row.flatMap(files)) + .forEach((f) => named.add(`${dir}/${f.file}`)); + }); + const onDisk = readdirSync(ROOT, { recursive: true, withFileTypes: true }) + .filter((e) => e.isFile()) + .map((e) => + join(e.parentPath, e.name) + .slice(ROOT.length + 1) + .split(sep) + .join('/') + ); + expect(onDisk.filter((f) => !named.has(f))).toEqual([]); + expect([...named].filter((f) => !existsSync(join(ROOT, f)))).toEqual([]); + }); +}); + +describe('the tile gates refuse a tile that is not what the manifest says', () => { + const dir = Object.values(index.places)[0]; + const manifest = readJson(join(ROOT, dir, 'manifest.json')) as WireManifest; + const e = manifest.tiles.map((row) => row[1]).find((x) => x) as WireTile; + const real = readFileSync(join(ROOT, dir, e.geometry.file)); + const { h } = e; + const w = manifest.view.tile_w + 2 * manifest.view.apron; + + it('accepts the real tile at its size', () => { + expect(webpFault(real, w, h)).toBeUndefined(); + }); + it("refuses a manifest that lies about the tile's size, and a file cut short or padded", () => { + expect(webpFault(real, w, h + 1)).toMatch(/states/); + expect(webpFault(real, manifest.view.tile_w, h)).toMatch(/states/); // a tile without its apron + expect(webpFault(real.subarray(0, real.length - 1), w, h)).toBeDefined(); + expect(webpFault(Buffer.concat([real, Buffer.from([0])]), w, h)).toBeDefined(); + }); + it('refuses bytes that are not a WebP', () => { + expect(webpFault(Buffer.from('not a webp, but long enough to try'), w, h)).toMatch(/RIFF/); + }); + it('re-derives a different bake id from a tile with the same length and 8 bytes overwritten', () => { + const bad = Buffer.from(real); + bad.fill(0xab, 100, 108); + expect(bad.length).toBe(real.length); + expect(bakeIdOf('m', [bad])).not.toBe(bakeIdOf('m', [real])); + }); + it('derives the id over the files in the order the baker writes them: any other order is another id', () => { + const [a, b, c] = [Buffer.from('t0-c0-colour'), Buffer.from('t0-c0-geometry'), Buffer.from('t1-c0-colour')]; + const want = createHash('sha256').update('manifest').update(a).update(b).update(c).digest('hex').slice(0, 12); + expect(bakeIdOf('manifest', [a, b, c])).toBe(want); + expect(bakeIdOf('manifest', [a, c, b])).not.toBe(want); + expect(bakeIdOf('manifest', [b, a, c])).not.toBe(want); + expect(bakeIdOf('manifest!', [a, b, c])).not.toBe(want); + }); +}); + +describe('sizeGate', () => { + const entry = (bytes: number, h = 100): WireTile => ({ + top: 0, + h, + distance_m: 1000, + colour: { file: 'c.webp', bytes: Math.floor(bytes / 2) }, + geometry: { file: 'g.webp', bytes: bytes - Math.floor(bytes / 2) }, + }); + const ring = (tiles: number, perTile: number, h = 100, cards = 1): WireManifest => ({ + schema: 3, + bake_id: 'x', + view: { ring_w: 6400, tile_w: 6400 / tiles, tiles, apron: 2, plane_h: 600, horizon_row: 357 }, + camera: { r_max_m: 50, r_max_forward_m: 50 }, + cards: Array.from({ length: cards }, () => ({})), + tiles: Array.from({ length: tiles }, () => + Array.from({ length: cards }, () => entry(perTile / cards, h)) + ), + }); + + it('passes a tile at the byte cap and fails one a byte over', () => { + expect(sizeGate(ring(32, 7000, 10))).toBeUndefined(); + const at = ring(32, 1, 10); + expect(sizeGate({ ...at, tiles: [[entry(TILE_BYTES_MAX, 10)], ...at.tiles.slice(1)] })).toBeUndefined(); + expect(sizeGate({ ...at, tiles: [[entry(TILE_BYTES_MAX + 1, 10)], ...at.tiles.slice(1)] })).toMatch( + /tile 0 is 235001 bytes/ + ); + }); + + it('passes a place at the byte cap and fails one a byte over', () => { + // 32 tiles at 234 375 bytes is exactly 7 500 000; one byte more on one tile is over. + const at = ring(32, PLACE_BYTES_MAX / 32, 10); + expect(sizeGate(at)).toBeUndefined(); + const over = { ...at, tiles: [[entry(PLACE_BYTES_MAX / 32 + 1, 10)], ...at.tiles.slice(1)] }; + expect(sizeGate(over)).toMatch(/the place is 7500001 bytes/); + }); + + it('fails a seventh card, and a ring that lights past the resident budget by a row', () => { + expect(sizeGate({ ...ring(32, 1, 10), cards: Array(7).fill({}) })).toMatch(/7 cards/); + const n = residentBytes(ring(32, 1, 100)).n; + const rows = Math.floor(RESIDENT_BYTES_MAX / (n * 4 * 202)); // the most rows N tiles can hold lit within the budget + expect(sizeGate(ring(32, 1, rows))).toBeUndefined(); + expect(sizeGate(ring(32, 1, rows + 1))).toMatch(/consecutive tiles light to/); + }); +}); diff --git a/src/app/features/scene/ridge/ridgeBake.test.ts b/src/app/features/scene/ridge/ridgeBake.test.ts deleted file mode 100644 index 8ce91f41..00000000 --- a/src/app/features/scene/ridge/ridgeBake.test.ts +++ /dev/null @@ -1,404 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { BakeParams, bakeSlice, faceLight, layerPaint, sunDirection } from './ridgeBake'; -import { SKY_BAND } from '../skyBand'; -import { ridgeSkyFor } from '../skyForState'; -import { LACUNARITY, LAYERS, profile } from './ridgeWorld'; -import { skyColours, SkyColours } from './skyColour'; - -const SKY: SkyColours = { ...skyColours(), sunAzimuth: 0.3 }; // sun toward +x -const PERIOD = 400; -const VIEW_H = 800; -const BAND = 480; - -const params = ( - li: number, - px0: number, - cols: number, - over: Partial = {} -): BakeParams => ({ - spec: LAYERS[li], - sky: SKY, - period: PERIOD, - scale: 1, - viewH: VIEW_H, - rows: BAND, - bandH: BAND, - px0, - cols, - ...over, -}); - -function bake(p: BakeParams, slices: number[] = [p.cols]): Uint8ClampedArray { - const out = new Uint8ClampedArray(p.cols * p.rows * 4); - const paint = layerPaint(p.spec, p.sky); - let c = 0; - for (const n of slices) { - bakeSlice(out, p, paint, c, Math.min(p.cols, c + n)); - c += n; - } - return out; -} - -const lum = (d: Uint8ClampedArray, cols: number, x: number, y: number) => { - const o = (y * cols + x) * 4; - return 0.2126 * d[o] + 0.7152 * d[o + 1] + 0.0722 * d[o + 2]; -}; -/** First row of column x whose alpha is full. */ -const solidRow = (d: Uint8ClampedArray, cols: number, x: number) => { - let y = 0; - while (y < BAND && d[(y * cols + x) * 4 + 3] < 255) y += 1; - return y; -}; - -describe('the field is a function of world-x', () => { - it('is deterministic, and defined and bounded at any world-x', () => { - for (const spec of LAYERS) { - for (const t of [-40.3, 0, 0.5, 17.77, 5000.123]) { - expect(profile(spec, t)).toBe(profile(spec, t)); - expect(profile(spec, t)).toBeGreaterThanOrEqual(0); - expect(profile(spec, t)).toBeLessThanOrEqual(1); - } - } - }); - - it('has no repeat at the old period (1 viewport) or its multiples: the profile differs from itself shifted', () => { - for (const spec of LAYERS) { - for (const lag of [1, 2, 3, 0.5]) { - let diff = 0; - for (let i = 0; i < 400; i += 1) - diff += Math.abs(profile(spec, i / 100) - profile(spec, i / 100 + lag)); - expect(diff / 400).toBeGreaterThan(0.04); - } - } - }); - - it('the same world column bakes to the same pixels whichever chunk or slice paints it', () => { - for (const li of [0, 3]) { - const whole = bake(params(li, 1000, 200)); - const sliced = bake(params(li, 1000, 200), [37, 64, 1000]); - expect(Array.from(sliced)).toEqual(Array.from(whole)); - // A chunk starting 120 columns later sees the same pixels for the columns it shares. - const shifted = bake(params(li, 1120, 80)); - for (const x of [0, 17, 79]) { - for (const y of [0, 100, 300, BAND - 1]) { - const a = (y * 200 + 120 + x) * 4; - const b = (y * 80 + x) * 4; - expect(Array.from(shifted.slice(b, b + 4))).toEqual(Array.from(whole.slice(a, a + 4))); - } - } - } - }); - - it('is continuous across a chunk seam: the crest steps no more at the seam than elsewhere', () => { - const chunk = Math.round(PERIOD * 1.2); - for (const li of [0, 1, 2, 3]) { - const p = params(li, chunk - 40, 80); - const d = bake(p); - let worst = 0; - for (let x = 1; x < 80; x += 1) - worst = Math.max(worst, Math.abs(solidRow(d, 80, x) - solidRow(d, 80, x - 1))); - const seam = Math.abs(solidRow(d, 80, 40) - solidRow(d, 80, 39)); - expect(seam).toBeLessThanOrEqual(Math.max(worst, 1)); - // and the seam columns equal a chunk baked from the other side - const other = bake(params(li, chunk - 40, 80, { cols: 80 })); - expect(Array.from(other)).toEqual(Array.from(d)); - } - }); -}); - -describe('shading from the slope normal', () => { - const sun = sunDirection(SKY); - - it('the sun is toward +x for azimuth 0.3', () => { - expect(sun[0]).toBeGreaterThan(0.5); - }); - - it('a face looking at the sun is lit more than one looking away', () => { - // slope < 0: the crest falls toward +x, so the face looks at +x, at the sun. - for (const s of [0.2, 0.6, 1.5]) expect(faceLight(-s, sun)).toBeGreaterThan(faceLight(s, sun)); - expect(faceLight(1.5, sun)).toBeLessThan(0.2); - expect(faceLight(-1.5, sun)).toBeGreaterThan(0.6); - }); - - it('in the baked pixels the lit side is brighter than the shadow side', () => { - for (const li of [0, 1, 2]) { - const cols = 900; - const p = params(li, 0, cols); - const d = bake(p); - const slope = (x: number) => (solidRow(d, cols, x - 1) - solidRow(d, cols, x + 1)) / 2; // rows up per column - const litX: number[] = []; - const shadeX: number[] = []; - for (let x = 2; x < cols - 2; x += 1) { - if (slope(x) < -0.8) litX.push(x); - if (slope(x) > 0.8) shadeX.push(x); - } - expect(litX.length).toBeGreaterThan(5); - expect(shadeX.length).toBeGreaterThan(5); - const mean = (xs: number[]) => - xs.reduce((a, x) => a + lum(d, cols, x, solidRow(d, cols, x) + 12), 0) / xs.length; - expect(mean(litX)).toBeGreaterThan(mean(shadeX)); - } - }); - - it('a lit crest rim: the crest pixels are brighter than the face a little below, on both sides', () => { - for (const li of [0, 1, 2, 3]) { - const cols = 600; - const d = bake(params(li, 300, cols)); - let rimmed = 0; - let n = 0; - for (let x = 3; x < cols - 3; x += 1) { - const y = solidRow(d, cols, x); - if (y + 40 >= BAND) continue; - n += 1; - if (lum(d, cols, x, y + 1) > lum(d, cols, x, y + 30)) rimmed += 1; - } - expect(n).toBeGreaterThan(100); - expect(rimmed / n).toBeGreaterThan(0.8); - } - }); - - it('the foot of the face is clearly darker than its top, on every layer: volume from the depth below the crest', () => { - // Without the depth shading the bottom row is 0.93 to 0.98 of the luminance 12 rows under the crest; with it, 0.73 to 0.82. - for (const li of [0, 1, 2, 3]) { - const cols = 900; - const d = bake(params(li, 0, cols, { spec: { ...LAYERS[li], mist: 0, gully: 0 } })); - let ratio = 0; - let n = 0; - for (let x = 0; x < cols; x += 1) { - const y = solidRow(d, cols, x); - if (y + 90 >= BAND) continue; - n += 1; - ratio += lum(d, cols, x, BAND - 1) / Math.max(1, lum(d, cols, x, y + 12)); - } - expect(n).toBeGreaterThan(30); - expect(ratio / n).toBeLessThan(0.88); - } - }); - - it('the valley mist still pulls the foot toward the haze colour', () => { - const cols = 300; - const p = params(0, 0, cols); - const misty = bake(p); - const clear = bake(params(0, 0, cols, { spec: { ...LAYERS[0], mist: 0 } })); - const haze = layerPaint(p.spec, p.sky).haze; - const dist = (d: Uint8ClampedArray, x: number, y: number) => { - const o = (y * cols + x) * 4; - return Math.hypot(d[o] - haze[0], d[o + 1] - haze[1], d[o + 2] - haze[2]); - }; - let nearer = 0; - let n = 0; - for (let x = 0; x < cols; x += 1) { - const y = solidRow(misty, cols, x); - if (y + 200 >= BAND) continue; - n += 1; - if (dist(misty, x, y + 200) < dist(clear, x, y + 200)) nearer += 1; - } - expect(n).toBeGreaterThan(50); - expect(nearer / n).toBeGreaterThan(0.9); - }); - - it('erosion streaks run down the face: brightness varies across columns at one depth, and not without them', () => { - const cols = 500; - const spread = (gully: number) => { - const d = bake(params(2, 0, cols, { spec: { ...LAYERS[2], gully } })); - // The same depth below the crest in every column, in the lit-independent part (gullies darken, lit is column-wise). - const v: number[] = []; - for (let x = 0; x < cols; x += 1) { - const y = solidRow(d, cols, x); - if (y + 90 < BAND) v.push(lum(d, cols, x, y + 80) / Math.max(1, lum(d, cols, x, y + 8))); - } - const m = v.reduce((a, b) => a + b, 0) / v.length; - return v.reduce((a, b) => a + (b - m) ** 2, 0) / v.length; - }; - expect(spread(LAYERS[2].gully)).toBeGreaterThan(spread(0) * 1.2); - }); -}); - -describe('bake cost', () => { - it('is recorded, not asserted: one chunk of every layer at 1280 x 720', () => { - const period = 1280; - const rows = Math.round(720 * 0.6); - const ms = LAYERS.map((spec) => { - const p: BakeParams = { - spec, - sky: SKY, - period, - scale: 1, - viewH: 720, - rows, - bandH: rows, - px0: 0, - cols: Math.round(period * 1.2), - }; - const t0 = performance.now(); - bake(p); - return performance.now() - t0; - }); - expect(ms.every((v) => Number.isFinite(v) && v >= 0)).toBe(true); - console.info( - `ridge bake ms per layer (node, 1 chunk, 1280x720): ${ms.map((v) => v.toFixed(1)).join(' ')}` - ); - }); -}); - -describe('the ridged multifractal core, each rule on its own', () => { - const one = { ...LAYERS[0], octaves: 1, warp: 0, crag: 1 }; - - it('folds each octave at its crest: a creased, sharp ridge line, not a smooth swell', () => { - // Largest second difference over a fine scan. A smooth curve of this size stays in the hundreds; - // a fold leaves a crease where the noise crosses its midpoint. - const h = 1e-3; - let worst = 0; - for (let i = 1; i < 20000; i += 1) { - const t = i * h; - worst = Math.max( - worst, - Math.abs(profile(one, t + h) - 2 * profile(one, t) + profile(one, t - h)) / (h * h) - ); - } - expect(worst).toBeGreaterThan(2000); - }); - - it('domain-warps: the same layer without its warp is a measurably different line', () => { - const spec = LAYERS[1]; - let diff = 0; - for (let i = 0; i < 2000; i += 1) - diff += Math.abs(profile(spec, i / 100) - profile({ ...spec, warp: 0 }, i / 100)); - expect(diff / 2000).toBeGreaterThan(0.02); - }); - - it('weights each octave by the previous one: where the first octave is low, the later ones add almost nothing', () => { - const lo = { ...LAYERS[1], octaves: 1, warp: 0 }; - const hi = { ...LAYERS[1], octaves: 5, warp: 0 }; - let valley = 0; - let nv = 0; - let peak = 0; - let np = 0; - for (let i = 0; i < 10000; i += 1) { - const a = profile(lo, i / 500); - const d = Math.abs(profile(hi, i / 500) - a); - if (a < 0.12) { - valley += d; - nv += 1; - } else if (a > 0.35) { - peak += d; - np += 1; - } - } - expect(nv).toBeGreaterThan(200); - expect(np).toBeGreaterThan(200); - expect(valley / nv).toBeLessThan(0.25 * (peak / np)); - }); - - it('octave lattices do not line up: the lacunarity is not a power of two', () => { - expect(Number.isInteger(Math.log2(LACUNARITY))).toBe(false); - expect(Number.isInteger(LACUNARITY)).toBe(false); - }); - - it('distance flattens relief: contrast falls from the nearest layer to the farthest', () => { - const c = LAYERS.map((spec) => layerPaint(spec, SKY).contrast); - expect(c[LAYERS.length - 1]).toBe(1); - for (let i = 1; i < c.length; i += 1) expect(c[i]).toBeGreaterThan(c[i - 1]); - // and it shows in the pixels: the lit/shadow difference is smaller on the farthest layer than the nearest - const gap = (li: number) => { - const cols = 700; - const d = bake(params(li, 0, cols)); - const slope = (x: number) => (solidRow(d, cols, x - 1) - solidRow(d, cols, x + 1)) / 2; - const avg = (pick: (s: number) => boolean) => { - const xs = Array.from({ length: cols - 4 }, (_, k) => k + 2).filter((x) => pick(slope(x))); - return ( - xs.reduce((a, x) => a + lum(d, cols, x, solidRow(d, cols, x) + 12), 0) / - Math.max(1, xs.length) - ); - }; - return ( - Math.abs(avg((s) => s < -0.8) - avg((s) => s > 0.8)) / - Math.max( - 1, - avg(() => true) - ) - ); - }; - expect(gap(0)).toBeLessThan(gap(3)); - }); -}); - -describe('the state band: the theme ink clears 4.5:1 on a ridge as on bare sky', () => { - const linear = (v: number) => { - const c = v / 255; - return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; - }; - const luma = (d: Uint8ClampedArray, o: number) => - 0.2126 * linear(d[o]) + 0.7152 * linear(d[o + 1]) + 0.0722 * linear(d[o + 2]); - /** Lowest and highest luminance over the solid pixels of every layer. */ - const range = (band: typeof SKY_BAND[keyof typeof SKY_BAND] | undefined) => { - let lo = 1; - let hi = 0; - for (const li of [0, 1, 2, 3]) { - const p = params(li, 0, 700, { sky: { ...SKY, band } }); - const d = bake(p); - for (let o = 0; o < d.length; o += 4) { - if (d[o + 3] < 255) continue; - const l = luma(d, o); - lo = Math.min(lo, l); - hi = Math.max(hi, l); - } - } - return { lo, hi }; - }; - - it("day and dusk: no ridge pixel is darker than the text floor (Day's), on every layer", () => { - for (const band of [SKY_BAND.day, SKY_BAND.dusk]) { - expect(range(band).lo).toBeGreaterThanOrEqual(SKY_BAND.day.floor); - } - }); - - it('night: no ridge pixel is lighter than the ceiling', () => { - expect(range(SKY_BAND.night).hi).toBeLessThanOrEqual(SKY_BAND.night.ceiling); - }); - - it('is the identity with no band, so nothing else changes', () => { - expect(layerPaint(LAYERS[2], SKY).shift).toBeNull(); - expect(range(undefined).lo).toBeLessThan(SKY_BAND.day.floor); - }); - - it('keeps the shading: the foot is still darker than the top inside the band', () => { - // Inside the band the face's range is compressed, not removed: dusk, no mist or gullies, bottom row over 12 rows under the crest. - const sky = { ...SKY, band: SKY_BAND.dusk }; - for (const li of [0, 1, 2, 3]) { - const cols = 900; - const d = bake(params(li, 0, cols, { sky, spec: { ...LAYERS[li], mist: 0, gully: 0 } })); - let ratio = 0; - let n = 0; - for (let x = 0; x < cols; x += 1) { - const y = solidRow(d, cols, x); - if (y + 90 >= BAND) continue; - n += 1; - ratio += luma(d, ((BAND - 1) * cols + x) * 4) / luma(d, ((y + 12) * cols + x) * 4); - } - expect(n).toBeGreaterThan(30); - // Measured 0.84, 0.85, 0.91, 0.97 far to near: the nearest ground is near black, so its range is small in absolute terms. - expect(ratio / n).toBeLessThan(li < 3 ? 0.95 : 1); - } - }); - - it('the real states, over a sweep of the sun: no pixel overflows the encoding (an overflow reads as a stray black or yellow channel)', () => { - for (const state of ['day', 'dusk', 'night'] as const) { - for (const sunAzimuth of [0, 0.1, 0.25, 0.3, 0.5, 0.75, 0.9]) { - const sky = { ...ridgeSkyFor(state), sunAzimuth }; - for (const li of [0, 1, 2, 3]) { - const d = bake(params(li, 1000, 400, { sky })); - let stray = 0; - for (let o = 0; o < d.length; o += 4) { - if (d[o + 3] < 255) continue; - // A channel far below both others is the signature of a lookup that read past its table. - const lo = Math.min(d[o], d[o + 1], d[o + 2]); - const mid = d[o] + d[o + 1] + d[o + 2] - lo - Math.max(d[o], d[o + 1], d[o + 2]); - if (mid - lo > 120) stray += 1; - } - expect(stray).toBe(0); - } - } - } - }); -}); diff --git a/src/app/features/scene/ridge/ridgeBake.ts b/src/app/features/scene/ridge/ridgeBake.ts deleted file mode 100644 index 063c4e3e..00000000 --- a/src/app/features/scene/ridge/ridgeBake.ts +++ /dev/null @@ -1,221 +0,0 @@ -/* eslint-disable no-param-reassign -- `bakeSlice` fills the caller's pixel buffer */ -// The pixels of a ridge chunk, as a pure function: no DOM, no canvas. Each column is lit from the -// slope of the heightfield's crest line against the sun; the face under it takes a light-to-haze -// gradient, erosion streaks and a lit rim on the crest. The depth treatment (colour, haze, contrast -// by distance) is ridgeWorld's `layerColour`, `hazeColour` and `transmittance`, used here and not redone. -import { - gullyAt, - HorizonView, - LayerSpec, - layerProfile, - hazeColour, - layerColour, - transmittance, -} from './ridgeWorld'; -import type { SkyBand } from '../skyBand'; -import { LUMA, SKY_BAND } from '../skyBand'; -import type { SkyColours, Srgb } from './skyColour'; - -export type Vec3 = readonly [number, number, number]; - -/** Unit vector toward the sun: x across the screen (from the azimuth), y up, z toward the viewer. */ -export function sunDirection(sky: SkyColours): Vec3 { - const az = sky.sunAzimuth ?? 0.3; - const x = 0.9 * Math.sin(2 * Math.PI * az); - const l = Math.hypot(x, 0.35, 0.45); - return [x / l, 0.35 / l, 0.45 / l]; -} - -/** How steeply the crest's slope tilts the face's normal sideways. */ -const TILT = 1.2; - -/** - * Sun light on the face under a crest whose silhouette has `slope` (rows per column, positive when the - * crest rises toward +x, so the face looks toward -x). 0 in full shadow .. 1 head-on to the sun. - */ -export function faceLight(slope: number, sun: Vec3): number { - const nx = -slope * TILT; - const inv = 1 / Math.hypot(nx, 0.55, 0.85); - const d = (nx * sun[0] + 0.55 * sun[1] + 0.85 * sun[2]) * inv; - return Math.min(1, Math.max(0, (d - 0.2) / 0.7)); -} - -export interface BakeParams { - spec: LayerSpec; - sky: SkyColours; - /** Pixels in one viewport width: the unit of world-x. */ - period: number; - /** CSS px to canvas px. */ - scale: number; - /** Viewport height in canvas px. */ - viewH: number; - /** Rows of the pixel buffer (the band plus any padding below it). */ - rows: number; - /** Row count of the visible band; the crest is measured from the top of it. */ - bandH: number; - /** Where world-x is a compass azimuth, for the horizon layer (`LayerSpec.horizon`); absent: every layer is noise. */ - horizonView?: HorizonView; - /** World pixel of the buffer's column 0 (may be fractional-free negative: a chunk's left minus its padding). */ - px0: number; - /** Columns of the buffer. */ - cols: number; -} - -const clamp01 = (v: number): number => Math.min(1, Math.max(0, v)); -const smoothstep = (a: number, b: number, v: number): number => { - const t = clamp01((v - a) / (b - a)); - return t * t * (3 - 2 * t); -}; -const SUN_WHITE: Srgb = [255, 238, 205]; - -/** Everything `bakeSlice` needs per layer, computed once. */ -export interface LayerPaint { - /** The state's band as a shift of linear light (raises the floor, lowers the ceiling); null when the sky has none. */ - shift: BandShift | null; - base: Srgb; - haze: Srgb; - warm: Srgb; - contrast: number; - sun: Vec3; - /** How much the weather's mist multiplies the layer's own (`weather.ts`): 1 in clear air. */ - mistK: number; -} - -const decode = (v: number): number => { - const s = v / 255; - return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4; -}; -const DECODE = Float32Array.from({ length: 256 }, (_, v) => decode(v)); -const ENCODE_STEPS = 4095; -const ENCODE = Uint8ClampedArray.from({ length: ENCODE_STEPS + 1 }, (_, i) => { - const l = i / ENCODE_STEPS; - return 255 * (l <= 0.0031308 ? 12.92 * l : 1.055 * l ** (1 / 2.4) - 0.055); -}); -/** What the band is held clear of at its edges: the 8-bit rounding and the blur and in-scatter the chunk takes after the bake. */ -const BAND_MARGIN = 0.012; - -/** Linear light out = in * `scale` + `add[channel]`. */ -export interface BandShift { - add: readonly [number, number, number]; - scale: number; -} - -/** - * The state's band (skyBand.ts) as a shift of linear light, solved once per layer. Adding `add` (the zenith colour, so - * the ridge reads as shadowed by the sky above, a hue apart from the horizon behind it) raises every pixel's - * luminance by exactly the floor, so the face keeps its whole gradient and the darkest pixel is on the floor; scaling by - * `scale` puts the lightest pixel on the ceiling. Smooth in the pixel's own luminance: no cut and no region. - * The floor is the text bound (Day's), not Dusk's higher link bound: the link ink is not set on ridges, and Dusk's - * floor washes the faces to a flat pale slab. - */ -export function bandShift(band: SkyBand | undefined, lift: Srgb): BandShift | null { - if (!band) return null; - const floor = Math.min(band.floor, SKY_BAND.day.floor); - const scale = band.ceiling < 1 ? band.ceiling - BAND_MARGIN / 3 : 1; - if (floor <= 0 && scale === 1) return null; - const lin = lift.map(decode); - const k = - floor > 0 - ? (floor + BAND_MARGIN) / (LUMA[0] * lin[0] + LUMA[1] * lin[1] + LUMA[2] * lin[2]) - : 0; - return { add: [lin[0] * k, lin[1] * k, lin[2] * k], scale }; -} - -export function layerPaint(spec: LayerSpec, sky: SkyColours): LayerPaint { - const warm: Srgb = [ - (sky.horizon[0] + SUN_WHITE[0]) / 2, - (sky.horizon[1] + SUN_WHITE[1]) / 2, - (sky.horizon[2] + SUN_WHITE[2]) / 2, - ]; - return { - shift: bandShift(sky.band, sky.top), - base: layerColour(spec, sky), - haze: hazeColour(sky), - warm, - // Distance flattens relief: the same transmittance that thins the colour. - contrast: 0.35 + 0.65 * transmittance(spec), - sun: sunDirection(sky), - mistK: 1 + 2.5 * (sky.physical?.weather.mist ?? 0), - }; -} - -/** Crest row (float, from the top of the band) of every buffer column from c0 - 1 to c1 (inclusive). */ -function crestRows(p: BakeParams, c0: number, c1: number): Float64Array { - const out = new Float64Array(c1 - c0 + 2); - const amp = p.spec.relief * p.viewH; - const lift = p.spec.base * p.viewH; - for (let c = c0 - 1; c <= c1; c += 1) { - const top = Math.min( - p.bandH, - lift + amp * layerProfile(p.spec, (p.px0 + c) / p.period, p.horizonView) - ); - out[c - c0 + 1] = p.bandH - top; - } - return out; -} - -/** - * Paint columns [c0, c1) of the chunk into `out` (RGBA, `p.cols` wide, `p.rows` tall, zeroed). One - * call is a slice of a chunk, so a caller can keep each task short. Seams are exact: a column's pixels - * depend only on its world pixel, never on where the slice or chunk begins. - */ -export function bakeSlice( - out: Uint8ClampedArray, - p: BakeParams, - paint: LayerPaint, - c0: number, - c1: number -): void { - const { spec } = p; - const crest = crestRows(p, c0, c1); - const faceH = 0.45 * p.viewH; - const rim = 2.2 * p.scale; - const glow = 9 * p.scale; - const { base, haze, warm, contrast, sun, shift, mistK } = paint; - for (let c = c0; c < c1; c += 1) { - const cy = crest[c - c0 + 1]; - const slope = (crest[c - c0 + 2] - crest[c - c0]) * -0.5; // rows up per column - const lit = faceLight(slope, sun); - const steep = 0.45 + 0.55 * clamp01(Math.abs(slope) * 0.8); - const gl = gullyAt(spec, (p.px0 + c) / p.scale) * steep; - const y0 = Math.max(0, Math.floor(cy)); - for (let y = y0; y < p.rows; y += 1) { - const d = y + 0.5 - cy; - const dn = clamp01(d / faceH); - const cover = clamp01(y + 1 - cy); - const gully = spec.gully * gl * smoothstep(0, 0.2, dn); - // Shade the ground colour by the sun; the lit warm light fades down the face and in the gullies. - // Volume from the depth below the crest: the face darkens toward its foot (before the mist lifts it - // toward the haze), and the sun catches its top. A few multiplies per pixel, in the bake only. - const foot = 1 - 0.4 * contrast * smoothstep(0.05, 0.9, dn); - const top = 1 - smoothstep(0, 0.3, dn); - const shade = (0.7 + 0.3 * lit * contrast + 0.3 * (1 - contrast)) * (1 - 0.5 * gully) * foot; - const warmK = - 0.22 * contrast * lit * lit * (1 - 0.7 * dn) * (1 - 0.6 * gully) + - 0.04 * contrast * lit * top; - // A hard 2 px lip on the crest and a soft glow under it. - const rimK = - (clamp01(1 - d / rim) * 0.4 + (d < glow * 5 ? Math.exp(-d / glow) * 0.08 : 0)) * - contrast * - (0.3 + 0.7 * lit); - const mist = Math.min(0.9, spec.mist * mistK) * smoothstep(0, 1, dn); - const o = (y * p.cols + c) * 4; - for (let i = 0; i < 3; i += 1) { - let v = base[i] * shade + warm[i] * (warmK + rimK); - v += (haze[i] - v) * mist; - out[o + i] = shift - ? ENCODE[ - Math.min( - ENCODE_STEPS, - ((DECODE[v >= 255 ? 255 : v <= 0 ? 0 : Math.round(v)] * shift.scale + - shift.add[i]) * - ENCODE_STEPS) | - 0 - ) - ] - : v; - } - out[o + 3] = cover * 255; - } - } -} diff --git a/src/app/features/scene/ridge/ridgeWorld.ts b/src/app/features/scene/ridge/ridgeWorld.ts deleted file mode 100644 index c6c745c3..00000000 --- a/src/app/features/scene/ridge/ridgeWorld.ts +++ /dev/null @@ -1,236 +0,0 @@ -// Every number of the ridge scene, and the pure functions that turn them into silhouettes. No DOM. -// A ridge is a function of world-x (t, in viewport widths): ridged multifractal noise, domain-warped, -// one function for every layer with the parameters below. Nothing in it repeats. -import { horizonShape } from './horizon'; -import { valueNoise } from './noise'; -import type { Srgb, SkyColours } from './skyColour'; - -export interface LayerSpec { - /** 0 farthest. Also the noise row, so layers never share a profile. */ - index: number; - /** Lattice cells per viewport width for the first octave; each octave multiplies it by LACUNARITY. */ - baseCells: number; - /** Peak-to-valley height of the silhouette, as a fraction of the viewport height. */ - relief: number; - /** 0 rounded hills .. 1 sharp crags: how tightly each octave is folded at its crest. */ - crag: number; - /** Ridge top at its lowest point, fraction of the viewport height up from the bottom. */ - base: number; - /** 0 = the layer is the horizon haze, 1 = the nearest ground colour. */ - depth: number; - /** Seconds for the layer to drift one viewport width. Farther layers are slower. */ - seconds: number; - /** Octaves of the ridged multifractal; the bake cost is linear in it. */ - octaves: number; - /** Domain warp, in cells of the first octave. */ - warp: number; - /** 0..1 depth of the erosion streaks down the face. */ - gully: number; - /** Width of one gully, CSS px. */ - gullyPx: number; - /** 0..1 how far the foot of the face dissolves into the valley mist. */ - mist: number; - /** - * The layer is the real horizon of the viewpoint (`horizon.ts`), not noise: world-x is compass azimuth across the viewport - * (`HorizonView`) and it does not drift, so it stays under the sun it is lit by. Its `relief` is the ring's own range. - */ - horizon?: boolean; -} - -/** Where the camera looks and how wide it sees, to read world-x as an azimuth: the sky's own view (`skyDome.ts viewFor`). */ -export interface HorizonView { - /** Compass azimuth of the viewport's centre, degrees clockwise from north. */ - azimuthDeg: number; - hfovDeg: number; -} - -/** The static horizon layer's track sits this many viewport widths left of the screen, so the camera's sway never shows its edge. */ -export const HORIZON_TRACK_SHIFT = 0.06; - -/** Four layers: one function, four parameter rows. */ -export const LAYERS: readonly LayerSpec[] = [ - { - index: 0, - baseCells: 2.2, - relief: 0.16, - crag: 0.85, - base: 0.3, - depth: 0.12, - seconds: Infinity, - octaves: 5, - warp: 0.6, - gully: 0.3, - gullyPx: 16, - mist: 0.35, - horizon: true, - }, - { - index: 1, - baseCells: 3.0, - relief: 0.2, - crag: 0.7, - base: 0.26, - depth: 0.38, - seconds: 300, - octaves: 5, - warp: 0.55, - gully: 0.5, - gullyPx: 20, - mist: 0.3, - }, - { - index: 2, - baseCells: 3.8, - relief: 0.16, - crag: 0.5, - base: 0.17, - depth: 0.66, - seconds: 210, - octaves: 5, - warp: 0.5, - gully: 0.6, - gullyPx: 24, - mist: 0.22, - }, - { - index: 3, - baseCells: 4.6, - relief: 0.12, - crag: 0.3, - base: 0.08, - depth: 1, - seconds: 150, - octaves: 4, - warp: 0.45, - gully: 0.7, - gullyPx: 30, - mist: 0.16, - }, -]; - -/** Not an integer power of two, so no octave's lattice lines up with another's. */ -export const LACUNARITY = 2.07; -/** Each octave is weighted by the previous octave's folded signal, times this, clamped to 1. */ -export const WEIGHT_GAIN = 2; -const AMP_GAIN = 0.5; -/** Calibration: the weighted sum's typical top is about 1 / this. */ -const PEAK_NORM = 1.25; - -/** Silhouette height in [0, 1] at world-x `t` (viewport widths); defined for every real t. */ -export function profile(spec: LayerSpec, t: number): number { - const row = spec.index * 101; - const wt = - t + (spec.warp * (2 * valueNoise(t * spec.baseCells * 0.7, row + 97) - 1)) / spec.baseCells; - const e = 0.03 + (1 - spec.crag) * 0.4; - const top = Math.sqrt(1 + e * e); - let sum = 0; - let norm = 0; - let amp = 1; - let f = spec.baseCells; - let w = 1; - for (let k = 0; k < spec.octaves; k += 1) { - const v = 2 * valueNoise(wt * f, row + k * 13) - 1; - // Fold: 1 at the zero crossing of the noise, 0 at its extremes; `e` rounds the crease. - let sig = 1 - Math.sqrt(v * v + e * e) / top; - sig *= sig; - sig *= w; - w = Math.min(1, sig * WEIGHT_GAIN); - sum += sig * amp; - norm += amp; - amp *= AMP_GAIN; - f *= LACUNARITY; - } - // A soft swell under the folds, so the valleys between sharp crests are not flat floors. - const swell = valueNoise(wt * spec.baseCells * 0.6, row + 211); - return Math.min(1, 0.85 * (sum / norm) * PEAK_NORM + 0.15 * swell); -} - -/** - * Silhouette height in [0, 1] of a layer at world-x `t` (viewport widths). The horizon layer reads the baked horizon at the azimuth `t` - * is under `view`; every other layer, or a horizon layer with no view, is the noise `profile`. - */ -export function layerProfile(spec: LayerSpec, t: number, view?: HorizonView): number { - if (!spec.horizon || !view) return profile(spec, t); - return horizonShape(view.azimuthDeg + (t - HORIZON_TRACK_SHIFT - 0.5) * view.hfovDeg); -} - -/** Erosion streak strength in [0, 1] at world-x `wxCss` (CSS px): a folded noise at gully width. */ -export function gullyAt(spec: LayerSpec, wxCss: number): number { - const g = 1 - Math.abs(2 * valueNoise(wxCss / spec.gullyPx, spec.index * 131 + 5) - 1); - return g * g; -} - -/** The distance haze the far layers dissolve into: between the mid sky and the horizon, not the horizon glow itself. */ -export function hazeColour(sky: SkyColours): Srgb { - const m = (a: number, b: number) => Math.round(a + (b - a) * 0.4); - return [ - m(sky.mid[0], sky.horizon[0]), - m(sky.mid[1], sky.horizon[1]), - m(sky.mid[2], sky.horizon[2]), - ]; -} - -/** - * Aerial perspective, applied once at bake time. A layer at distance d (0 nearest, 1 farthest) is seen - * through Beer-Lambert transmittance T = exp(-extinction * d): it shows T of its own colour and 1 - T of - * the haze, then loses `desaturate * (1 - T)` of its chroma, is softened by up to `blurPx` (canvas - * pixels at scale 1) and takes a faint warm in-scatter of at most `scatter` on the sun side. - */ -export const AERIAL = { extinction: 1.6, desaturate: 0.5, blurPx: 2, scatter: 0.16 }; - -/** Distance of a layer from the viewer, 0 (nearest) .. 1 (farthest). */ -export const layerDistance = (spec: LayerSpec): number => 1 - spec.depth; - -export const transmittance = (spec: LayerSpec): number => - Math.exp(-AERIAL.extinction * layerDistance(spec)); - -/** Layer colour as seen: its own ground colour thinned by the haze between it and the eye. */ -export function layerColour(spec: LayerSpec, sky: SkyColours): Srgb { - const h = hazeColour(sky); - const t = transmittance(spec); - const seen = (i: number) => sky.ground[i] * t + h[i] * (1 - t); - const luma = 0.2126 * seen(0) + 0.7152 * seen(1) + 0.0722 * seen(2); - const keep = 1 - AERIAL.desaturate * (1 - t); - const out = (i: number) => Math.round(luma + (seen(i) - luma) * keep); - return [out(0), out(1), out(2)]; -} - -/** Edge softening for a layer, in canvas pixels at scale 1; 0 for the nearest. */ -export const edgeBlur = (spec: LayerSpec): number => AERIAL.blurPx * (1 - transmittance(spec)); - -/** - * Alpha of the warm sun-side in-scatter at world-x `t` (viewport widths). Zero when the sky has no - * sun; grows with distance. The lobe is the product of two cosines with incommensurate wavelengths - * (1.9 and 1.9 * golden ratio), so it is not periodic; its peaks are where the sun's azimuth puts them. - */ -export function scatterAlpha(spec: LayerSpec, sky: SkyColours, t: number): number { - if (sky.sunAzimuth === undefined) return 0; - const a = 0.5 + 0.5 * Math.cos(2 * Math.PI * (t / 1.9 - sky.sunAzimuth)); - const b = 0.75 + 0.25 * Math.cos((2 * Math.PI * t) / (1.9 * 1.618034)); - return AERIAL.scatter * (1 - transmittance(spec)) * a * a * b; -} - -/** Chunk width as a multiple of the viewport width: room for the yaw sway on top of the viewport. */ -export const CHUNK_OVER = 1.2; - -/** - * Integer pixel sizes for a viewport. `period` is one viewport width, the unit of world-x; a chunk - * is `chunk` pixels of world, `height` the band a layer is painted in. - */ -export function layerSize(cssW: number, cssH: number, scale: number) { - const period = Math.round(cssW * scale); - const band = Math.round(cssH * scale * 0.6); - return { period, chunk: Math.round(period * CHUNK_OVER), height: band }; -} - -/** Ridge-top y (canvas pixels, from the top of the layer's band) at world-x `t` (viewport widths). */ -export function ridgeY( - spec: LayerSpec, - t: number, - bandH: number, - viewH: number, - view?: HorizonView -): number { - const topFromBottom = spec.base * viewH + spec.relief * viewH * layerProfile(spec, t, view); - return bandH - Math.min(bandH, topFromBottom); -} diff --git a/src/app/features/scene/ridge/ring.test.ts b/src/app/features/scene/ridge/ring.test.ts new file mode 100644 index 00000000..bfe049fa --- /dev/null +++ b/src/app/features/scene/ridge/ring.test.ts @@ -0,0 +1,93 @@ +import { describe, expect, it } from 'vitest'; +import { distanceAt, norm, residentTiles, runTiles, tileAzimuth } from './ring'; +import { parseManifest } from './manifest'; +import { wireManifest } from './manifest.fixture'; + +const ring32 = { tiles: 32 }; + +describe('norm', () => { + it('brings any angle into [0, 360)', () => { + expect(norm(0)).toBe(0); + expect(norm(360)).toBe(0); + expect(norm(-10)).toBe(350); + expect(norm(725)).toBe(5); + }); +}); + +describe('residentTiles', () => { + it('names the tiles an arc overlaps across north, with turns 0 and 1 and monotone unwrapped azimuths', () => { + // Centre 355, half 40: [315, 395] overlaps tiles 28..31 of the first turn and 0..3 of the next. + const refs = residentTiles(ring32, 355, 40); + expect(refs.map((r) => r.tile)).toEqual([28, 29, 30, 31, 0, 1, 2, 3]); + expect(refs.map((r) => r.turn)).toEqual([0, 0, 0, 0, 1, 1, 1, 1]); + const az = refs.map((r) => tileAzimuth(ring32, r)); + az.slice(1).forEach((a, i) => expect(a).toBeGreaterThan(az[i])); + expect(az[0]).toBe(315); + expect(az[4]).toBe(360); + }); + + it('picks the same tiles for a heading and the heading a revolution on, in another turn', () => { + const a = residentTiles(ring32, 40, 30); + const b = residentTiles(ring32, 400, 30); + expect(b.map((r) => r.tile)).toEqual(a.map((r) => r.tile)); + expect(b.every((r, i) => r.turn === a[i].turn + 1)).toBe(true); + // And a heading turned backwards across north. + const c = residentTiles(ring32, -20, 30); + expect(c.map((r) => r.tile)).toEqual([27, 28, 29, 30, 31, 0]); + expect(c.map((r) => r.turn)).toEqual([-1, -1, -1, -1, -1, 0]); + }); + + it('names a tile once at most, even for an arc of a whole ring or more', () => { + const all = residentTiles(ring32, 100, 400); + expect(all).toHaveLength(32); + expect(new Set(all.map((r) => r.tile)).size).toBe(32); + }); + + it('is one tile for an arc inside a tile, and includes a tile an arc only touches at its edge', () => { + expect(residentTiles(ring32, 5, 1).map((r) => r.tile)).toEqual([0]); + expect(residentTiles(ring32, 11.25, 0).map((r) => r.tile)).toEqual([1]); + }); +}); + +describe('distanceAt', () => { + const m = parseManifest(wireManifest(), '/d/'); // four tiles of 90 degrees, centres at 45, 135, 225, 315 + it('is the tile distance at a tile centre and interpolates linearly between centres', () => { + expect(distanceAt(m, 0, 45)).toBeCloseTo(1000, 9); + expect(distanceAt(m, 0, 135)).toBeCloseTo(1200, 9); + expect(distanceAt(m, 0, 90)).toBeCloseTo(1100, 9); + }); + + it('interpolates across the wrap at north and takes any unwrapped heading the same as its wrapped one', () => { + // between tile 3 (315 degrees, 1100 m) and tile 0 (45, 1000 m): north is halfway. + expect(distanceAt(m, 0, 0)).toBeCloseTo(1050, 9); + expect(distanceAt(m, 0, 360)).toBeCloseTo(1050, 9); + expect(distanceAt(m, 0, -360)).toBeCloseTo(1050, 9); + expect(distanceAt(m, 0, 400)).toBeCloseTo(distanceAt(m, 0, 40), 9); + expect(distanceAt(m, 0, -20)).toBeCloseTo(distanceAt(m, 0, 340), 9); + }); + + it('skips a tile where the card is absent: the line runs on to the next tile that holds it', () => { + // card 2 is absent in tile 2 (centre 225): between tile 1 (41000 m at 135) and tile 3 (39000 m at 315), 225 is halfway. + expect(distanceAt(m, 2, 225)).toBeCloseTo(40000, 9); + expect(distanceAt(m, 2, 135)).toBeCloseTo(41000, 9); + expect(distanceAt(m, 2, 180)).toBeCloseTo(40500, 9); + expect(distanceAt(m, 2, 270)).toBeCloseTo(39500, 9); + }); + + it('is the one distance all round for a card that is in one tile only', () => { + const one = wireManifest({}, 3) as { tiles: (unknown | null)[][] }; + const only = { ...one, tiles: one.tiles.map((row, t) => [row[0], row[1], t === 1 ? row[2] : null]) }; + const mo = parseManifest(only, '/d/'); + [0, 77, 135, 200, 359].forEach((az) => expect(distanceAt(mo, 2, az)).toBeCloseTo(41000, 9)); + }); +}); + +describe('runTiles', () => { + it('is export.py run_tiles: the arc at the smallest slide rate plus the offset swing, a straddled tile and two tiles of margin each side', () => { + // Vienna's numbers: r_max 98.2, nearest card 603 m. s_min = 603 / 701.2; arc = 65.45 / s_min + 2 (98.2 / 603) 57.3. + const sMin = 603 / (603 + 98.2); + const arc = 65.4545 / sMin + 2 * (98.2 / 603) * 57.3; + expect(runTiles(ring32, 72 / 1.1, 98.2, 603)).toBe(Math.ceil(arc / 11.25) + 1 + 4); + expect(runTiles(ring32, 72 / 1.1, 100000, 603)).toBe(32); + }); +}); diff --git a/src/app/features/scene/ridge/ring.ts b/src/app/features/scene/ridge/ring.ts new file mode 100644 index 00000000..746ae12e --- /dev/null +++ b/src/app/features/scene/ridge/ring.ts @@ -0,0 +1,79 @@ +// The ring: the one place that reasons about wrap-around at 0 / 360 degrees (a heading is unwrapped and never wrapped by a consumer), and the +// one place a card's distance at an azimuth is read from its tiles. Pure: no DOM, no state. +import type { RidgeManifest } from './manifest'; +import type { View } from './view'; + +/** Tiles fetched beyond the arc each side, and tiles kept beyond it each side (the baker's resident gate counts the keep: `export.py` `run_tiles`; `view.ts` `maxSpeed` spends what it leaves). */ +export const LOAD_MARGIN_TILES = 1; +export const KEEP_MARGIN_TILES = 2; + +/** A compass angle brought into [0, 360). */ +export const norm = (deg: number): number => ((deg % 360) + 360) % 360; + +/** A tile of the ring and the revolution it is met in: its unwrapped azimuth is `turn x 360 + tile x (360 / tiles)`. */ +export interface TileRef { + tile: number; + turn: number; +} + +/** + * The tiles that overlap `[centre - half, centre + half]`, unwrapped compass degrees, in increasing unwrapped azimuth. Each tile is named at most once + * (an arc of a whole ring or more is every tile, from the one the arc starts in). + */ +export function residentTiles( + view: Pick, + centreDeg: number, + halfArcDeg: number +): TileRef[] { + const w = 360 / view.tiles; + const first = Math.floor((centreDeg - halfArcDeg) / w); + const last = Math.min(Math.floor((centreDeg + halfArcDeg) / w), first + view.tiles - 1); + const out: TileRef[] = []; + for (let u = first; u <= last; u += 1) { + out.push({ tile: ((u % view.tiles) + view.tiles) % view.tiles, turn: Math.floor(u / view.tiles) }); + } + return out; +} + +/** The unwrapped azimuth of the left edge of a tile met in `turn`. */ +export const tileAzimuth = (view: Pick, ref: TileRef): number => + ref.turn * 360 + (ref.tile * 360) / view.tiles; + +/** + * The distance of card `card` at compass angle `azDeg`, metres: the circular linear interpolation of the tiles' `distanceM` between tile centres, a tile + * where the card is absent skipped (the line runs on to the next tile that holds it; a card in one tile only has that distance all round). + */ +export function distanceAt(manifest: RidgeManifest, card: number, azDeg: number): number { + const n = manifest.view.tiles; + const at = (t: number) => manifest.tiles[t][card]?.distanceM; + const u = norm(azDeg) / (360 / n) - 0.5; // tile-centre coordinates: tile t's centre is at t + const lo = Math.floor(u); + const frac = u - lo; + const held = (from: number, step: number): number => { + for (let k = 0; k < n; k += 1) { + const t = (((from + step * k) % n) + n) % n; + if (at(t) !== undefined) return k; + } + throw new Error(`ridge: card ${card} is in no tile`); + }; + // The nearest tiles that hold the card at or before the point (back) and after it (ahead), by how many tile steps away they are. + const back = held(lo, -1); + const ahead = held(lo + 1, 1); + const tBack = (((lo - back) % n) + n) % n; + const tAhead = (((lo + 1 + ahead) % n) + n) % n; + const dBack = at(tBack) as number; + const dAhead = at(tAhead) as number; + const span = back + 1 + ahead; // tile steps between the two holders + const along = back + frac; // steps from the back holder to the point + return dBack + (dAhead - dBack) * (along / span); +} + +/** + * N: the tiles the loader may hold at once for a bake (export.py `run_tiles`): the widest viewport arc at the smallest slide rate plus the offset's own + * swing, one straddled tile and two tiles of margin each side. `rminM` is the nearest card's nearest distance. + */ +export function runTiles(view: Pick, hfovMaxDeg: number, rMaxM: number, rminM: number): number { + const sMin = rminM / (rminM + rMaxM); + const arc = hfovMaxDeg / sMin + 2 * (rMaxM / rminM) * 57.3; + return Math.min(view.tiles, Math.ceil(arc / (360 / view.tiles)) + 1 + 4); +} diff --git a/src/app/features/scene/ridge/skyColour.ts b/src/app/features/scene/ridge/skyColour.ts index e2898a0b..259fb2da 100644 --- a/src/app/features/scene/ridge/skyColour.ts +++ b/src/app/features/scene/ridge/skyColour.ts @@ -1,10 +1,8 @@ // The one place the sky's colours come from. Void's `src/sky/sun.js` (`light({ time, lat, lon, // cloud_cover, precipitation })`, PR #20) is the intended source; until it lands this returns a -// fixed twilight: lavender zenith, rose mid-sky, orange horizon. These are the raw stops: the scene draws them -// shaped into the dusk band of ../skyBand.ts (`ridgeSkyFor`, skyForState.ts), whose floor the link of Noonday Sky needs. Replace the body, keep the signature: the scene calls it once, at startup, -// and bakes the result. +// fixed twilight: lavender zenith, rose mid-sky, orange horizon. Replace the body, keep the signature: the scene calls it once, at startup, +// and paints the result. -import type { SkyBand } from '../skyBand'; import type { PhysicalSky } from './physicalSky'; export type Srgb = readonly [number, number, number]; @@ -14,14 +12,8 @@ export interface SkyColours { top: Srgb; /** Mid-sky band. */ mid: Srgb; - /** Colour at the horizon, which the far ridges fade into. */ + /** Colour at the horizon. */ horizon: Srgb; - /** Nearest ridge: the ground colour the farther layers mix away from. */ - ground: Srgb; - /** Where the sun sits across one drift period, 0..1; the layers pick up a faint warm in-scatter there. Omit for none. */ - sunAzimuth?: number; - /** The state's luminance band (skyBand.ts): the layers are shaped into it as the sky is, so the theme ink clears 4.5:1 on a ridge as on bare sky. Omit for none. */ - band?: SkyBand; /** The physical sky this palette was read from; when present the host canvas is painted from it, not from the three stops. */ physical?: PhysicalSky; } @@ -31,7 +23,5 @@ export function skyColours(_now: Date = new Date()): SkyColours { top: [170, 145, 220], mid: [225, 130, 165], horizon: [240, 150, 80], - ground: [7, 17, 26], - sunAzimuth: 0.3, }; } diff --git a/src/app/features/scene/ridge/skyDome.ts b/src/app/features/scene/ridge/skyDome.ts index 41da66b8..913ae298 100644 --- a/src/app/features/scene/ridge/skyDome.ts +++ b/src/app/features/scene/ridge/skyDome.ts @@ -2,29 +2,15 @@ // LUT (`earthAtmosphere.ts`), and nothing else; one lookup per texel, no march. The result is linear HDR // radiance per unit of sun irradiance (a `Float32Array`); `toneMap.ts` makes it pixels. import type { Atmosphere } from './earthAtmosphere'; -import type { SunSample } from './vienna'; +import type { SunSample } from './sunAt'; +import type { Camera } from './view'; import { cloudAmount, cloudRadiance } from './clouds'; +import { addNightRadiance } from './nightSky'; +import type { NightLight } from './nightSky'; const RAD = Math.PI / 180; /** The sun's angular radius in radians (Hillaire's/Bruneton's `sun_angular_radius`). */ export const SUN_RADIUS = 0.004675; -/** Vertical field of view of the camera, degrees, and where the horizon sits down the image: the ridge scene's sky stops. */ -export const VFOV_DEG = 50; -export const HORIZON_AT = 0.78; - -export interface DomeView { - /** Compass azimuth the camera faces, degrees clockwise from north. */ - azimuthDeg: number; - /** Width over height of the viewport. */ - aspect: number; -} - -/** Where the camera looks: toward the sun's side while it is up, so the sun sits right of centre; south in the dark. */ -export const viewFor = (sun: SunSample, aspect: number): DomeView => ({ - azimuthDeg: sun.elevation > -6 ? sun.azimuth - 24 : 180, - aspect, -}); - export interface Dome { w: number; h: number; @@ -41,23 +27,18 @@ export const domeSize = (cssW: number, cssH: number): { w: number; h: number } = }); /** - * Render the HDR sky. Rays below the horizon take the horizon's radiance (the ridges cover them). The sun's disc is not here: it is smaller than a texel, so the host draws it on the upscaled canvas (`sunOnScreen`). `cover` (0..1, `weather.ts`) lays the cloud deck (`clouds.ts`) over it. + * Render the HDR sky: the sun's atmosphere, plus at night the moon's (`night`, scaled by its irradiance ratio) and the airglow. Rays below the horizon take the horizon's radiance (the ridges cover them). The sun's disc is not here: it is smaller than a texel, so the host draws it on the upscaled canvas (`sunOnScreen`). `cover` (0..1, `weather.ts`) lays the cloud deck (`clouds.ts`) over it. */ export function renderDome( atm: Atmosphere, sun: SunSample, - view: DomeView, + camera: Camera, w: number, h: number, - cover = 0 + cover = 0, + night?: NightLight ): Dome { const hdr = new Float32Array(w * h * 3); - const tanHalf = Math.tan((VFOV_DEG * RAD) / 2); - const fa = view.azimuthDeg * RAD; - const fx = Math.sin(fa); - const fy = Math.cos(fa); - const rx = Math.cos(fa); - const ry = -Math.sin(fa); const sunAz = sun.azimuth * RAD; const sunEl = sun.elevation * RAD; const sz = Math.sin(sunEl); @@ -69,25 +50,36 @@ export function renderDome( const zenith = [0, 0, 0]; atm.radiance(1, 1, zenith); cloudRadiance(sz, trans, zenith, cover, cloud); + if (night?.moon) { + // The deck is moonlit as it is sunlit: the moon's own light through the air, scaled by its irradiance. + const m = night.moon; + const moonCloud = [0, 0, 0]; + const moonTrans = [0, 0, 0]; + const moonZenith = [0, 0, 0]; + m.atm.transmittanceToSpace(Math.max(Math.sin(m.elevation * RAD), 0), moonTrans); + m.atm.radiance(1, 1, moonZenith); + cloudRadiance(Math.sin(m.elevation * RAD), moonTrans, moonZenith, cover, moonCloud); + for (let i = 0; i < 3; i += 1) cloud[i] += moonCloud[i] * m.ratio; + } + // The airglow lights the deck too, at the zenith's strength. + addNightRadiance(undefined, 1, 0, cloud); } let logSum = 0; for (let j = 0; j < h; j += 1) { - const v = (HORIZON_AT - (j + 0.5) / h) * 2 * tanHalf; + const el = (camera.horizonAt - (j + 0.5) / h) * camera.vfovDeg * RAD; + const vz = Math.sin(el); + const ground = Math.cos(el); for (let i = 0; i < w; i += 1) { - const u = ((i + 0.5) / w - 0.5) * view.aspect * 2 * tanHalf; - const dx = fx + rx * u; - const dy = fy + ry * u; - const dz = v; - const n = Math.hypot(dx, dy, dz); - const vz = dz / n; - const cosFromSun = Math.cos(Math.atan2(dx, dy) - sunAz); + const az = (camera.azimuthDeg + ((i + 0.5) / w - 0.5) * camera.hfovDeg) * RAD; + const cosFromSun = Math.cos(az - sunAz); atm.radiance(vz, cosFromSun, rgb); + addNightRadiance(night, vz, az, rgb); let r = rgb[0]; let g = rgb[1]; let b = rgb[2]; let lum = 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]; if (cover > 0) { - const c = cloudAmount(dx / n, dy / n, vz, cover); + const c = cloudAmount(ground * Math.sin(az), ground * Math.cos(az), vz, cover); lum += (0.2126 * cloud[0] + 0.7152 * cloud[1] + 0.0722 * cloud[2] - lum) * c; r += (cloud[0] - r) * c; g += (cloud[1] - g) * c; @@ -103,20 +95,11 @@ export function renderDome( return { w, h, hdr, meanLuma: Math.exp(logSum / (w * h)) }; } -/** Where the sun is on the image, as fractions of its width and height (y down), or null when it is behind the camera or below the horizon. */ -export function sunOnScreen(sun: SunSample, view: DomeView): { x: number; y: number } | null { +/** Where the sun is on the image (the camera's angle-linear mapping, `view.ts`), as fractions of its width and height (y down), or null when it is behind the camera or below the horizon. */ +export function sunOnScreen(sun: SunSample, camera: Camera): { x: number; y: number } | null { if (sun.elevation < -0.3) return null; - const tanHalf = Math.tan((VFOV_DEG * RAD) / 2); - const fa = view.azimuthDeg * RAD; - const az = sun.azimuth * RAD; - const el = sun.elevation * RAD; - const sx = Math.cos(el) * Math.sin(az); - const sy = Math.cos(el) * Math.cos(az); - const along = sx * Math.sin(fa) + sy * Math.cos(fa); - if (along <= 0.05) return null; - const u = (sx * Math.cos(fa) - sy * Math.sin(fa)) / along; - const v = Math.sin(el) / along; - const x = u / (view.aspect * 2 * tanHalf) + 0.5; - const y = HORIZON_AT - v / (2 * tanHalf); + const dAz = ((sun.azimuth - camera.azimuthDeg + 540) % 360) - 180; + const x = 0.5 + dAz / camera.hfovDeg; + const y = camera.horizonAt - sun.elevation / camera.vfovDeg; return x < -0.05 || x > 1.05 || y < -0.05 || y > 1.05 ? null : { x, y }; } diff --git a/src/app/features/scene/ridge/skyMoment.test.ts b/src/app/features/scene/ridge/skyMoment.test.ts new file mode 100644 index 00000000..019c58ba --- /dev/null +++ b/src/app/features/scene/ridge/skyMoment.test.ts @@ -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 = { + 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); + }); +}); diff --git a/src/app/features/scene/ridge/skyMoment.ts b/src/app/features/scene/ridge/skyMoment.ts new file mode 100644 index 00000000..684fcc2c --- /dev/null +++ b/src/app/features/scene/ridge/skyMoment.ts @@ -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(); +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 = {}; + 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 = { + 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(); +const named = new Map(); +/** 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 { + 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)}`; +} diff --git a/src/app/features/scene/ridge/skyTestkit.ts b/src/app/features/scene/ridge/skyTestkit.ts new file mode 100644 index 00000000..e66a0731 --- /dev/null +++ b/src/app/features/scene/ridge/skyTestkit.ts @@ -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 + ) + ); diff --git a/src/app/features/scene/ridge/skyTurn.test.ts b/src/app/features/scene/ridge/skyTurn.test.ts new file mode 100644 index 00000000..bd6e4bec --- /dev/null +++ b/src/app/features/scene/ridge/skyTurn.test.ts @@ -0,0 +1,130 @@ +import { describe, expect, it } from 'vitest'; +import { + alignTurns, + LATENESS_S, + marginFor, + MIN_TRAVEL_DEG, + panPx, + plateCamera, + plateSize, + PLATE_MAX_PX, + recentre, + SLACK_MIN_DEG, + slackFor, + TRAVEL_DEG, +} from './skyTurn'; +import { FALLBACK_VIEW, SPEED_CEILING_DEG_S, windowFor } from './view'; +import { RESIDENCY_MS } from './Ridge'; + +const win = windowFor(FALLBACK_VIEW, 1280, 720); + +describe('plateCamera', () => { + it('spans the viewport plus the slack each side about its centre, at the viewport angles per pixel', () => { + const cam = plateCamera(win, 100, SLACK_MIN_DEG); + expect(cam.azimuthDeg).toBe(100); + expect(cam.hfovDeg).toBeCloseTo(win.camera.hfovDeg + 2 * SLACK_MIN_DEG, 12); + expect(cam.vfovDeg).toBe(win.camera.vfovDeg); + expect(cam.horizonAt).toBe(win.camera.horizonAt); + // a plate is `plateSize` wide and shows the same degrees per pixel as the viewport + const { cssW } = plateSize(win, 1280, 720, 1, SLACK_MIN_DEG); + expect(cssW / cam.hfovDeg).toBeCloseTo(1280 / win.camera.hfovDeg, 9); + }); + + it('names its centre within one turn, whatever turn the heading owner is on', () => { + expect(plateCamera(win, 750, SLACK_MIN_DEG).azimuthDeg).toBe(30); + expect(plateCamera(win, -10, SLACK_MIN_DEG).azimuthDeg).toBe(350); + expect(plateCamera(win, 214, 0).hfovDeg).toBe(win.camera.hfovDeg); // no slack: the viewport's own camera, as a still paints + }); +}); + +describe('recentre', () => { + const still = (heading: number, centre: number, slack = SLACK_MIN_DEG) => recentre(heading, centre, slack, 0, RESIDENCY_MS); + + it('fires at the slack for a heading that does not turn, and not for one that stays', () => { + expect(still(100, 100)).toBe(false); + expect(still(119.9, 100)).toBe(false); + expect(still(120.1, 100)).toBe(true); + expect(still(80.1, 100)).toBe(false); + expect(still(79.9, 100)).toBe(true); + }); + + it('takes the margin from the speed in force and the tick: a faster turn is replaced sooner, a slower tick sooner too', () => { + const slack = slackFor(4, RESIDENCY_MS); // 4 degrees a second: margin 10 in 2.5 s + expect(marginFor(4, RESIDENCY_MS)).toBeCloseTo(4 * (LATENESS_S + 0.5), 12); + expect(recentre(100 + slack - 10.1, 100, slack, 4, RESIDENCY_MS)).toBe(false); + expect(recentre(100 + slack - 9.9, 100, slack, 4, RESIDENCY_MS)).toBe(true); + expect(recentre(100 + slack - 10.1, 100, slack, 4, 1500)).toBe(true); // a tick that really took 1.5 s: margin 14 + expect(recentre(100 + slack - 10.1, 100, slack, 0, RESIDENCY_MS)).toBe(false); + }); + + it('never takes the whole slack: a plate just painted is not due again whatever the tick', () => { + expect(recentre(100, 100, SLACK_MIN_DEG, 12, 60_000)).toBe(false); + expect(recentre(100 + MIN_TRAVEL_DEG - 0.1, 100, SLACK_MIN_DEG, 12, 60_000)).toBe(false); + expect(recentre(100 + MIN_TRAVEL_DEG + 0.1, 100, SLACK_MIN_DEG, 12, 60_000)).toBe(true); + }); + + it('reads the heading on the turn of the centre', () => { + expect(still(10 + 360, 10)).toBe(false); + expect(still(350, 5, 14)).toBe(true); // 15 degrees off, the short way + expect(still(358, 5)).toBe(false); + expect(alignTurns(10, 725)).toBe(730); + expect(alignTurns(370, 5)).toBe(10); + }); +}); + +describe('the slack at the speed in force', () => { + const speeds = [0, 0.6, 4, 6, SPEED_CEILING_DEG_S]; + + it('holds the margin and the travel between replacements, at every speed, and is the floor when the view barely turns', () => { + for (const v of speeds) { + const slack = slackFor(v, RESIDENCY_MS); + expect(slack).toBeGreaterThanOrEqual(SLACK_MIN_DEG); + expect(slack).toBeGreaterThanOrEqual(marginFor(v, RESIDENCY_MS) + TRAVEL_DEG); + } + expect(slackFor(0, RESIDENCY_MS)).toBe(SLACK_MIN_DEG); + expect(slackFor(SPEED_CEILING_DEG_S, RESIDENCY_MS)).toBe(TRAVEL_DEG + SPEED_CEILING_DEG_S * (LATENESS_S + RESIDENCY_MS / 1000)); + }); + + it('is never run out between two ticks, in the worst phase, with a late tick, at every speed: a tick that finds the plate whole is followed by one that does too', () => { + for (const v of speeds) { + for (const periodMs of [RESIDENCY_MS, 700]) { + const slack = slackFor(v, RESIDENCY_MS); + // The farthest from its centre a heading can be at a tick that leaves the plate alone, found by walking out from the centre. + let edge = 0; + while (!recentre(100 + edge + 0.001, 100, slack, v, periodMs)) edge += 0.001; + // The next tick comes a period later and as late as the budget lets it be. + const worst = edge + v * (periodMs / 1000 + LATENESS_S); + expect(worst).toBeLessThanOrEqual(slack + 1e-6); + } + } + }); +}); + +describe('plateSize', () => { + it('never has more backing store than PLATE_MAX_PX: the pixel ratio lowers, the plate does not shrink', () => { + [ + [1280, 720, 2], + [1920, 1080, 2], + [3840, 2160, 1], + [390, 844, 3], + [800, 600, 1], + ].forEach(([w, h, dpr]) => { + const wn = windowFor(FALLBACK_VIEW, w, h); + const p = plateSize(wn, w, h, dpr, SLACK_MIN_DEG); + expect(Math.floor(p.cssW * p.ratio) * Math.floor(h * p.ratio)).toBeLessThanOrEqual(PLATE_MAX_PX); + expect(p.ratio).toBeLessThanOrEqual(dpr); + expect(p.cssW).toBeCloseTo((w * (wn.camera.hfovDeg + 2 * SLACK_MIN_DEG)) / wn.camera.hfovDeg, 9); + }); + // a small viewport keeps the whole device ratio, a phone-sized one at 2x loses a little of it + expect(plateSize(windowFor(FALLBACK_VIEW, 300, 500), 300, 500, 2, SLACK_MIN_DEG).ratio).toBe(2); + }); +}); + +describe('panPx', () => { + it('slides the plate one for one with the heading, opposite to it', () => { + const ppd = 1280 / win.camera.hfovDeg; + expect(panPx(214, 214, ppd)).toBeCloseTo(0, 12); + expect(panPx(224, 214, ppd)).toBeCloseTo(-10 * ppd, 9); + expect(panPx(204, 214, ppd)).toBeCloseTo(10 * ppd, 9); + }); +}); diff --git a/src/app/features/scene/ridge/skyTurn.ts b/src/app/features/scene/ridge/skyTurn.ts new file mode 100644 index 00000000..15654778 --- /dev/null +++ b/src/app/features/scene/ridge/skyTurn.ts @@ -0,0 +1,66 @@ +// The sky that turns with the view. The sky is at infinity: it pans one for one with the view direction and ignores the camera's offset (`view.ts` +// `cardPose` is where the near cards differ). So the live scene paints it once into a PLATE, a canvas wider than the viewport by its slack each side, +// centred on a heading, and the compositor slides the plate by `(heading - centre)` degrees of pixels on the same keyframes as the cards (`heading.ts` +// `poseAt`). The slack, sized to the speed of the turn (`slackFor`), lets the heading wander before the plate runs out; the scene paints a new plate about the heading it has reached, in the same +// tick it takes the old one away. Both plates are the same sky, so nothing moves. This file owns which arc of sky a plate holds and when it is replaced. +import { norm } from './ring'; +import type { Camera, Window } from './view'; + +/** The least sky painted beyond the viewport on each side of it, degrees: what a slow turn gets. Authored. */ +export const SLACK_MIN_DEG = 20; +/** Degrees the heading may wander from a fresh plate's centre before it is due a new one, however fast it turns: a plate is not repainted more often than this. Authored. */ +export const TRAVEL_DEG = 14; +/** + * How late a residency tick may run, seconds, beyond its own period, before the plate can run out: a tile mount, a paint, a collection or a busy phone each cost + * a tick a few hundred milliseconds; this is a budget for several of them. Authored. + */ +export const LATENESS_S = 2; +/** The margin never takes more than this much of the slack, degrees, so a plate that has just been painted is not due again at once. */ +export const MIN_TRAVEL_DEG = 1; +/** The most backing store a plate may have, pixels: the pixel ratio lowers before the plate shrinks. */ +export const PLATE_MAX_PX = 3_000_000; + +/** + * Degrees a heading turning at `rateDegPerS` covers between a residency tick that finds the plate good and the next one: a tick's period (`periodMs`, the real + * one, work included) and the lateness budget. A plate is replaced once the heading is nearer its edge than this, so the next tick, however late, finds it whole. + */ +export const marginFor = (rateDegPerS: number, periodMs: number): number => Math.abs(rateDegPerS) * (LATENESS_S + periodMs / 1000); + +/** The slack a plate needs at `rateDegPerS`, the speed in force (`heading.ts` `turnRate`): its margin at the nominal tick `tickMs` and the travel between replacements. */ +export const slackFor = (rateDegPerS: number, tickMs: number): number => + Math.max(SLACK_MIN_DEG, TRAVEL_DEG + marginFor(rateDegPerS, tickMs)); + +/** The camera of a plate: the viewport's, with `slackDeg` more field each side, centred on the compass azimuth `centreDeg` (any turn of it). Angles per pixel are the viewport's. */ +export function plateCamera(win: Window, centreDeg: number, slackDeg: number): Camera { + return { ...win.camera, azimuthDeg: norm(centreDeg), hfovDeg: win.camera.hfovDeg + 2 * slackDeg }; +} + +/** The plate for a viewport `w` x `h` CSS px at `dpr` device pixels per CSS px with `slackDeg` of slack: its CSS width (the viewport's px per degree is the plate's), and the pixel ratio of its backing store. */ +export function plateSize( + win: Window, + w: number, + h: number, + dpr: number, + slackDeg: number +): { cssW: number; ratio: number; pxPerDeg: number } { + const pxPerDeg = w / win.camera.hfovDeg; + const cssW = pxPerDeg * (win.camera.hfovDeg + 2 * slackDeg); + const ratio = Math.min(dpr, Math.sqrt(PLATE_MAX_PX / (cssW * h))); + return { cssW, ratio, pxPerDeg }; +} + +/** `centreDeg` shifted by whole turns to the one nearest `headingDeg` (the heading owner keeps its angles within a turn of zero, so the plate's centre follows). */ +export const alignTurns = (centreDeg: number, headingDeg: number): number => + centreDeg + 360 * Math.round((headingDeg - centreDeg) / 360); + +/** + * Whether a plate with `slackDeg` of slack centred on `centreDeg` should be replaced now: the heading is nearer its edge than the margin, which the speed in + * force and the tick's real period set (`marginFor`) and which never takes more than the slack less MIN_TRAVEL_DEG. A still heading never is. + */ +export function recentre(headingDeg: number, centreDeg: number, slackDeg: number, rateDegPerS: number, periodMs: number): boolean { + const margin = Math.min(marginFor(rateDegPerS, periodMs), slackDeg - MIN_TRAVEL_DEG); + return Math.abs(headingDeg - alignTurns(centreDeg, headingDeg)) > slackDeg - margin; +} + +/** How far the plate is slid, px, when the view faces `headingDeg` and the plate is centred on `centreDeg` (both in the same turn, `alignTurns`): negative once the view has turned clockwise. */ +export const panPx = (headingDeg: number, centreDeg: number, pxPerDeg: number): number => -(headingDeg - centreDeg) * pxPerDeg; diff --git a/src/app/features/scene/ridge/starCatalogue.test.ts b/src/app/features/scene/ridge/starCatalogue.test.ts new file mode 100644 index 00000000..5e0073e9 --- /dev/null +++ b/src/app/features/scene/ridge/starCatalogue.test.ts @@ -0,0 +1,117 @@ +import { describe, expect, it } from 'vitest'; +import { moonPosition } from '../../../../sky/moon.js'; +import { catalogue, lineChains, linesAt, precess, starsAt } from './starCatalogue'; + +const DEG = 180 / Math.PI; +const VIENNA = { lat: 48.1929826, lon: 16.3534237 }; + +/** + * Reference altitude/azimuth (degrees, no refraction) from astropy 8.0.3 (ICRS to AltAz at Vienna 48.1929826 N 16.3534237 E, sea level, + * UTC, J2000 coordinates of the stars as Hipparcos lists them), computed once and pasted: an independent implementation of the transform. + */ +const REFERENCE: { t: string; name: string; ra: number; dec: number; alt: number; az: number }[] = [ + { t: '2026-01-15T21:00:00Z', name: 'Sirius', ra: 101.2875, dec: -16.7161, alt: 23.711, az: 164.391 }, + { t: '2026-01-15T21:00:00Z', name: 'Betelgeuse', ra: 88.7929, dec: 7.4071, alt: 49.164, az: 176.246 }, + { t: '2026-11-20T21:00:00Z', name: 'Vega', ra: 279.2347, dec: 38.7837, alt: 15.924, az: 311.197 }, + { t: '2026-11-20T21:00:00Z', name: 'Polaris', ra: 37.9546, dec: 89.2641, alt: 48.79, az: 0.26 }, + { t: '2026-06-01T23:00:00Z', name: 'Arcturus', ra: 213.9153, dec: 19.1824, alt: 47.976, az: 239.397 }, +]; + +describe('the catalogue', () => { + it('is the Yale Bright Star Catalogue cut at naked-eye, brightest first, Sirius leading', () => { + const c = catalogue(); + expect(c.length).toBeGreaterThan(2500); + expect(c.length).toBeLessThan(3200); + expect(c.every((s, i) => i === 0 || s.mag >= c[i - 1].mag - 1e-9)).toBe(true); + const sirius = c[0]; + expect(sirius.mag).toBeCloseTo(-1.46, 1); + // Sirius, J2000: RA 6h45m09s = 101.287 deg, Dec -16d42'58" = -16.716 deg. + expect(sirius.ra * DEG).toBeCloseTo(101.287, 1); + expect(sirius.dec * DEG).toBeCloseTo(-16.716, 1); + expect(sirius.bv).toBeCloseTo(0.0, 1); + }); + + it('carries the figures: 150 chains of at least two vertices', () => { + const l = lineChains(); + expect(l.length).toBe(150); + expect(l.every((ch) => ch.length >= 2)).toBe(true); + }); +}); + +describe('precession', () => { + it('moves Polaris in declination by 20.04 arcsec a year times cos(RA): 0.118 degrees in 26.9 years, and nothing at the epoch', () => { + const polaris = catalogue().find((s) => Math.abs(s.dec * DEG - 89.264) < 0.05)!; + const [, dec] = precess(polaris.ra, polaris.dec, new Date('2026-11-20T00:00:00Z')); + expect(Math.abs(dec - polaris.dec) * DEG).toBeGreaterThan(0.1); + expect(Math.abs(dec - polaris.dec) * DEG).toBeLessThan(0.13); + const [ra0, dec0] = precess(polaris.ra, polaris.dec, new Date('2000-01-01T12:00:00Z')); + expect(Math.abs(ra0 - polaris.ra) * DEG).toBeLessThan(1e-3); + expect(Math.abs(dec0 - polaris.dec) * DEG).toBeLessThan(1e-3); + }); +}); + +describe('star placement', () => { + it.each(REFERENCE)('puts $name at the reference altitude and azimuth at $t, within half a degree', (r) => { + const placed = starsAt(new Date(r.t), VIENNA.lat, VIENNA.lon, 6, -90); + // The catalogue's star nearest the reference position (the reference coordinates are rounded). + const star = catalogue().reduce( + (best, s, i) => { + const d = Math.hypot((s.ra * DEG - r.ra) * Math.cos(r.dec / DEG), s.dec * DEG - r.dec); + return d < best.d ? { d, i } : best; + }, + { d: 1e9, i: -1 } + ); + expect(star.d).toBeLessThan(0.1); + const p = placed.find((s) => s.index === star.i)!; + expect(Math.abs(p.elevation - r.alt)).toBeLessThan(0.5); + // Azimuth error scales with 1/cos(alt); Polaris sits within 0.8 degree of the pole where azimuth swings fastest. + const dAz = Math.abs(((p.azimuth - r.az + 540) % 360) - 180); + expect(dAz * Math.cos(r.alt / DEG)).toBeLessThan(0.5); + }); + + it("puts Polaris at the observer's latitude in altitude, due north", () => { + for (const t of ['2026-11-20T21:00:00Z', '2026-11-21T02:13:00Z', '2026-06-01T23:00:00Z']) { + const polaris = starsAt(new Date(t), VIENNA.lat, VIENNA.lon).find( + (s) => s.mag > 1.9 && s.mag < 2.1 && s.elevation > 47 && s.elevation < 50 + )!; + expect(Math.abs(polaris.elevation - VIENNA.lat)).toBeLessThan(0.8); + expect(Math.min(polaris.azimuth, 360 - polaris.azimuth)).toBeLessThan(2); + } + }); + + it('hides what is below the horizon and keeps stars brightest first', () => { + const placed = starsAt(new Date('2026-11-20T21:00:00Z'), VIENNA.lat, VIENNA.lon); + expect(placed.length).toBeGreaterThan(900); + expect(placed.length).toBeLessThan(1700); + expect(placed.every((s) => s.elevation >= -1)).toBe(true); + expect(placed.every((s, i) => i === 0 || s.mag >= placed[i - 1].mag - 1e-9)).toBe(true); + }); + + it('turns with the sky: a sidereal day later the same star is back within a quarter degree', () => { + const t0 = Date.parse('2026-11-20T21:00:00Z'); + const a = starsAt(new Date(t0), VIENNA.lat, VIENNA.lon)[3]; + const b = starsAt(new Date(t0 + 86164091), VIENNA.lat, VIENNA.lon).find((s) => s.index === a.index)!; + expect(Math.abs(a.elevation - b.elevation)).toBeLessThan(0.25); + }); +}); + +describe('the moon at Vienna', () => { + it('is where astropy puts it, 2026-11-20 21:00 UTC (alt 42.576, az 215.016), within the series\' 0.5 degrees', () => { + const m = moonPosition('2026-11-20T21:00:00Z', VIENNA.lat, VIENNA.lon); + expect(Math.abs(m.elevation - 42.576)).toBeLessThan(0.5); + expect(Math.abs(m.azimuth - 215.016)).toBeLessThan(0.7); + }); + it('and 2026-06-01 23:00 UTC (alt 11.48, az 164.748)', () => { + const m = moonPosition('2026-06-01T23:00:00Z', VIENNA.lat, VIENNA.lon); + expect(Math.abs(m.elevation - 11.48)).toBeLessThan(0.5); + expect(Math.abs(m.azimuth - 164.748)).toBeLessThan(0.7); + }); +}); + +describe('constellation lines', () => { + it('place every vertex for the moment, in az/el, one chain per chain', () => { + const l = linesAt(new Date('2026-11-20T21:00:00Z'), VIENNA.lat, VIENNA.lon); + expect(l).toHaveLength(150); + expect(l[0].every((p) => p.azimuth >= 0 && p.azimuth < 360 && Math.abs(p.elevation) <= 90)).toBe(true); + }); +}); diff --git a/src/app/features/scene/ridge/starCatalogue.ts b/src/app/features/scene/ridge/starCatalogue.ts new file mode 100644 index 00000000..b7e59b1e --- /dev/null +++ b/src/app/features/scene/ridge/starCatalogue.ts @@ -0,0 +1,120 @@ +// The real stars and constellation lines of the night sky, placed for a place and a moment. The data is nightSkyData.ts (generated, J2000; +// see its header for sources); the sidereal transform is the sun's own (`src/sky/sun.js` equatorialToHorizontal), after precessing the +// J2000 positions to the date. Proper motion and nutation are left out: both are under an arcminute here. +import { daysSinceJ2000, equatorialToHorizontal } from '../../../../sky/sun.js'; +import { LINES_B64, LINE_CHAINS, STARS_B64, STAR_COUNT } from './nightSkyData'; + +const RAD = Math.PI / 180; +const ARCSEC = RAD / 3600; + +/** Faintest star drawn, by catalogue Vmag. The data is cut at 5.5. */ +export const MAG_LIMIT = 5.5; + +export interface CatalogueStar { + /** J2000, radians. */ + ra: number; + dec: number; + /** Visual magnitude. */ + mag: number; + /** B-V colour index. */ + bv: number; +} + +const bytes = (b64: string): Uint8Array => { + const bin = atob(b64.replace(/\s+/g, '')); + return Uint8Array.from(bin, (c) => c.charCodeAt(0)); +}; +const raOf = (u16: number): number => (u16 / 65536) * 360 * RAD; +const decOf = (u16: number): number => ((u16 / 65535) * 180 - 90) * RAD; + +let stars: CatalogueStar[] | undefined; +let chains: { ra: number; dec: number }[][] | undefined; + +/** The catalogue, brightest first (decoded once). */ +export function catalogue(): readonly CatalogueStar[] { + if (!stars) { + const b = bytes(STARS_B64); + const v = new DataView(b.buffer); + stars = Array.from({ length: STAR_COUNT }, (_, i) => ({ + ra: raOf(v.getUint16(i * 6, true)), + dec: decOf(v.getUint16(i * 6 + 2, true)), + mag: b[i * 6 + 4] / 20 - 2, + bv: b[i * 6 + 5] / 50 - 0.5, + })); + } + return stars; +} + +/** The constellation figures: chains of J2000 vertices (decoded once). */ +export function lineChains(): readonly { ra: number; dec: number }[][] { + if (!chains) { + const b = bytes(LINES_B64); + const v = new DataView(b.buffer); + const out: { ra: number; dec: number }[][] = []; + let at = 0; + while (at < b.length) { + const n = b[at]; + at += 1; + out.push( + Array.from({ length: n }, (_, k) => ({ + ra: raOf(v.getUint16(at + k * 4, true)), + dec: decOf(v.getUint16(at + k * 4 + 2, true)), + })) + ); + at += n * 4; + } + if (out.length !== LINE_CHAINS) throw new Error('nightSkyData: line chains do not match the header'); + chains = out; + } + return chains; +} + +/** J2000 right ascension and declination (radians) precessed to the date of `time` (IAU 1976, Meeus, "Astronomical Algorithms" 21.2). */ +export function precess(ra: number, dec: number, time: Date | number): [number, number] { + const t = daysSinceJ2000(time) / 36525; + const zeta = (2306.2181 * t + 0.30188 * t * t + 0.017998 * t ** 3) * ARCSEC; + const z = (2306.2181 * t + 1.09468 * t * t + 0.018203 * t ** 3) * ARCSEC; + const theta = (2004.3109 * t - 0.42665 * t * t - 0.041833 * t ** 3) * ARCSEC; + const a = Math.cos(dec) * Math.sin(ra + zeta); + const b = Math.cos(theta) * Math.cos(dec) * Math.cos(ra + zeta) - Math.sin(theta) * Math.sin(dec); + const c = Math.sin(theta) * Math.cos(dec) * Math.cos(ra + zeta) + Math.cos(theta) * Math.sin(dec); + return [Math.atan2(a, b) + z, Math.asin(Math.max(-1, Math.min(1, c)))]; +} + +interface Horizontal { + azimuth: number; + elevation: number; +} + +export interface PlacedStar extends CatalogueStar, Horizontal { + /** Index into the catalogue. */ + index: number; +} + +/** The stars at or above `minElevation` degrees (and no fainter than `magLimit`) for the moment and place, brightest first. Degrees; azimuth clockwise from north; no refraction. */ +export function starsAt( + time: Date, + lat: number, + lon: number, + magLimit: number = MAG_LIMIT, + minElevation = -1 +): PlacedStar[] { + const out: PlacedStar[] = []; + catalogue().forEach((s, index) => { + if (s.mag > magLimit) return; + const [ra, dec] = precess(s.ra, s.dec, time); + const h = equatorialToHorizontal(ra, dec, time, lat, lon) as Horizontal; + if (h.elevation >= minElevation) out.push({ ...s, index, azimuth: h.azimuth, elevation: h.elevation }); + }); + return out; +} + +/** The constellation chains for the moment and place as azimuth and elevation (degrees), every vertex kept (the horizon is the ridge's to hide). */ +export function linesAt(time: Date, lat: number, lon: number): Horizontal[][] { + return lineChains().map((chain) => + chain.map((p) => { + const [ra, dec] = precess(p.ra, p.dec, time); + return equatorialToHorizontal(ra, dec, time, lat, lon) as Horizontal; + }) + ); +} diff --git a/src/app/features/scene/ridge/stars.test.ts b/src/app/features/scene/ridge/stars.test.ts index e14f2a7c..87a1244f 100644 --- a/src/app/features/scene/ridge/stars.test.ts +++ b/src/app/features/scene/ridge/stars.test.ts @@ -1,85 +1,43 @@ /* eslint-disable no-restricted-syntax, no-continue -- test loops over sample times */ import { describe, expect, it } from 'vitest'; -import { skyColours } from './skyColour'; import { - MAX_STARS, - NIGHT_LUMA, SLOTS, TWINKLE_GAIN, TWINKLE_PERIOD, activeAt, - makeStars, - skyLuma, slotCount, + slotsFor, slotOffset, slotPeriod, - starCount, twinkleGain, } from './stars'; -const DAY = { - ...skyColours(), - top: [96, 150, 220], - mid: [150, 190, 235], - horizon: [240, 215, 190], -} as const; -const NIGHT = { - ...skyColours(), - top: [10, 14, 40], - mid: [30, 34, 80], - horizon: [60, 50, 90], -} as const; -const N = makeStars(NIGHT, 390, 844).length; +/** A field the size of a night's visible stars. */ +const N = 1200; function hash2(a: number, b: number) { return ((a * 7919 + b * 104729) % 1000) / 1000; } -describe('star placement', () => { - it('is deterministic: the same sky and size give the identical field', () => { - expect(makeStars(NIGHT, 390, 844)).toEqual(makeStars(NIGHT, 390, 844)); - expect(makeStars(skyColours(), 390, 844)).toEqual(makeStars(skyColours(), 390, 844)); +describe('the schedule over a universe of which a plate shows a share', () => { + const U = 2887; + const shown = 90; // stars on the plate: the first of the universe's, as any plate's are some of them + + it('twinkles SLOTS of the shown stars on average, and is the same schedule whichever plate asks', () => { + const slots = slotsFor(U, shown); + let on = 0; + const ts = Array.from({ length: 300 }, (_, i) => i * 0.53); + for (const t of ts) on += activeAt(U, t, slots).filter((a) => a.star < shown).length; + expect(on / ts.length).toBeGreaterThan(SLOTS * 0.7); + expect(on / ts.length).toBeLessThan(SLOTS * 1.3); + // a star's twinkle is keyed by its identity: asked again, by another plate, the same star has the same phase and gain + expect(activeAt(U, 41.3, slots)).toEqual(activeAt(U, 41.3, slots)); }); - it('draws none in a day sky or the lavender dusk, and some in a night one', () => { - expect(makeStars(DAY, 390, 844)).toHaveLength(0); - expect(makeStars(skyColours(), 390, 844)).toHaveLength(0); - expect(makeStars(NIGHT, 390, 844).length).toBeGreaterThan(50); - }); - - it('is a few hundred at most: bounded by MAX_STARS and by the viewport', () => { - for (const [w, h] of [ - [390, 844], - [1920, 1080], - [100, 100], - ] as const) { - expect(makeStars(NIGHT, w, h).length).toBeLessThanOrEqual(starCount(w, h)); - expect(starCount(w, h)).toBeLessThanOrEqual(MAX_STARS); - } - expect(N).toBeGreaterThan(150); - }); - - it('thins toward the horizon: more than twice the stars in the top third than the bottom third of the sky', () => { - const all = makeStars(NIGHT, 390, 844); - expect(all.filter((s) => s.y < 0.26).length).toBeGreaterThan( - 2 * all.filter((s) => s.y > 0.52).length - ); - }); - - it('fades with the sky: every star sits where the sky is dark, alpha within bounds', () => { - for (const s of makeStars(NIGHT, 390, 844)) { - expect(skyLuma(NIGHT, s.y)).toBeLessThan(NIGHT_LUMA); - expect(s.alpha).toBeLessThanOrEqual(0.9); - expect(s.alpha).toBeGreaterThanOrEqual(0.05); - } - }); - - it('varies in size and brightness', () => { - const all = makeStars(NIGHT, 390, 844); - expect(new Set(all.map((s) => s.r.toFixed(2))).size).toBeGreaterThan(50); - expect( - Math.max(...all.map((s) => s.alpha)) - Math.min(...all.map((s) => s.alpha)) - ).toBeGreaterThan(0.3); + it('never has more slots than half the universe, nor fewer than one', () => { + expect(slotsFor(U, 1)).toBe(Math.floor(U / 2)); + expect(slotsFor(U, 0)).toBe(Math.floor(U / 2)); + expect(slotsFor(2, 5)).toBe(1); }); }); diff --git a/src/app/features/scene/ridge/stars.ts b/src/app/features/scene/ridge/stars.ts index 0e6d2628..d91a6f6c 100644 --- a/src/app/features/scene/ridge/stars.ts +++ b/src/app/features/scene/ridge/stars.ts @@ -1,22 +1,11 @@ -// The Midnight starfield: placed once from a seeded PRNG and baked once into the sky canvas. A -// rolling window of them twinkles on an overlay canvas: SLOTS slots, each running back-to-back -// twinkles of one star at a time, so the active set is always SLOTS stars and every star gets its turn. -// The schedule is a pure function of (seed, time): no state accumulates and no Math.random runs -// after the field is built, so any instant maps straight to the active set and its brightnesses. +// The twinkle of the real stars (`nightBodies.ts` places them from the catalogue for the place and moment). A rolling window of them twinkles +// on an overlay canvas: SLOTS slots, each running back-to-back twinkles of one star at a time, so the active set is always SLOTS stars and every +// star gets its turn. The schedule is a pure function of (seed, time): no state accumulates and no Math.random runs, so any instant maps +// straight to the active set and its gains. A gain multiplies the star's radiance before the display (scintillation is flux), so a star +// the twilight hides stays hidden whatever it does. -/* eslint-disable no-bitwise -- the seeded PRNG and hash are 32-bit integer arithmetic */ -import type { SkyColours, Srgb } from './skyColour'; +/* eslint-disable no-bitwise -- the seeded hash is 32-bit integer arithmetic */ -/** - * Stars show when the sky behind them is darker than this sRGB luma (0..255). The ridge scene has - * no night flag (the sky theme's Midnight/Noonday is a body class chosen by the app, not seen here), - * so night is the sky's own darkness: a star's alpha is 1 - luma/NIGHT_LUMA at its height in the - * gradient, and a sky whose zenith is lighter than this gets no stars at all. - */ -export const NIGHT_LUMA = 110; -/** The sky gradient runs from the top (0) through mid (0.5) to the horizon glow (0.78 and below). */ -export const SKY_STOPS = { mid: 0.5, horizon: 0.78 }; -export const MAX_STARS = 400; /** Twinkling stars at any instant (fewer only if the field has fewer stars). */ export const SLOTS = 32; export const TWINKLE_PERIOD = { min: 2, max: 7 } as const; @@ -25,48 +14,19 @@ export const TWINKLE_GAIN = { dim: 0.35, bright: 1.15 } as const; const SEED = 0x57a45eed; export interface Star { + /** The star's index in the catalogue (`starCatalogue.ts`): the identity the twinkle schedule is keyed by, the same on every plate of a sky. */ + id: number; /** Position as fractions of the sky canvas width and height. */ x: number; y: number; /** Radius in CSS px. */ r: number; - /** Base alpha 0..0.9 (brightness times how dark the sky is there). */ - alpha: number; - /** CSS colour, white tinted blue or warm. */ + /** CSS colour of the star's centre at base brightness: the display of the sky behind it plus the star, through the sky's own display. */ fill: string; - /** The sky gradient's colour at this height: dimming paints it over the baked star. */ + /** CSS colour of the sky behind it, through the same display: twinkling paints it over the baked star first. */ cover: string; -} - -const luma = (c: Srgb) => 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]; -const lerp = (a: number, b: number, t: number) => a + (b - a) * t; - -/** The baked gradient's colour at fraction t of the canvas height (the canvas interpolates in sRGB). */ -function skyAt(sky: SkyColours, t: number): Srgb { - const mix = (a: Srgb, b: Srgb, k: number): Srgb => [ - Math.round(lerp(a[0], b[0], k)), - Math.round(lerp(a[1], b[1], k)), - Math.round(lerp(a[2], b[2], k)), - ]; - if (t <= SKY_STOPS.mid) return mix(sky.top, sky.mid, t / SKY_STOPS.mid); - if (t <= SKY_STOPS.horizon) - return mix(sky.mid, sky.horizon, (t - SKY_STOPS.mid) / (SKY_STOPS.horizon - SKY_STOPS.mid)); - return sky.horizon; -} - -export const skyLuma = (sky: SkyColours, t: number): number => luma(skyAt(sky, t)); -export const isNight = (sky: SkyColours): boolean => luma(sky.top) < NIGHT_LUMA; - -/** mulberry32: 32-bit seeded PRNG, one float in [0, 1) per call. */ -function prng(seed: number) { - let a = seed >>> 0; - return () => { - a = (a + 0x6d2b79f5) >>> 0; - let t = a; - t = Math.imul(t ^ (t >>> 15), t | 1); - t ^= t + Math.imul(t ^ (t >>> 7), t | 61); - return ((t ^ (t >>> 14)) >>> 0) / 4294967296; - }; + /** The star's centre colour with its radiance multiplied by `gain` (scintillation). */ + shade: (gain: number) => string; } /** Stateless seeded hash of up to three integers to [0, 1). */ @@ -78,52 +38,16 @@ export function hash(a: number, b = 0, c = 0): number { return (h >>> 0) / 4294967296; } -/** How many stars a viewport carries: about one per 1100 CSS px squared, 150..MAX_STARS. */ -export const starCount = (cssW: number, cssH: number): number => - Math.min(MAX_STARS, Math.max(150, Math.round((cssW * cssH) / 1100))); - -/** - * Seeded placement. Each candidate draws all its random numbers whether it is kept or not, so a - * given seed and sky always give the same field and the prefix does not shift with the count. - * Heights are squeezed toward the zenith (y = 0.78 u^1.7) and alpha falls with the sky's luma, so - * the stars thin out and fade into the horizon glow. None for a day sky. - */ -export function makeStars(sky: SkyColours, cssW: number, cssH: number): Star[] { - if (!isNight(sky)) return []; - const rnd = prng(SEED); - const n = starCount(cssW, cssH); - // Every candidate draws all its numbers, kept or not, so the prefix is stable. - const candidates = Array.from({ length: MAX_STARS }, () => ({ - x: rnd(), - y: SKY_STOPS.horizon * rnd() ** 1.7, - r: 0.35 + 1.0 * rnd() ** 4, - bright: 0.35 + 0.65 * rnd() ** 1.5, - tint: rnd(), - })).slice(0, n); - return candidates.flatMap(({ x, y, r, bright, tint }) => { - const alpha = Math.min(0.9, bright * Math.max(0, 1 - skyLuma(sky, y) / NIGHT_LUMA)); - if (alpha < 0.05) return []; - // White, pulled toward blue or toward warm by the tint draw. - const to: Srgb = tint < 0.5 ? [165, 195, 255] : [255, 222, 185]; - const k = 0.55 * Math.abs(tint - 0.5) * 2; - const c = [255, 255, 255].map((v, j) => Math.round(lerp(v, to[j], k))); - const s = skyAt(sky, y); - return [ - { - x, - y, - r, - alpha, - fill: `rgb(${c[0]},${c[1]},${c[2]})`, - cover: `rgb(${s[0]},${s[1]},${s[2]})`, - }, - ]; - }); -} - // ---- The schedule --------------------------------------------------------------------------- export const slotCount = (stars: number): number => Math.min(SLOTS, stars); +/** + * The slots for a schedule over `universe` stars of which `shown` are on the plate that is up: enough that SLOTS of the ones shown twinkle at any instant on + * average, though the schedule runs over the whole universe (the catalogue), so that the same stars twinkle whichever plate shows them. Never more than half + * the universe, so each slot has a star to turn to. + */ +export const slotsFor = (universe: number, shown: number): number => + Math.max(1, Math.min(Math.floor(universe / 2), Math.round((SLOTS * universe) / Math.max(1, shown)), universe)); /** A slot's twinkle period in seconds: its own, in TWINKLE_PERIOD. */ export const slotPeriod = (j: number): number => TWINKLE_PERIOD.min + (TWINKLE_PERIOD.max - TWINKLE_PERIOD.min) * hash(j, 1); @@ -174,9 +98,8 @@ export interface Twinkling { gain: number; } -/** The active set at time `t` seconds for a field of `stars` stars, in slot order. */ -export function activeAt(stars: number, t: number): Twinkling[] { - const slots = slotCount(stars); +/** The active set at time `t` seconds for a universe of `stars` stars, in slot order, in `slots` slots (`slotCount` of them, or `slotsFor`). `star` is an index into the universe. */ +export function activeAt(stars: number, t: number, slots: number = slotCount(stars)): Twinkling[] { return Array.from({ length: slots }, (_, j) => { const period = slotPeriod(j); const off = slotOffset(j); @@ -199,32 +122,13 @@ export function activeAt(stars: number, t: number): Twinkling[] { // ---- Drawing -------------------------------------------------------------------------------- -/** Bake `stars` into `ctx` (canvas `w` x `h` device px, `scale` device px per CSS px) at base alpha. */ -export function drawStars( - ctx: CanvasRenderingContext2D, - stars: readonly Star[], - w: number, - h: number, - scale: number -) { - stars.forEach((s) => { - ctx.globalAlpha = s.alpha; - ctx.fillStyle = s.fill; - ctx.beginPath(); - ctx.arc(s.x * w, s.y * h, s.r * scale, 0, 2 * Math.PI); - ctx.fill(); - }); - ctx.globalAlpha = 1; -} - /** - * The overlay pass: clear, then for each active star whose gain is off base, paint over the baked - * star. Dimming covers it with the sky's own colour at (1 - gain), which leaves exactly - * alpha * gain of the star; brightening adds a second star on top. A star at base draws nothing. + * The overlay pass over the plate's stars by identity: clear, then for each active star on this plate whose gain is off base, cover the baked star with the sky behind it and draw it again + * at the gain. A star at base draws nothing. */ export function drawTwinkle( ctx: CanvasRenderingContext2D, - stars: readonly Star[], + stars: ReadonlyMap, active: readonly Twinkling[], w: number, h: number, @@ -232,18 +136,15 @@ export function drawTwinkle( ) { ctx.clearRect(0, 0, w, h); active.forEach((a) => { - const s = stars[a.star]; + const s = stars.get(a.star); if (!s || Math.abs(a.gain - 1) < 0.01) return; - if (a.gain < 1) { - ctx.globalAlpha = 1 - a.gain; - ctx.fillStyle = s.cover; - } else { - ctx.globalAlpha = Math.min(1, ((a.gain - 1) * s.alpha) / (1 - s.alpha)); - ctx.fillStyle = s.fill; - } + ctx.fillStyle = s.cover; ctx.beginPath(); - ctx.arc(s.x * w, s.y * h, s.r * scale + (a.gain < 1 ? 1 : 0), 0, 2 * Math.PI); + ctx.arc(s.x * w, s.y * h, s.r * scale + 1, 0, 2 * Math.PI); + ctx.fill(); + ctx.fillStyle = s.shade(a.gain); + ctx.beginPath(); + ctx.arc(s.x * w, s.y * h, s.r * scale, 0, 2 * Math.PI); ctx.fill(); }); - ctx.globalAlpha = 1; } diff --git a/src/app/features/scene/ridge/sunAt.test.ts b/src/app/features/scene/ridge/sunAt.test.ts new file mode 100644 index 00000000..ed66552f --- /dev/null +++ b/src/app/features/scene/ridge/sunAt.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it } from 'vitest'; +import { sunAt } from './sunAt'; +import { momentFor } from './skyMoment'; +import { FALLBACK_VIEW } from './view'; + +const P = FALLBACK_VIEW.place; + +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', () => { + it('the Vienna place reproduces the sun the old Vienna constant gave, exactly, at three dates', () => { + // Values taken from the old constant's sunPosition before it was replaced. + const pinned: [string, number, number][] = [ + ['2026-03-20T06:30:00Z', 14.339283830037077, 106.82531633377323], + ['2026-06-21T10:40:00Z', 65.0288142821217, 171.0604046707017], + ['2026-12-21T15:20:00Z', -3.19313392852625, 237.64629073006313], + ]; + for (const [iso, el, az] of pinned) { + const s = sunAt(P, at(iso)); + expect(s.elevation).toBe(el); + expect(s.azimuth).toBe(az); + } + }); + + it('stands at 90 - lat + declination at solar noon: the solstices and equinox', () => { + const june = sunAt(P, noonOf(P, at('2026-06-21T12:00:00Z'))); + expect(june.elevation).toBeCloseTo(90 - P.lat + 23.44, 0); + const december = sunAt(P, noonOf(P, at('2026-12-21T12:00:00Z'))); + expect(december.elevation).toBeCloseTo(90 - P.lat - 23.44, 0); + const march = sunAt(P, noonOf(P, at('2026-03-20T12:00:00Z'))); + expect(march.elevation).toBeCloseTo(90 - P.lat, 0); + }); + + it('is due south at solar noon, east in the morning and west in the afternoon', () => { + const noon = noonOf(P, at('2026-09-23T12:00:00Z')); + 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).toBeGreaterThan(210); + }); + + 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 = noonOf(P, at('2026-11-11T12:00:00Z')); + const minutes = n.getUTCHours() * 60 + n.getUTCMinutes(); + expect(minutes).toBeGreaterThan(10 * 60 + 30); + expect(minutes).toBeLessThan(10 * 60 + 50); + }); + + it('has a short day in December and a long one in June: published 8 h 4 min and 16 h 0 min with refraction, which adds about 6 minutes each end the ephemeris leaves out', () => { + const daylight = (day: string) => { + let n = 0; + for (let m = 0; m < 24 * 60; m += 1) + if (sunAt(P, new Date(Date.parse(day) + m * 60_000)).elevation > 0) n += 1; + return n; + }; + 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); + }); +}); diff --git a/src/app/features/scene/ridge/sunAt.ts b/src/app/features/scene/ridge/sunAt.ts new file mode 100644 index 00000000..6e688285 --- /dev/null +++ b/src/app/features/scene/ridge/sunAt.ts @@ -0,0 +1,21 @@ +// 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). The moment a sky is drawn at is skyMoment.ts's. The ridge sky is the physical atmosphere (`earthAtmosphere.ts`) lit from this sun. +import { sunPosition } from '../../../../sky/sun.js'; +import type { Place } from './view'; + +export interface SunSample { + /** Degrees above the horizon, no refraction. */ + elevation: number; + /** Degrees clockwise from north. */ + azimuth: number; + /** The moment this is the sun of. */ + time: Date; +} + +export function sunAt(place: Place, time: Date): SunSample { + const { elevation, azimuth } = sunPosition(time, place.lat, place.lon) as { + elevation: number; + azimuth: number; + }; + return { elevation, azimuth, time }; +} diff --git a/src/app/features/scene/ridge/toneMap.test.ts b/src/app/features/scene/ridge/toneMap.test.ts new file mode 100644 index 00000000..5c19912b --- /dev/null +++ b/src/app/features/scene/ridge/toneMap.test.ts @@ -0,0 +1,117 @@ +import { describe, expect, it } from 'vitest'; +import { FALLBACK_VIEW } from './view'; +import { makePhysicalSky } from './physicalSky'; +import { sunOfBand } from './skyTestkit'; +import { renderDome } from './skyDome'; +import { windowFor } from './view'; +import { applyCurve, BLACK_LIFT, BUDGET, NIGHT_CEILING, NIGHT_LIFT, SCOTOPIC, displayLumaOf, fitDisplay, makeCurve, scotopic, scotopicWeight } from './toneMap'; +import { sunAt } from './sunAt'; +import type { FixedSkyState } from './skyMoment'; + +const sweep = (c: ReturnType) => + Array.from({ length: 401 }, (_, i) => applyCurve(c, i / 400)); + +describe('the tone curve', () => { + it('is monotone, starts at the black lift and ends at the top knot, for a spread of knots', () => { + const cases: [number[], number[]][] = [ + [[0, 0.01, 0.2, 0.7, 1], [BLACK_LIFT, 0.12, 0.5, 0.9, 1]], + [[0, 0.0005, 0.003, 0.05, 1], [BLACK_LIFT, 0.0225, 0.04, 0.043, 0.043]], + [[0, 0.3, 0.31, 0.32, 1], [BLACK_LIFT, 0.2, 0.5, 0.8, 1]], + ]; + for (const [x, y] of cases) { + const c = makeCurve(x, y); + const v = sweep(c); + expect(v[0]).toBeCloseTo(BLACK_LIFT, 12); + expect(v[400]).toBeCloseTo(y[4], 12); + for (let i = 1; i < v.length; i += 1) expect(v[i]).toBeGreaterThanOrEqual(v[i - 1] - 1e-12); + } + }); +}); + +describe.each(['day', 'dusk', 'night'] as FixedSkyState[])('the %s curve fitted to a sky', (state) => { + 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 dome = renderDome(sky.atm, sky.sun, camera, 64, 36, sky.weather.cover, sky.night); + const b = BUDGET[state]; + + it('has the black lift constant at black and every texel inside the state budget', () => { + const c = sky.fit.display.curve; + expect(applyCurve(c, 0)).toBe(b.lift); + expect(b.lift).toBe(state === 'night' ? NIGHT_LIFT : BLACK_LIFT); + expect(sky.fit.lo).toBeGreaterThanOrEqual(b.floor); + expect(sky.fit.hi).toBeLessThanOrEqual(b.ceiling + 0.004); + const v = sweep(c); + for (let i = 1; i < v.length; i += 1) expect(v[i]).toBeGreaterThanOrEqual(v[i - 1] - 1e-12); + }); + + it('puts the sky percentiles on the targets (as far as the gain limit allows)', () => { + const n = dome.hdr.length / 3; + const ls: number[] = []; + for (let i = 0; i < n; i += 1) + ls.push(displayLumaOf(dome.hdr[i * 3], dome.hdr[i * 3 + 1], dome.hdr[i * 3 + 2], sky.fit.display)); + ls.sort((p, q) => p - q); + const at = (q: number) => ls[Math.floor(q * n)]; + const flat = fitDisplay(state, dome.hdr, dome.meanLuma); + expect(flat.display).toEqual(sky.fit.display); + // The curve is fitted on luminance and applied per channel, so the byte luminance is near its targets, not on them. The median is never limited; the outer two are at or below their targets by the gain limit only. + const p = b.partial; + const level = p ? Math.min(p.levelMax, Math.max(p.levelMin, (dome.meanLuma / p.ref) ** (1 - p.exponent))) : 1; + expect(at(0.5)).toBeGreaterThan(b.targets[1] * level * 0.75); + // The scotopic grade lifts the blue channel, which the per-channel curve takes up faster than the luminance it was fitted on: night reads up to twice its target. + const slack = p ? 2.5 : 1.25; + expect(at(0.5)).toBeLessThan(b.targets[1] * level * slack); + expect(at(0.95)).toBeLessThanOrEqual(b.targets[2] * level * slack + 0.004); + expect(at(0.05)).toBeLessThan(at(0.5)); + }); +}); + +describe('the night display', () => { + const night = (iso: string) => { + const t = new Date(iso); + return makePhysicalSky(sunAt(FALLBACK_VIEW.place, t), 0, FALLBACK_VIEW); + }; + const fullMoon = night('2026-11-24T22:00:00Z'); + const newMoon = night('2026-12-09T20:00:00Z'); + + it('adapts the exposure to the sky: a moonless night is exposed far brighter than a moonlit one', () => { + expect(fullMoon.moon.illuminated).toBeGreaterThan(0.99); + expect(newMoon.moon.illuminated).toBeLessThan(0.1); + expect(newMoon.fit.display.exposure).toBeGreaterThan(10 * fullMoon.fit.display.exposure); + }); + + it('reads the new-moon night darker than the full-moon night (partial adaptation), by the level of the budget', () => { + const med = (p: ReturnType) => applyCurve(p.fit.display.curve, p.fit.display.curve.x[2]); // the median of the sky + expect(med(newMoon)).toBeLessThan(0.6 * med(fullMoon)); + }); + + it('grades toward the rods at night and not by day', () => { + expect(fullMoon.fit.display.grade).toBeGreaterThan(0.8); + expect(newMoon.fit.display.grade).toBeGreaterThan(0.99); + 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', () => { + expect(applyCurve(newMoon.fit.display.curve, 1)).toBe(NIGHT_CEILING); + expect(BUDGET.night.ceiling).toBe(NIGHT_CEILING); + }); +}); + +describe('the scotopic grade', () => { + it('leaves a neutral grey alone in hue, moves colour toward blue and darkens red against blue', () => { + const o = [0, 0, 0]; + scotopic(0.2, 0.2, 0.2, 1, o); + expect(o[0] / o[1]).toBeCloseTo(SCOTOPIC.tint[0] / SCOTOPIC.tint[1], 6); + scotopic(0.5, 0.1, 0.1, 1, o); + const red = [...o]; + scotopic(0.1, 0.1, 0.5, 1, o); + expect(o[2]).toBeGreaterThan(red[2]); + expect(red[0]).toBeLessThan(0.5); // red is nearly black to the rods + scotopic(0.3, 0.2, 0.1, 0, o); + expect(o).toEqual([0.3, 0.2, 0.1]); + }); + it('weighs 1 in the dark and 0 in daylight, falling through the mesopic range', () => { + expect(scotopicWeight(2e-9)).toBeCloseTo(1, 6); + expect(scotopicWeight(0.3)).toBe(0); + expect(scotopicWeight(1e-6)).toBeGreaterThan(scotopicWeight(1e-4)); + }); +}); diff --git a/src/app/features/scene/ridge/toneMap.ts b/src/app/features/scene/ridge/toneMap.ts index 44bc9dbe..e7a8f0cc 100644 --- a/src/app/features/scene/ridge/toneMap.ts +++ b/src/app/features/scene/ridge/toneMap.ts @@ -3,25 +3,32 @@ // matrix), then the sRGB encode. A per-pixel function with no state, applied once to the baked sky (CPU: the scene is a 2D // canvas, there is no float render target to fall back from). // -// Exposure is chosen per sky state (`exposureFor`): the sky is physical radiance, so brightness is the camera's, not a -// shaping of the result. Day and dusk expose to the sky's own luminance (adaptation, as an eye or auto-exposure does) so the -// darkest of the sky stays where the state's dark ink needs a backdrop; night is fixed, the physical dark. -import type { FixedSkyState } from '../skyBand'; +// Exposure adapts to the sky's own luminance in every state (the sky is physical radiance, so brightness is the camera's); night +// adapts only in part (`Budget.partial`), so a new-moon night reads darker than a full-moon one. Before exposure a scotopic grade +// (`scotopic`: desaturation and a blue shift as the adapted luminance falls through the mesopic range) carries the night read. After +// ACES comes one more curve, per channel in display-linear: a monotone cubic through five knots, fitted per sky from the luminance +// 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 +// cards are not sampled, they ride the same curve. +import type { FixedSkyState } from './skyMoment'; +import { SUN_LUX } from './nightSky'; type Rgb = readonly [number, number, number]; -const IN: readonly Rgb[] = [ +export const ACES_IN: readonly Rgb[] = [ [0.59719, 0.35458, 0.04823], [0.076, 0.90834, 0.01566], [0.0284, 0.13383, 0.83777], ]; -const OUT: readonly Rgb[] = [ +export const ACES_OUT: readonly Rgb[] = [ [1.60475, -0.53108, -0.07367], [-0.10208, 1.10813, -0.00605], [-0.00327, -0.07276, 1.07602], ]; +/** Hill's rational fit, `(v (v + a) - b) / (v (c v + d) + e)`: the display the lit cards share (`lightCards.ts` writes the same into its shader). */ +export const ACES_FIT = [0.0245786, 0.000090537, 0.983729, 0.432951, 0.238081] as const; const fit = (v: number): number => - (v * (v + 0.0245786) - 0.000090537) / (v * (0.983729 * v + 0.432951) + 0.238081); + (v * (v + ACES_FIT[0]) - ACES_FIT[1]) / (v * (ACES_FIT[2] * v + ACES_FIT[3]) + ACES_FIT[4]); const encode = (l: number): number => { const c = Math.min(1, Math.max(0, l)); return 255 * (c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055); @@ -32,9 +39,51 @@ export function acesLinear(r: number, g: number, b: number, exposure: number, ou const x = r * exposure; const y = g * exposure; const z = b * exposure; - const p = [0, 1, 2].map((i) => fit(Math.max(0, IN[i][0] * x + IN[i][1] * y + IN[i][2] * z))); + const p = [0, 1, 2].map((i) => + fit(Math.max(0, ACES_IN[i][0] * x + ACES_IN[i][1] * y + ACES_IN[i][2] * z)) + ); for (let i = 0; i < 3; i += 1) - out[i] = Math.min(1, Math.max(0, OUT[i][0] * p[0] + OUT[i][1] * p[1] + OUT[i][2] * p[2])); + out[i] = Math.min( + 1, + Math.max(0, ACES_OUT[i][0] * p[0] + ACES_OUT[i][1] * p[1] + ACES_OUT[i][2] * p[2]) + ); +} + +/** Scotopic luminance of linear sRGB (Jensen et al. 2001, from CIE XYZ): the response of the rods, which see red as nearly black. */ +export const scotopicLuminance = (r: number, g: number, b: number): number => { + const X = 0.4124 * r + 0.3576 * g + 0.1805 * b; + const Y = 0.2126 * r + 0.7152 * g + 0.0722 * b; + const Z = 0.0193 * r + 0.1192 * g + 0.9505 * b; + return Math.max(0, Y * (1.33 * (1 + (Y + Z) / Math.max(X, 1e-30)) - 1.68)); +}; + +/** + * The scotopic grade of linear radiance `r, g, b` at weight `w` (0 photopic .. 1 scotopic): toward the rods' luminance in a blue-shifted grey. A neutral grey keeps its luminance, so the grade moves colour more than brightness. Written into `out`. + * `lightCards.ts` writes the same into its shader. + */ +export function scotopic(r: number, g: number, b: number, w: number, out: number[]): void { + if (w <= 0) { + out[0] = r; + out[1] = g; + out[2] = b; + return; + } + const v = scotopicLuminance(r, g, b); + // Scale the rods' grey to the cones' luminance for a neutral, so only the colour is graded. + const grey = scotopicLuminance(1, 1, 1); + const k = v / grey; + for (let i = 0; i < 3; i += 1) { + const target = k * SCOTOPIC.tint[i]; + out[i] = [r, g, b][i] + (target - [r, g, b][i]) * w; + } +} + +/** How scotopic a sky is, 0..1, from its log-mean luminance per unit of sun irradiance: through the mesopic range (`SCOTOPIC`). */ +export function scotopicWeight(meanLuma: number): number { + const lg = Math.log10(Math.max(meanLuma * SUN_LUX, 1e-12)); + const [lo, hi] = SCOTOPIC.mesopic; + const t = Math.min(1, Math.max(0, (lg - lo) / (hi - lo))); + return SCOTOPIC.strength * (1 - t * t * (3 - 2 * t)); } /** The 8-bit sRGB of linear radiance, exposed and tone-mapped. */ @@ -49,43 +98,127 @@ export function toneMap8(r: number, g: number, b: number, exposure: number, out: export const displayLuma = (c: ArrayLike): number => 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]; -/** What a sky state needs of its backdrop's display luminance, from the ink it wears (skyBand.ts, skyInk.ts). */ +/** What a sky state needs of its backdrop's display luminance, and the targets its curve is fitted to. */ export interface Budget { - /** The darkest texel may not be darker than this (dark ink needs a light backdrop). 0: no floor. */ + /** The darkest texel the curve can draw (its black lift, less one 8-bit step). */ floor: number; - /** The lightest texel may not be lighter than this (light ink needs a dark one). 1: no ceiling. */ + /** What black is drawn as, display-linear: the curve's first knot. */ + lift: number; + /** The lightest texel may not be lighter than this (light ink needs a dark one); it is the curve's top knot. 1: white. */ ceiling: number; - /** Display luminance the log-mean of the sky is exposed to, before the budget is applied; undefined: a fixed exposure. */ + /** Display luminance the log-mean of the sky is exposed to before the curve; undefined: a fixed exposure. */ key?: number; /** Exposure range, in multiples of scene radiance (per unit sun irradiance). */ min: number; max: number; + /** Display luminance the 5th, 50th and 95th percentile of the sky's luminance are mapped to. */ + targets: readonly [number, number, number]; + /** + * Partial adaptation: the targets are scaled by `(meanLuma / ref) ^ (1 - exponent)` (clamped to `levelMin`..`levelMax`) where `meanLuma` is the sky's + * log-mean luminance per unit of sun irradiance and `ref` the one the targets were set at. Exponent 1 is full adaptation (day, dusk). + */ + partial?: { ref: number; exponent: number; levelMin: number; levelMax: number }; + /** The most the curve may steepen the sky's own spread about its median (display luminance per unit of ACES output): a nearly flat overcast sky is not blown up into a gradient. */ + maxGain: number; } -/** Display luminance slack for the 8-bit rounding and the smooth upscale of the baked grid. */ -export const MARGIN = 0.004; +/** The one absolute lift of day and dusk: what black is drawn as, display-linear. The rest of the range is made by the curve. */ +export const BLACK_LIFT = 0.02; +/** Night's black lift: a little lower than day's, the darks stay soft rather than crushed. */ +export const NIGHT_LIFT = 0.004; +/** The night's ceiling, display-linear: the top of its curve (1 is white). EYEBALLED: the operator tunes it by eye; the moon and the stars are drawn through the same display and need the room. */ +export const NIGHT_CEILING = 1; /** - * 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. + * The scotopic grade (Thompson, Shirley & Ferwerda 2002; Kirk & O'Brien 2011; Jensen et al. 2001): `strength` scales it (EYEBALLED, 0 off), + * the mesopic range is log10 of the adapted luminance in cd/m^2 from `mesopic[0]` (fully scotopic) to `mesopic[1]` (fully photopic), + * and `tint` is the blue shift of the scotopic luminance (Jensen et al.). */ -export const BUDGET: Record = { - 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 }, +export const SCOTOPIC = { + strength: 1, + mesopic: [-2, 0.5] as const, + tint: [1.05, 0.97, 1.27] as const, }; -/** The display transform of a sky: exposure, then ACES, then a black lift (veiling glare) in display-linear. */ +export const BUDGET: Record = { + day: { floor: BLACK_LIFT - 0.001, lift: BLACK_LIFT, ceiling: 1, key: 0.45, min: 4, max: 60, targets: [0.22, 0.58, 0.9], maxGain: 4 }, + dusk: { floor: BLACK_LIFT - 0.001, lift: BLACK_LIFT, ceiling: 1, key: 0.5, min: 4, max: 400, targets: [0.12, 0.45, 0.85], maxGain: 4 }, + night: { + floor: NIGHT_LIFT - 0.001, + lift: NIGHT_LIFT, + ceiling: NIGHT_CEILING, + // The key sits at the targets (not day's 0.45): the sky is exposed to where the curve wants it, so the curve is near the identity over it and + // the per-channel curve does not blow a small colour difference (the scotopic blue shift) up into a saturated sky. + key: 0.03, + min: 4, + max: 1e13, + targets: [0.012, 0.03, 0.07], + maxGain: 4, + // A full-moon sky is about 2e-7 of the sun's irradiance in radiance; a moonless one about 2e-9. Partial adaptation of 0.7 puts + // the second at about a quarter of the first. + partial: { ref: 2e-7, exponent: 0.7, levelMin: 0.2, levelMax: 1.3 }, + }, +}; + +/** Knots of the curve: black, the 5th, 50th, 95th percentile, white. */ +export const KNOTS = 5; + +/** A monotone piecewise-cubic Hermite curve over display-linear 0..1: knot positions, values and slopes. */ +export interface Curve { + x: number[]; + y: number[]; + m: number[]; +} + +/** The monotone cubic (Fritsch-Carlson, Brodlie's weighted harmonic mean) through strictly increasing `x` and non-decreasing `y`. */ +export function makeCurve(x: number[], y: number[]): Curve { + const n = x.length; + const h = x.slice(1).map((v, i) => v - x[i]); + const d = h.map((hk, i) => (y[i + 1] - y[i]) / hk); + const m = new Array(n).fill(0); + m[0] = d[0]; + m[n - 1] = d[n - 2]; + for (let k = 1; k < n - 1; k += 1) { + if (d[k - 1] * d[k] <= 0) continue; + const w1 = 2 * h[k] + h[k - 1]; + const w2 = h[k] + 2 * h[k - 1]; + m[k] = (w1 + w2) / (w1 / d[k - 1] + w2 / d[k]); + } + return { x, y, m }; +} + +/** The curve at `v` (clamped to 0..1). `lightCards.ts` writes the same evaluation into its shader. */ +export function applyCurve(c: Curve, v: number): number { + const t0 = Math.min(1, Math.max(0, v)); + let k = 0; + for (let i = 1; i < c.x.length - 1; i += 1) if (t0 > c.x[i]) k = i; + const h = c.x[k + 1] - c.x[k]; + const t = (t0 - c.x[k]) / h; + const t2 = t * t; + const t3 = t2 * t; + return ( + (2 * t3 - 3 * t2 + 1) * c.y[k] + + (t3 - 2 * t2 + t) * h * c.m[k] + + (-2 * t3 + 3 * t2) * c.y[k + 1] + + (t3 - t2) * h * c.m[k + 1] + ); +} + +/** The display transform of a sky: exposure, then ACES, then the fitted curve in display-linear. */ export interface Display { exposure: number; - /** Added to every channel after the curve, then rescaled so white stays white: out = lift + (1 - lift) * aces. */ - lift: number; + curve: Curve; + /** Weight of the scotopic grade before exposure, 0 (photopic, the default) .. 1 (`scotopicWeight`). */ + grade?: number; } /** The 8-bit sRGB of linear radiance through a display. */ export function display8(r: number, g: number, b: number, d: Display, out: number[]): void { - acesLinear(r, g, b, d.exposure, out); - for (let i = 0; i < 3; i += 1) out[i] = Math.round(encode(d.lift + (1 - d.lift) * out[i])); + if (d.grade) { + scotopic(r, g, b, d.grade, out); + acesLinear(out[0], out[1], out[2], d.exposure, out); + } else acesLinear(r, g, b, d.exposure, out); + for (let i = 0; i < 3; i += 1) out[i] = Math.round(encode(applyCurve(d.curve, out[i]))); } const decode = (v: number): number => { @@ -109,15 +242,16 @@ export interface Fit { /** Darkest and lightest display luminance of the grid under `display`. */ lo: number; hi: number; - /** The exposure before the budget moved it, and what the budget took (for the numbers a report cites). */ + /** The exposure the state's key chose (the curve does the rest). */ keyExposure: number; } /** - * Choose the display of a sky, the one place brightness is decided. `hdr` is the grid's radiance (3 floats a texel) and - * `meanLuma` its log-mean luminance. Exposure starts at the state's key (adaptation); a ceiling lowers it until the - * lightest texel is inside the budget (bisection: luminance is monotone in exposure); a floor raises the black lift until the - * darkest is (luminance is monotone in lift, and linear: the lift needed is solved in one step). + * Choose the display of a sky, the one place brightness is decided. `hdr` is the grid's radiance (3 floats a texel) and `meanLuma` its + * log-mean luminance. Exposure is the state's key (adaptation); the targets of a state with partial adaptation are scaled by the sky's level. The scotopic grade's weight comes from the sky's luminance. The curve is then fitted: the 5th, 50th and 95th percentile of the + * grid's luminance after ACES go to the state's targets (the outer two held to the budget's `maxGain` times the sky's own spread about the median), + * between a black lift below and white (or the night ceiling) above. Monotone by construction, so the ceiling holds for every texel + * of every grid and card, and no pass over another viewport's grid is needed. */ export function fitDisplay(state: FixedSkyState, hdr: Float32Array, meanLuma: number): Fit { const b = BUDGET[state]; @@ -126,83 +260,47 @@ export function fitDisplay(state: FixedSkyState, hdr: Float32Array, meanLuma: nu ? b.min : Math.min(b.max, Math.max(b.min, (b.key * 1.6) / Math.max(meanLuma, 1e-9))); const n = hdr.length / 3; + const tmp = [0, 0, 0]; + const xs: number[] = []; + const grade = scotopicWeight(meanLuma); + for (let i = 0; i < n; i += 1) { + scotopic(hdr[i * 3], hdr[i * 3 + 1], hdr[i * 3 + 2], grade, tmp); + acesLinear(tmp[0], tmp[1], tmp[2], keyExposure, tmp); + xs.push(displayLuma(tmp)); + } + xs.sort((p, q) => p - q); + const pct = (q: number) => xs[Math.min(n - 1, Math.floor(q * n))]; + const x = [0, pct(0.05), pct(0.5), pct(0.95), 1]; + x[1] = Math.max(x[1], 1e-7); + x[2] = Math.max(x[2], x[1] * 1.001 + 1e-7); + x[3] = Math.max(x[3], x[2] * 1.001 + 1e-7); + if (x[3] > 0.97) { + x[3] = 0.97; + x[2] = Math.min(x[2], 0.965); + x[1] = Math.min(x[1], 0.96); + } + const p = b.partial; + const level = p + ? Math.min(p.levelMax, Math.max(p.levelMin, (Math.max(meanLuma, 1e-30) / p.ref) ** (1 - p.exponent))) + : 1; + const [t0, t1, t2] = b.targets.map((t) => t * level); + const y = [ + b.lift, + Math.max(b.lift + 1e-4, t0, t1 - b.maxGain * (x[2] - x[1])), + t1, + Math.min(b.ceiling - 1e-4, t2, t1 + b.maxGain * (x[3] - x[2])), + b.ceiling, + ]; + y[1] = Math.min(y[1], y[2] - 1e-4); + y[3] = Math.max(y[3], y[2] + 1e-4); + const display: Display = { exposure: keyExposure, curve: makeCurve(x, y), grade }; + let lo = 2; + let hi = -1; const stride = Math.max(1, Math.floor(n / 4000)); - const tmp = [0, 0, 0]; - const range = (d: Display) => { - let lo = 2; - let hi = -1; - for (let i = 0; i < n; i += stride) { - const l = displayLumaOf(hdr[i * 3], hdr[i * 3 + 1], hdr[i * 3 + 2], d, tmp); - if (l < lo) lo = l; - if (l > hi) hi = l; - } - return { lo, hi }; - }; - let exposure = keyExposure; - let r = range({ exposure, lift: 0 }); - if (r.hi > b.ceiling) { - let lo = 0; - let hiE = exposure; - for (let k = 0; k < 24; k += 1) { - const mid = (lo + hiE) / 2; - if (range({ exposure: mid, lift: 0 }).hi > b.ceiling) hiE = mid; - else lo = mid; - } - exposure = lo; - r = range({ exposure, lift: 0 }); + for (let i = 0; i < n; i += stride) { + const l = displayLumaOf(hdr[i * 3], hdr[i * 3 + 1], hdr[i * 3 + 2], display, tmp); + if (l < lo) lo = l; + if (l > hi) hi = l; } - let lift = 0; - if (r.lo < b.floor) { - // Linear in the displayed linear luminance: L' = lift + (1 - lift) L, but through the 8-bit encode; solve in linear then check once. - lift = (b.floor - r.lo) / (1 - r.lo); - let probe = range({ exposure, lift }); - for (let k = 0; k < 6 && probe.lo < b.floor; k += 1) { - lift += (b.floor - probe.lo) * 1.05; - probe = range({ exposure, lift }); - } - r = probe; - } - return { display: { exposure, lift }, lo: r.lo, hi: r.hi, keyExposure }; -} - -/** - * The display, moved only as far as the budget needs, for a grid other than the one it was fitted on (another viewport's shape, - * its own texels): the fit is made once on a canonical grid so that resizing repaints the same sky, and this keeps a texel the canonical - * grid did not have inside the state's bounds. A display that already holds them is returned as it is. - */ -export function holdBudget(state: FixedSkyState, hdr: Float32Array, d: Display): Display { - const b = BUDGET[state]; - const n = hdr.length / 3; - const tmp = [0, 0, 0]; - const range = (x: Display) => { - let lo = 2; - let hi = -1; - for (let i = 0; i < n; i += 1) { - const l = displayLumaOf(hdr[i * 3], hdr[i * 3 + 1], hdr[i * 3 + 2], x, tmp); - if (l < lo) lo = l; - if (l > hi) hi = l; - } - return { lo, hi }; - }; - let cur = d; - let r = range(cur); - if (r.hi > b.ceiling) { - let lo = 0; - let hiE = cur.exposure; - for (let k = 0; k < 20; k += 1) { - const mid = (lo + hiE) / 2; - if (range({ exposure: mid, lift: cur.lift }).hi > b.ceiling) hiE = mid; - else lo = mid; - } - cur = { exposure: lo, lift: cur.lift }; - r = range(cur); - } - for (let k = 0; k < 8 && r.lo < b.floor; k += 1) { - cur = { - exposure: cur.exposure, - lift: cur.lift + ((b.floor - r.lo) / (1 - r.lo)) * 1.05 + 1e-4, - }; - r = range(cur); - } - return cur; + return { display, lo, hi, keyExposure }; } diff --git a/src/app/features/scene/ridge/vienna.test.ts b/src/app/features/scene/ridge/vienna.test.ts deleted file mode 100644 index 4f26303c..00000000 --- a/src/app/features/scene/ridge/vienna.test.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { solarNoon, STATE_ELEVATION, sunForState, VIENNA, viennaSun } from './vienna'; - -const at = (iso: string) => new Date(iso); - -describe('the sun over Vienna', () => { - it('stands at 90 - lat + declination at solar noon: the solstices and equinox', () => { - const june = viennaSun(solarNoon(at('2026-06-21T12:00:00Z'))); - expect(june.elevation).toBeCloseTo(90 - VIENNA.lat + 23.44, 0); - const december = viennaSun(solarNoon(at('2026-12-21T12:00:00Z'))); - expect(december.elevation).toBeCloseTo(90 - VIENNA.lat - 23.44, 0); - const march = viennaSun(solarNoon(at('2026-03-20T12:00:00Z'))); - expect(march.elevation).toBeCloseTo(90 - VIENNA.lat, 0); - }); - - it('is due south at solar noon, east in the morning and west in the afternoon', () => { - const noon = solarNoon(at('2026-09-23T12:00:00Z')); - expect(Math.abs(viennaSun(noon).azimuth - 180)).toBeLessThan(2); // solarNoon is found to 5 minutes, which is 1.25 degrees of azimuth - expect(viennaSun(new Date(noon.getTime() - 3 * 3600_000)).azimuth).toBeLessThan(150); - expect(viennaSun(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', () => { - // 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); - expect(minutes).toBeLessThan(10 * 60 + 50); - }); - - it('has a short day in December and a long one in June: published 8 h 4 min and 16 h 0 min with refraction, which adds about 6 minutes each end the ephemeris leaves out', () => { - const daylight = (day: string) => { - let n = 0; - for (let m = 0; m < 24 * 60; m += 1) - if (viennaSun(new Date(Date.parse(day) + m * 60_000)).elevation > 0) n += 1; - return n; - }; - 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); - }); - - it('sunForState: the real sun when it is in the state, else a moment of today that is', () => { - const noon = solarNoon(at('2026-11-11T12:00:00Z')); - expect(sunForState('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(state, now); - const [lo, hi] = STATE_ELEVATION[state]; - expect(s.elevation).toBeGreaterThanOrEqual(lo - 0.01); - expect(s.elevation).toBeLessThanOrEqual(hi + 0.01); - } - } - expect(sunForState('dusk', noon).elevation).toBeCloseTo(0, 1); - expect(sunForState('dusk', noon).azimuth).toBeGreaterThan(180); // sets in the west half - }); -}); diff --git a/src/app/features/scene/ridge/vienna.ts b/src/app/features/scene/ridge/vienna.ts deleted file mode 100644 index f21082e5..00000000 --- a/src/app/features/scene/ridge/vienna.ts +++ /dev/null @@ -1,75 +0,0 @@ -// 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.1929826, lon: 16.3534237, altitudeKm: 0.183 } as const; - -export interface SunSample { - /** Degrees above the horizon, no refraction. */ - elevation: number; - /** Degrees clockwise from north. */ - azimuth: number; - /** The moment this is the sun of. */ - time: Date; -} - -export function viennaSun(time: Date): SunSample { - const { elevation, azimuth } = sunPosition(time, VIENNA.lat, VIENNA.lon) as { - elevation: number; - azimuth: number; - }; - 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 = { - 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 Vienna: solar noon to the step. */ -export function solarNoon(t: Date): Date { - const d0 = startOfUtcDay(t); - let best = d0; - let bestEl = -90; - for (let m = 0; m < 24 * 60; m += 5) { - const el = viennaSun(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 Vienna 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(state: FixedSkyState, now: Date): SunSample { - const real = viennaSun(now); - const [lo, hi] = STATE_ELEVATION[state]; - if (real.elevation >= lo && real.elevation <= hi) return real; - const noon = solarNoon(now); - if (state === 'day') return viennaSun(noon); - if (state === 'night') return viennaSun(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 (viennaSun(new Date(m)).elevation > 0) a = m; - else b = m; - } - return viennaSun(new Date((a + b) / 2)); -} diff --git a/src/app/features/scene/ridge/viennaHorizon.json b/src/app/features/scene/ridge/viennaHorizon.json deleted file mode 100644 index adbc289a..00000000 --- a/src/app/features/scene/ridge/viennaHorizon.json +++ /dev/null @@ -1,306 +0,0 @@ -{ - "viewpoint": { "lat": 48.1929826, "lon": 16.3534237, "groundM": 183.3 }, - "stepDeg": 0.5, - "radiusKm": 60.0, - "minKm": 1.0, - "curvature": "drop d^2/2R*(1-0.13), R=6371000 m", - "source": { - "dataset": "Copernicus DEM GLO-30 (COP-DEM_GLO-30-DGED), a DSM, EGM2008 heights, 1 arc-second grid", - "tiles": [ - "N47_00_E015_00", - "N47_00_E016_00", - "N47_00_E017_00", - "N48_00_E015_00", - "N48_00_E016_00", - "N48_00_E017_00", - "N49_00_E015_00", - "N49_00_E016_00", - "N49_00_E017_00" - ], - "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 \u00a9 DLR e.V. 2010-2014 and \u00a9 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": [ - 1.608, 1.522, 1.467, 1.452, 1.433, 1.426, 1.497, 1.6, 1.597, 1.564, 1.532, 1.495, 1.467, 1.544, - 1.62, 1.655, 1.707, 1.775, 1.803, 1.683, 1.532, 1.394, 1.263, 1.297, 1.358, 1.412, 1.433, 1.339, - 1.264, 1.269, 1.195, 1.142, 1.13, 1.22, 1.401, 1.368, 1.326, 1.294, 1.378, 1.46, 1.488, 1.516, - 1.549, 1.598, 1.647, 1.698, 1.769, 1.816, 1.801, 1.783, 1.695, 1.619, 1.586, 1.547, 1.442, - 1.335, 1.282, 1.286, 1.335, 1.421, 1.449, 1.437, 1.313, 1.268, 1.164, 1.14, 1.098, 1.06, 0.984, - 0.938, 0.91, 0.877, 0.884, 0.872, 0.943, 0.974, 0.919, 0.873, 0.861, 0.839, 0.731, 0.673, 0.56, - 0.494, 0.527, 0.601, 0.566, 0.584, 0.579, 0.643, 0.666, 0.741, 0.851, 0.711, 0.703, 0.573, 0.54, - 0.488, 0.433, 0.452, 0.467, 0.483, 0.475, 0.517, 0.419, 0.428, 0.457, 0.489, 0.522, 0.482, 0.5, - 0.527, 0.528, 0.471, 0.458, 0.487, 0.521, 0.578, 0.553, 0.419, 0.301, 0.324, 0.425, 0.468, - 0.512, 0.558, 0.575, 0.521, 0.477, 0.444, 0.372, 0.297, 0.365, 0.446, 0.486, 0.523, 0.532, - 0.516, 0.516, 0.531, 0.52, 0.546, 0.565, 0.535, 0.527, 0.508, 0.516, 0.37, 0.359, 0.33, 0.375, - 0.454, 0.546, 0.496, 0.449, 0.425, 0.447, 0.398, 0.388, 0.439, 0.476, 0.496, 0.517, 0.541, - 0.494, 0.439, 0.383, 0.411, 0.502, 0.621, 0.578, 0.548, 0.568, 0.642, 0.713, 0.708, 0.654, - 0.704, 0.741, 0.709, 0.677, 0.661, 0.66, 0.666, 0.662, 0.651, 0.699, 0.727, 0.746, 0.809, 0.788, - 0.799, 0.793, 0.702, 0.734, 0.79, 0.754, 0.704, 0.616, 0.598, 0.708, 0.719, 0.706, 0.704, 0.726, - 0.826, 0.849, 0.85, 0.813, 0.853, 0.926, 0.971, 0.918, 1.003, 1.0, 0.927, 0.985, 1.031, 1.043, - 1.067, 1.13, 1.022, 1.02, 1.043, 1.101, 1.144, 1.099, 1.082, 1.064, 1.2, 1.238, 1.16, 1.084, - 1.202, 1.326, 1.39, 1.429, 1.405, 1.332, 1.358, 1.361, 1.357, 1.354, 1.335, 1.319, 1.376, 1.309, - 1.289, 1.257, 1.283, 1.237, 1.296, 1.353, 1.259, 1.314, 1.236, 1.307, 1.344, 1.36, 1.251, 1.292, - 1.308, 1.26, 1.288, 1.365, 1.391, 1.414, 1.32, 1.299, 1.35, 1.288, 1.361, 1.303, 1.268, 1.29, - 1.305, 1.326, 1.344, 1.328, 1.32, 1.358, 1.375, 1.443, 1.477, 1.492, 1.525, 1.513, 1.422, 1.314, - 1.294, 1.337, 1.414, 1.343, 1.397, 1.431, 1.409, 1.378, 1.423, 1.438, 1.343, 1.257, 1.208, - 1.209, 1.233, 1.251, 1.267, 1.274, 1.248, 1.254, 1.297, 1.34, 1.359, 1.34, 1.199, 1.162, 1.255, - 1.292, 1.29, 1.24, 1.222, 1.24, 1.271, 1.264, 1.317, 1.256, 1.26, 1.321, 1.301, 1.266, 1.268, - 1.308, 1.357, 1.474, 1.419, 1.438, 1.393, 1.354, 1.343, 1.354, 1.333, 1.321, 1.359, 1.437, 1.47, - 1.395, 1.413, 1.446, 1.466, 1.434, 1.446, 1.458, 1.419, 1.522, 1.502, 1.506, 1.512, 1.528, - 1.526, 1.485, 1.427, 1.508, 1.5, 1.48, 1.534, 1.514, 1.449, 1.449, 1.386, 1.368, 1.388, 1.404, - 1.374, 1.374, 1.352, 1.3, 1.347, 1.332, 1.265, 1.235, 1.39, 1.285, 1.226, 1.233, 1.235, 1.211, - 1.164, 1.183, 1.217, 1.143, 1.128, 1.117, 1.112, 1.086, 1.071, 1.118, 1.103, 1.002, 0.99, 0.995, - 1.025, 0.998, 1.024, 0.971, 1.045, 1.09, 1.11, 1.108, 1.081, 1.171, 1.308, 1.446, 1.482, 1.484, - 1.494, 1.469, 1.472, 1.479, 1.493, 1.467, 1.388, 1.293, 1.203, 1.104, 1.145, 1.12, 1.028, 1.004, - 0.982, 0.968, 0.933, 0.97, 0.986, 1.035, 1.12, 1.227, 1.281, 1.316, 1.312, 1.273, 1.187, 1.205, - 1.197, 1.199, 1.176, 1.177, 1.142, 1.19, 1.377, 1.369, 1.322, 1.295, 1.385, 1.493, 1.576, 1.679, - 1.769, 1.622, 1.711, 1.641, 1.517, 1.582, 1.525, 1.39, 1.389, 1.343, 1.331, 1.369, 1.343, 1.257, - 1.212, 1.134, 1.039, 1.03, 1.075, 1.027, 1.059, 1.112, 1.132, 1.14, 1.16, 1.167, 1.178, 1.179, - 1.192, 1.214, 1.245, 1.289, 1.286, 1.279, 1.259, 1.256, 1.202, 1.138, 1.159, 1.116, 1.12, 1.102, - 0.999, 1.042, 1.051, 1.09, 1.143, 1.244, 1.269, 1.296, 1.353, 1.412, 1.579, 1.686, 1.814, 1.857, - 1.773, 1.731, 1.748, 1.742, 1.668, 1.594, 1.628, 1.692, 1.76, 1.822, 1.863, 1.904, 1.895, 1.849, - 1.786, 1.778, 1.731, 1.666, 1.633, 1.561, 1.526, 1.662, 1.747, 1.75, 1.704, 1.631, 1.563, 1.473, - 1.501, 1.488, 1.464, 1.441, 1.386, 1.31, 1.298, 1.293, 1.306, 1.371, 1.42, 1.416, 1.417, 1.418, - 1.409, 1.399, 1.408, 1.431, 1.434, 1.437, 1.509, 1.544, 1.58, 1.674, 1.528, 1.534, 1.517, 1.497, - 1.525, 1.546, 1.562, 1.58, 1.55, 1.634, 1.614, 1.66, 1.643, 1.663, 1.68, 1.829, 1.99, 2.058, - 2.014, 1.911, 2.025, 2.023, 2.036, 2.031, 2.009, 2.012, 2.02, 2.109, 2.107, 2.12, 2.171, 2.179, - 2.125, 2.084, 2.09, 2.129, 2.183, 2.16, 2.172, 2.239, 2.237, 2.218, 2.217, 2.137, 2.169, 2.203, - 2.233, 2.262, 2.272, 2.21, 2.133, 1.955, 1.909, 1.97, 2.138, 2.187, 2.229, 2.278, 2.191, 2.167, - 2.213, 2.327, 2.409, 2.31, 2.242, 2.205, 2.152, 2.154, 2.258, 2.217, 2.126, 2.054, 1.97, 1.942, - 2.022, 1.894, 1.886, 1.921, 1.897, 1.936, 1.964, 1.978, 1.961, 1.927, 1.879, 1.904, 1.96, 1.9, - 1.922, 2.023, 2.061, 2.115, 1.99, 1.805, 1.736, 1.776, 1.841, 1.863, 1.934, 1.942, 1.962, 2.043, - 2.082, 2.082, 2.092, 2.062, 1.957, 1.794, 1.821, 1.913, 2.009, 2.066, 2.105, 2.036, 1.964, - 1.984, 2.005, 2.036, 2.072, 2.094, 2.022, 2.153, 2.177, 2.146, 2.125, 2.061, 2.004, 1.955, - 1.902, 1.84, 1.767, 1.7, 1.696, 1.718, 1.725, 1.709, 1.745, 1.805, 1.836, 1.939, 2.053, 2.14, - 2.139, 2.142, 2.035, 1.902, 1.779, 1.667, 1.564, 1.57, 1.581, 1.628, 1.693, 1.739, 1.738, 1.738, - 1.675 - ], - "distanceKm": [ - 1.0, 1.0, 1.06, 1.06, 1.06, 1.06, 1.06, 1.03, 1.0, 1.0, 1.0, 1.0, 1.09, 1.09, 1.0, 1.09, 1.09, - 1.09, 1.09, 1.09, 1.09, 1.09, 1.09, 1.12, 1.12, 1.12, 1.12, 1.12, 1.12, 1.09, 1.09, 1.09, 1.09, - 1.0, 1.0, 1.0, 1.0, 1.03, 1.06, 1.06, 1.03, 1.03, 1.03, 1.03, 1.03, 1.03, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.03, 1.03, 1.03, 1.03, 1.03, 1.0, 1.0, 1.06, 1.06, 1.06, 1.06, 1.06, 1.12, 1.0, 1.0, 1.24, - 1.24, 1.21, 1.21, 1.3, 1.3, 1.27, 1.3, 1.33, 1.33, 1.33, 1.33, 1.27, 1.24, 1.27, 1.27, 1.27, - 1.03, 1.03, 1.42, 1.84, 1.84, 1.81, 1.03, 1.72, 1.63, 1.63, 1.63, 1.33, 1.33, 1.06, 1.06, 1.72, - 1.72, 1.69, 1.69, 1.69, 1.69, 1.69, 1.81, 1.81, 1.75, 1.51, 1.75, 1.75, 1.75, 1.75, 1.75, 1.72, - 1.72, 1.72, 1.72, 1.72, 1.72, 1.72, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.42, - 1.42, 1.24, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.27, 1.03, 1.36, 1.36, 1.36, 1.36, 1.36, 1.45, - 1.45, 1.09, 1.12, 1.12, 1.54, 1.57, 1.48, 1.48, 1.48, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.18, 1.18, 1.21, 1.21, 1.21, 1.12, 1.12, 1.12, 1.12, 1.12, 1.15, 1.15, 1.15, 1.15, 1.18, - 1.15, 1.15, 1.24, 1.24, 1.27, 1.27, 1.24, 1.24, 1.24, 1.27, 1.27, 1.27, 1.9, 1.9, 1.93, 1.93, - 1.93, 1.99, 1.99, 1.99, 1.99, 1.9, 2.02, 2.02, 2.02, 2.05, 2.02, 1.99, 1.99, 1.99, 1.48, 1.21, - 1.21, 1.57, 1.69, 1.69, 1.66, 1.39, 1.39, 1.39, 1.54, 1.6, 1.54, 1.54, 1.54, 1.48, 1.45, 1.21, - 1.21, 1.21, 1.27, 1.39, 1.39, 1.36, 1.39, 1.39, 1.39, 1.33, 1.33, 1.33, 1.33, 1.33, 1.48, 1.45, - 1.39, 1.39, 1.18, 1.18, 1.18, 1.48, 1.48, 1.27, 1.24, 1.27, 1.36, 1.36, 1.39, 1.33, 1.3, 1.3, - 1.3, 1.3, 1.3, 1.3, 1.33, 1.0, 1.42, 1.42, 1.27, 1.27, 1.27, 1.27, 1.03, 1.03, 1.03, 1.03, 1.03, - 1.03, 1.03, 1.03, 1.06, 1.06, 1.03, 1.03, 1.03, 1.36, 1.06, 1.06, 1.06, 1.06, 1.09, 1.09, 1.18, - 1.21, 1.09, 1.09, 1.09, 1.09, 1.09, 1.09, 1.09, 1.09, 1.09, 1.09, 1.15, 1.15, 1.36, 1.36, 1.36, - 1.36, 1.33, 1.33, 3.13, 1.21, 1.21, 3.34, 3.31, 2.83, 2.65, 2.65, 1.3, 2.29, 1.3, 1.15, 1.15, - 1.15, 2.29, 2.68, 2.41, 2.23, 2.23, 2.2, 1.12, 2.23, 2.17, 2.17, 2.17, 1.84, 2.74, 1.87, 1.87, - 2.95, 2.2, 2.17, 2.17, 2.35, 2.35, 2.23, 2.23, 2.11, 2.14, 2.08, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2, - 2.41, 2.41, 2.38, 2.41, 2.41, 2.44, 2.44, 2.44, 1.99, 2.08, 2.08, 2.08, 2.08, 2.05, 2.05, 2.5, - 2.38, 2.47, 2.29, 2.23, 2.17, 1.69, 1.69, 2.38, 2.47, 2.38, 2.17, 2.71, 2.71, 2.2, 2.47, 2.41, - 2.41, 2.32, 2.38, 2.38, 2.08, 2.5, 2.11, 2.11, 1.75, 1.75, 1.48, 1.81, 1.81, 1.78, 1.78, 1.87, - 17.2, 17.2, 17.26, 17.32, 17.44, 18.1, 17.56, 17.5, 17.38, 17.5, 17.62, 17.68, 17.74, 17.8, - 14.86, 14.92, 14.98, 2.98, 26.38, 26.38, 26.38, 26.62, 26.14, 26.02, 26.02, 26.38, 26.26, 26.38, - 26.38, 26.26, 26.26, 26.26, 14.98, 14.98, 14.98, 14.44, 13.12, 13.18, 13.66, 13.72, 13.72, - 13.84, 13.84, 13.84, 13.72, 12.52, 12.58, 12.58, 12.28, 12.22, 12.28, 16.54, 14.02, 15.04, - 16.18, 16.24, 17.08, 17.26, 17.44, 17.5, 17.44, 17.32, 17.44, 17.02, 13.96, 14.14, 9.22, 9.16, - 9.1, 9.22, 9.28, 9.28, 9.22, 9.16, 9.16, 9.34, 8.68, 8.68, 8.62, 8.74, 8.86, 8.92, 8.86, 8.92, - 8.92, 11.74, 14.08, 11.98, 12.22, 12.04, 34.3, 10.36, 10.06, 9.64, 9.58, 9.58, 9.7, 9.7, 10.18, - 10.18, 10.18, 10.24, 10.06, 10.48, 9.94, 9.82, 9.76, 9.7, 8.02, 8.14, 8.14, 8.14, 8.08, 8.56, - 8.38, 8.38, 8.32, 8.38, 8.02, 8.02, 8.02, 8.14, 8.2, 7.9, 7.9, 7.84, 7.78, 7.66, 7.72, 7.72, - 7.72, 1.0, 1.0, 1.0, 1.0, 1.0, 1.45, 1.21, 1.21, 1.3, 1.15, 1.15, 1.15, 1.15, 1.15, 1.15, 1.15, - 1.33, 1.33, 1.33, 1.48, 1.3, 1.3, 1.3, 1.42, 1.09, 2.02, 1.81, 2.59, 2.59, 2.53, 1.21, 1.75, - 1.69, 1.66, 2.38, 1.57, 1.57, 1.57, 7.18, 7.18, 7.24, 7.24, 7.18, 7.12, 1.0, 1.0, 1.0, 1.0, 1.0, - 7.36, 7.3, 7.3, 7.18, 7.24, 7.06, 7.06, 7.06, 7.06, 7.0, 7.12, 7.12, 7.12, 7.0, 7.0, 7.0, 7.0, - 7.24, 7.24, 7.06, 7.18, 7.0, 7.06, 7.0, 7.0, 6.94, 7.0, 7.24, 1.03, 1.03, 1.03, 1.0, 1.0, 1.0, - 1.06, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.03, 1.03, 1.03, 1.03, 1.03, 1.03, 1.27, 1.27, 1.27, - 1.24, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.09, 1.09, 1.06, 1.06, 1.06, 1.06, 1.06, - 1.09, 1.09, 9.64, 9.58, 9.64, 9.64, 9.7, 9.7, 9.7, 9.7, 9.7, 9.64, 9.64, 9.64, 9.7, 1.03, 1.03, - 1.03, 1.03, 1.03, 1.03, 9.52, 1.0, 1.0, 9.4, 8.68, 8.68, 8.68, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 9.52, 9.46, 9.46, 9.46, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 - ], - "peakHeightM": [ - 211.4, 209.9, 210.5, 210.2, 209.9, 209.7, 211.0, 212.1, 211.2, 210.6, 210.1, 209.4, 211.3, - 212.7, 211.6, 214.8, 215.8, 217.1, 217.7, 215.4, 212.5, 209.9, 207.4, 208.7, 209.9, 211.0, - 211.4, 209.5, 208.1, 207.5, 206.1, 205.1, 204.8, 204.6, 207.8, 207.2, 206.5, 206.6, 208.8, - 210.4, 210.1, 210.6, 211.2, 212.1, 213.0, 213.9, 214.2, 215.0, 214.8, 214.5, 212.9, 212.5, - 211.9, 211.2, 209.3, 207.3, 205.7, 205.8, 208.1, 209.6, 210.2, 209.9, 207.6, 208.2, 203.7, - 203.2, 207.2, 206.3, 204.2, 203.2, 204.0, 203.3, 203.0, 203.2, 205.3, 206.0, 204.7, 203.7, - 202.5, 201.5, 199.6, 198.3, 195.8, 192.2, 192.8, 198.3, 201.7, 202.3, 201.8, 194.9, 203.5, - 204.5, 207.7, 203.7, 199.7, 196.7, 193.3, 192.4, 196.5, 197.1, 197.2, 197.7, 197.5, 198.7, - 195.8, 197.0, 197.9, 198.4, 197.2, 198.2, 198.7, 199.6, 199.6, 197.9, 197.2, 198.1, 199.1, - 200.8, 200.1, 196.0, 192.5, 189.0, 190.8, 191.5, 192.3, 193.1, 193.4, 192.4, 191.7, 191.1, - 189.8, 190.8, 192.5, 193.0, 194.4, 195.2, 195.5, 195.1, 195.1, 195.4, 195.2, 195.5, 193.5, - 196.1, 195.9, 195.5, 195.6, 192.2, 192.5, 191.8, 190.5, 192.2, 194.0, 196.8, 195.7, 194.4, - 195.0, 193.7, 190.1, 191.0, 191.7, 192.0, 192.4, 192.8, 192.0, 191.0, 190.0, 191.8, 193.7, - 196.5, 195.6, 194.9, 194.5, 195.9, 197.3, 197.2, 196.1, 197.5, 198.2, 197.6, 196.9, 197.0, - 196.6, 196.7, 197.7, 197.5, 198.9, 199.5, 199.5, 200.9, 200.4, 201.1, 201.0, 198.9, 207.9, - 209.7, 208.9, 207.2, 204.3, 204.3, 208.1, 208.5, 208.1, 206.9, 209.1, 212.7, 213.5, 214.0, - 212.2, 213.2, 215.7, 217.3, 207.1, 204.6, 204.5, 208.8, 212.5, 213.9, 213.7, 209.3, 210.8, - 208.2, 210.9, 212.6, 213.0, 214.2, 213.0, 211.4, 210.3, 208.7, 209.5, 207.9, 207.4, 212.6, - 215.6, 216.4, 218.1, 217.5, 215.7, 214.9, 215.0, 214.9, 214.8, 214.4, 217.5, 218.3, 215.2, - 214.7, 209.3, 209.8, 208.9, 216.9, 218.4, 211.3, 211.8, 210.8, 214.4, 215.3, 216.4, 212.4, - 212.7, 213.1, 212.0, 212.6, 214.4, 215.0, 216.2, 206.4, 215.6, 216.9, 211.9, 213.6, 212.3, - 211.5, 206.5, 206.8, 207.2, 207.5, 207.2, 207.1, 207.8, 208.1, 210.0, 210.7, 210.2, 210.8, - 210.5, 217.2, 207.7, 207.3, 208.1, 209.5, 208.9, 209.9, 212.8, 213.1, 209.6, 210.4, 210.7, - 208.9, 207.3, 206.3, 206.4, 206.8, 207.2, 207.5, 208.9, 208.4, 213.2, 214.2, 215.2, 215.7, - 214.5, 211.2, 247.4, 209.9, 210.7, 259.2, 255.7, 244.2, 241.1, 242.6, 212.1, 236.3, 211.9, - 208.7, 209.9, 209.5, 234.2, 243.1, 238.7, 236.5, 241.0, 238.1, 211.5, 237.8, 234.9, 234.5, - 234.9, 226.3, 246.9, 227.9, 230.4, 259.6, 237.2, 237.1, 238.4, 243.8, 242.5, 239.9, 240.4, - 235.8, 240.4, 238.1, 241.4, 241.7, 242.3, 242.2, 240.6, 238.4, 247.1, 246.8, 245.2, 248.2, - 247.4, 245.4, 245.4, 242.7, 231.1, 234.0, 234.5, 233.4, 233.5, 231.9, 230.1, 242.5, 239.0, - 238.2, 233.0, 237.7, 232.3, 219.6, 219.9, 235.0, 235.9, 232.0, 228.4, 241.4, 237.8, 226.9, - 231.8, 230.5, 229.4, 227.0, 230.1, 229.5, 219.9, 226.9, 220.2, 221.3, 214.0, 214.8, 208.5, - 216.5, 217.9, 218.0, 217.9, 218.8, 554.9, 596.3, 639.3, 651.8, 655.9, 677.7, 654.8, 653.7, - 652.5, 660.3, 655.7, 632.9, 605.1, 578.6, 484.8, 496.7, 491.5, 237.4, 693.3, 682.9, 676.3, - 665.1, 672.6, 677.4, 699.5, 746.5, 793.0, 820.8, 836.9, 831.7, 813.8, 774.3, 513.7, 511.5, - 512.0, 493.9, 464.6, 457.9, 479.7, 526.0, 524.0, 515.7, 509.3, 531.0, 553.8, 538.4, 562.8, - 582.7, 541.4, 558.5, 545.3, 640.0, 583.8, 599.0, 593.8, 595.2, 603.6, 604.7, 620.9, 614.5, - 586.6, 570.3, 549.1, 511.8, 447.5, 462.2, 354.3, 358.3, 365.5, 371.3, 373.8, 377.0, 376.8, - 377.3, 377.6, 383.6, 372.4, 377.1, 382.3, 384.6, 386.4, 384.8, 382.9, 375.9, 365.9, 430.3, - 471.0, 427.2, 428.5, 403.2, 887.7, 380.7, 381.5, 382.0, 397.5, 401.8, 409.1, 418.8, 441.2, - 470.9, 490.1, 514.8, 516.4, 515.3, 490.4, 489.5, 486.6, 472.2, 410.8, 419.1, 428.3, 437.9, - 444.8, 466.6, 466.6, 465.3, 456.6, 449.4, 436.6, 430.0, 421.0, 419.8, 411.4, 398.0, 416.8, - 426.6, 425.1, 415.1, 407.2, 398.0, 385.9, 209.6, 209.3, 208.9, 208.5, 207.5, 216.6, 210.8, - 210.7, 213.0, 210.9, 211.9, 211.8, 211.8, 211.8, 211.6, 211.4, 216.1, 216.6, 216.7, 220.6, - 217.6, 218.4, 219.2, 224.9, 212.4, 237.7, 231.4, 251.4, 252.7, 252.0, 216.4, 231.7, 229.2, - 230.8, 250.7, 228.9, 228.5, 229.0, 397.4, 416.0, 438.4, 447.0, 439.3, 424.3, 218.7, 218.7, - 218.9, 218.8, 218.4, 445.6, 444.4, 455.8, 451.0, 454.8, 454.3, 455.3, 448.6, 443.6, 442.1, - 451.4, 458.2, 455.3, 452.1, 460.3, 460.0, 457.7, 467.1, 457.0, 454.1, 463.0, 459.5, 465.5, - 464.3, 456.8, 445.0, 425.5, 428.2, 218.8, 221.8, 222.7, 222.3, 223.1, 221.6, 223.5, 222.0, - 224.0, 225.4, 223.7, 222.5, 221.8, 220.9, 222.1, 224.0, 223.2, 221.6, 220.3, 218.8, 226.4, - 228.2, 225.4, 224.2, 216.9, 216.5, 217.1, 217.6, 217.9, 217.6, 217.0, 216.1, 216.6, 220.6, - 219.5, 218.9, 220.8, 221.5, 222.5, 220.2, 217.7, 216.4, 488.4, 497.5, 503.2, 515.2, 518.5, - 522.0, 535.7, 542.3, 542.3, 541.8, 536.7, 518.9, 493.5, 216.1, 217.8, 219.5, 220.5, 221.2, - 220.0, 516.0, 218.0, 218.4, 523.4, 502.5, 505.8, 494.9, 220.9, 221.3, 220.8, 220.4, 219.3, - 218.3, 217.5, 216.5, 215.5, 214.2, 213.0, 212.9, 213.3, 213.5, 473.5, 477.6, 487.5, 492.6, - 217.2, 219.2, 220.7, 220.7, 220.7, 218.9, 216.5, 214.4, 212.5, 210.6, 210.7, 210.9, 211.8, - 212.9, 213.7, 213.7, 213.7, 212.6 - ], - "slopeEast": [ - 0.002, -0.001, 0.056, 0.043, 0.022, 0.002, 0.007, -0.005, 0.014, 0.012, 0.002, -0.013, 0.046, - 0.027, -0.083, -0.005, -0.017, -0.01, -0.007, -0.03, -0.051, -0.056, -0.058, -0.088, -0.109, - -0.099, -0.085, -0.079, -0.077, 0.008, 0.005, 0.006, -0.01, 0.062, 0.068, 0.071, 0.074, 0.084, - 0.019, -0.001, 0.023, 0.02, 0.021, 0.024, 0.025, 0.031, 0.054, 0.031, 0.003, -0.022, -0.034, - -0.054, -0.055, -0.049, -0.047, -0.045, -0.038, -0.041, -0.051, -0.054, -0.073, -0.086, -0.104, - -0.05, -0.085, -0.083, 0.125, 0.082, 0.049, 0.018, 0.064, 0.034, -0.013, -0.004, -0.06, -0.087, - -0.128, -0.166, -0.129, -0.038, -0.154, -0.158, -0.163, -0.116, -0.12, 0.088, 0.055, 0.048, - 0.095, 0.036, 0.154, 0.016, -0.009, -0.018, -0.079, -0.121, -0.161, -0.174, 0.003, 0.037, 0.108, - 0.103, 0.1, 0.106, 0.101, -0.064, -0.045, 0.013, 0.149, 0.083, 0.078, 0.071, 0.039, -0.062, - -0.065, -0.118, -0.105, -0.072, -0.045, -0.025, -0.001, -0.008, -0.007, -0.02, -0.037, -0.058, - -0.078, -0.075, -0.069, -0.063, -0.054, -0.008, 0.003, 0.123, 0.036, 0.015, -0.005, 0.017, - 0.049, 0.086, 0.068, 0.013, 0.032, -0.024, -0.01, 0.005, 0.009, -0.005, -0.004, 0.021, 0.062, - -0.012, -0.014, -0.013, -0.031, 0.02, -0.004, -0.021, -0.005, -0.018, -0.026, -0.032, -0.038, - -0.046, -0.055, -0.063, -0.067, -0.007, 0.009, -0.048, -0.051, -0.051, -0.004, -0.015, -0.025, - -0.018, 0.002, -0.002, 0.005, 0.013, 0.02, 0.049, 0.013, 0.002, -0.023, -0.009, -0.075, -0.065, - 0.018, 0.02, 0.024, -0.023, -0.022, -0.049, 0.01, 0.056, -0.003, -0.001, 0.008, -0.048, -0.05, - -0.03, -0.015, 0.002, -0.045, -0.077, -0.052, -0.113, -0.035, 0.052, 0.029, -0.006, -0.008, - 0.119, 0.111, 0.049, 0.019, -0.001, -0.008, 0.003, 0.025, 0.028, 0.004, -0.059, 0.008, 0.005, - -0.0, 0.055, 0.03, -0.044, -0.024, -0.002, -0.029, -0.015, -0.028, -0.04, -0.079, -0.084, - -0.073, 0.118, 0.104, 0.095, 0.098, 0.122, -0.042, 0.014, 0.108, 0.117, -0.077, -0.066, -0.052, - 0.006, 0.018, -0.026, -0.008, 0.016, -0.019, -0.02, 0.006, 0.033, 0.056, 0.035, 0.017, 0.002, - 0.011, 0.009, -0.015, 0.039, -0.016, -0.019, 0.073, 0.06, 0.028, 0.012, -0.052, -0.037, -0.027, - -0.026, -0.025, -0.027, -0.034, -0.033, -0.112, -0.098, -0.018, -0.005, 0.014, -0.002, -0.012, - -0.021, -0.041, -0.06, -0.073, -0.068, -0.007, 0.023, -0.002, 0.014, 0.031, 0.042, 0.045, 0.05, - 0.06, 0.075, 0.066, 0.054, 0.029, 0.03, -0.066, -0.045, -0.033, -0.035, 0.1, 0.072, 0.022, - -0.017, 0.002, 0.006, 0.105, 0.007, -0.015, 0.014, -0.019, -0.045, 0.021, -0.027, -0.032, - -0.043, 0.023, -0.048, 0.051, -0.072, -0.099, -0.013, 0.016, 0.062, 0.05, 0.066, 0.041, 0.022, - -0.031, -0.028, -0.003, 0.047, -0.019, -0.007, 0.014, -0.047, 0.019, -0.023, -0.023, 0.008, - -0.064, 0.049, -0.035, -0.026, 0.01, 0.043, 0.057, 0.094, -0.076, -0.07, 0.043, 0.029, 0.051, - 0.001, 0.036, 0.056, -0.016, -0.042, -0.015, -0.0, 0.037, 0.052, 0.089, 0.032, 0.021, 0.06, - -0.018, 0.018, 0.002, 0.036, 0.058, -0.043, 0.005, -0.0, -0.004, -0.084, -0.088, 0.055, -0.004, - 0.02, 0.027, 0.018, -0.003, -0.013, -0.01, -0.005, 0.032, 0.037, -0.085, -0.114, 0.016, -0.076, - -0.081, 0.043, 0.029, 0.014, -0.247, -0.334, -0.183, -0.03, -0.023, 0.027, 0.067, 0.018, -0.17, - 0.04, 0.076, 0.16, 0.142, 0.214, -0.239, -0.036, 0.236, 0.006, -0.075, -0.015, -0.134, 0.191, - -0.098, -0.235, -0.094, -0.348, -0.156, -0.126, 0.06, -0.008, 0.039, 0.184, 0.048, 0.037, 0.035, - -0.057, -0.06, 0.062, -0.295, -0.071, -0.175, 0.046, -0.045, -0.173, -0.173, -0.161, -0.148, - 0.042, -0.034, -0.145, 0.247, 0.002, -0.209, 0.028, -0.129, -0.037, 0.154, -0.069, -0.023, - 0.149, 0.119, -0.146, 0.175, 0.112, -0.005, -0.029, -0.11, -0.064, -0.06, -0.018, -0.04, 0.03, - -0.087, -0.043, -0.015, -0.031, -0.13, -0.068, -0.06, 0.001, -0.021, -0.0, -0.013, 0.032, 0.012, - -0.025, 0.013, 0.081, 0.008, -0.101, 0.006, -0.063, -0.072, -0.034, -0.109, -0.03, -0.058, - -0.068, -0.174, -0.1, -0.092, -0.088, -0.053, 0.072, 0.007, -0.043, -0.029, -0.004, -0.033, - -0.07, -0.071, -0.07, -0.077, -0.07, -0.021, -0.02, -0.061, -0.004, -0.114, -0.02, -0.023, - 0.032, 0.05, -0.037, -0.005, -0.02, -0.109, -0.063, 0.014, -0.015, -0.037, 0.007, 0.019, 0.035, - 0.051, 0.064, -0.018, -0.034, -0.025, 0.038, -0.074, -0.071, -0.068, -0.065, -0.061, -0.056, - -0.05, -0.038, -0.032, -0.02, 0.035, -0.023, -0.034, -0.042, -0.009, -0.053, -0.061, -0.048, - 0.032, 0.055, -0.052, 0.019, 0.04, -0.026, 0.007, -0.033, -0.04, -0.044, -0.047, 0.134, -0.002, - 0.095, 0.061, -0.082, -0.127, 0.039, 0.057, 0.077, 0.092, 0.081, 0.007, -0.041, 0.057, -0.038, - 0.02, 0.004, -0.126, -0.118, -0.042, -0.061, -0.009, -0.034, -0.028, -0.016, 0.066, -0.008, - -0.033, -0.062, -0.168, 0.054, 0.058, -0.007, 0.007, -0.054, -0.042, -0.257, -0.152, 0.009, - 0.029, 0.032, 0.036, -0.033, -0.046, -0.05, 0.018, -0.059, -0.065, -0.078, -0.093, -0.109, - -0.126, -0.136, -0.072, -0.057, -0.05, -0.039, -0.032, -0.029, -0.024, -0.055, -0.05, -0.057, - 0.019, 0.031, 0.057, 0.078, 0.091, 0.084, 0.071, 0.05, 0.033, 0.066, 0.024, -0.039, -0.043, - -0.062, -0.086, -0.078, -0.035, -0.041, 0.114, -0.004, 0.08, -0.043, 0.008, 0.035, 0.117, 0.075, - 0.091, -0.088, -0.074, -0.157, -0.187, 0.023, 0.023, 0.021, 0.021, 0.017, 0.002, -0.01, 0.054, - 0.037, 0.016, 0.058, -0.096, -0.292, 0.009, 0.007, -0.003, -0.011, -0.009, -0.005, -0.017, - -0.031, -0.04, -0.029, -0.019, 0.007, 0.036, 0.064, 0.06, 0.091, 0.084, 0.021, 0.044, 0.024, - 0.007, 0.007, 0.006, -0.001, -0.004, -0.011, -0.026, -0.037, -0.048, -0.06, -0.057, -0.054, - -0.051, -0.031, -0.014, -0.007 - ], - "slopeNorth": [ - -0.005, 0.005, -0.003, 0.002, -0.006, -0.016, -0.044, -0.027, -0.024, -0.026, -0.026, -0.026, - -0.05, -0.054, 0.02, -0.042, -0.033, -0.022, -0.009, 0.008, 0.025, 0.032, 0.037, 0.003, 0.01, - 0.01, 0.013, 0.017, 0.026, 0.059, 0.018, -0.02, -0.039, 0.024, 0.024, 0.008, -0.005, -0.003, - -0.06, -0.088, -0.024, -0.033, -0.037, -0.039, -0.046, -0.052, -0.026, -0.019, -0.023, -0.025, - -0.027, -0.106, -0.113, -0.118, -0.111, -0.103, -0.016, -0.016, -0.129, -0.122, -0.096, -0.075, - -0.046, -0.071, 0.056, 0.061, -0.108, -0.077, 0.028, 0.067, -0.029, -0.009, 0.048, -0.009, - -0.029, -0.018, 0.006, 0.025, 0.144, 0.19, 0.17, 0.167, 0.149, -0.078, -0.083, -0.0, -0.081, - -0.04, -0.001, -0.033, -0.082, -0.031, 0.061, 0.14, 0.078, 0.132, 0.104, 0.127, -0.011, -0.01, - 0.071, 0.129, 0.113, 0.103, 0.13, -0.038, -0.037, 0.044, 0.052, 0.016, 0.01, -0.01, -0.02, - -0.014, 0.06, 0.086, 0.082, 0.067, 0.049, 0.051, 0.058, -0.08, -0.095, -0.099, -0.098, -0.093, - -0.064, -0.024, 0.007, 0.03, 0.041, -0.085, -0.064, -0.021, -0.069, -0.063, -0.054, -0.027, - 0.013, 0.058, 0.082, 0.091, 0.065, 0.04, 0.085, 0.117, 0.139, 0.134, 0.059, 0.047, 0.008, 0.002, - 0.005, 0.01, 0.034, 0.039, 0.068, 0.077, -0.041, -0.017, -0.011, -0.017, -0.021, -0.021, -0.003, - 0.016, 0.034, -0.057, -0.046, -0.067, -0.062, -0.059, -0.032, -0.028, -0.023, -0.01, -0.01, - -0.033, -0.028, -0.004, 0.019, -0.01, 0.056, 0.067, -0.061, -0.049, -0.108, -0.079, -0.0, 0.018, - 0.024, 0.053, 0.08, 0.085, -0.008, 0.015, 0.016, 0.027, 0.048, -0.05, -0.038, -0.058, -0.086, - -0.001, -0.061, -0.038, -0.014, 0.027, 0.062, -0.036, -0.007, 0.046, -0.023, -0.001, 0.01, - -0.073, 0.053, 0.073, -0.02, 0.004, -0.001, -0.014, -0.069, -0.016, -0.041, 0.001, 0.021, - -0.017, -0.019, -0.115, -0.11, -0.083, -0.119, -0.097, -0.076, -0.101, -0.069, -0.054, -0.022, - -0.045, -0.028, -0.016, -0.008, 0.019, -0.037, 0.005, 0.007, 0.01, -0.092, -0.096, -0.079, - 0.074, 0.07, -0.076, -0.025, -0.075, -0.039, 0.003, -0.006, 0.013, -0.03, -0.064, -0.079, - -0.076, -0.056, -0.026, 0.042, -0.084, 0.038, 0.055, 0.002, 0.033, 0.01, -0.003, 0.001, -0.02, - -0.041, -0.057, -0.056, -0.053, -0.045, -0.037, 0.043, 0.037, -0.023, -0.013, -0.012, 0.063, - 0.029, 0.024, 0.012, -0.007, 0.01, 0.006, -0.057, 0.007, -0.017, 0.02, 0.061, 0.058, 0.039, - 0.021, 0.001, -0.02, -0.025, -0.024, 0.039, 0.052, 0.03, 0.03, 0.028, 0.035, 0.003, 0.005, - 0.027, -0.048, -0.059, 0.005, -0.037, -0.029, -0.058, -0.066, -0.009, -0.02, 0.014, -0.009, - -0.015, -0.01, -0.045, -0.036, -0.085, -0.017, 0.011, -0.052, 0.048, -0.025, -0.024, -0.035, - -0.031, -0.05, -0.058, -0.013, -0.05, -0.053, -0.058, -0.033, -0.017, 0.001, -0.025, -0.066, - -0.023, -0.014, -0.011, -0.059, -0.019, -0.009, 0.005, -0.007, -0.034, -0.051, 0.002, 0.036, - 0.0, 0.007, -0.022, -0.028, -0.046, -0.051, -0.018, -0.021, -0.013, 0.012, -0.005, -0.035, - -0.036, 0.011, -0.065, 0.025, 0.006, 0.018, -0.103, 0.005, -0.007, -0.025, -0.061, -0.044, - -0.049, -0.008, 0.004, -0.043, 0.022, -0.062, -0.019, -0.055, 0.001, -0.01, -0.057, -0.005, - -0.051, -0.064, -0.023, 0.029, -0.044, 0.079, 0.066, -0.049, -0.043, 0.043, 0.037, 0.009, -0.04, - -0.175, -0.046, -0.025, -0.055, -0.045, 0.01, -0.078, -0.036, -0.127, -0.126, -0.145, 0.102, - 0.094, -0.123, 0.055, -0.109, 0.133, -0.142, -0.009, -0.085, 0.067, 0.024, 0.056, -0.06, 0.156, - 0.025, -0.068, 0.018, -0.106, 0.077, 0.019, -0.02, -0.043, 0.021, -0.021, 0.053, -0.023, -0.091, - -0.044, 0.016, 0.174, 0.024, 0.172, 0.213, -0.05, -0.021, -0.051, -0.255, 0.041, 0.076, -0.168, - 0.031, -0.153, -0.058, -0.022, 0.063, -0.084, -0.122, -0.153, -0.157, -0.171, 0.014, 0.054, - 0.036, 0.084, 0.009, 0.019, 0.018, -0.012, 0.013, 0.008, 0.011, 0.061, 0.061, 0.057, -0.013, - -0.036, -0.024, -0.045, -0.046, -0.101, -0.156, -0.066, -0.239, -0.1, -0.077, -0.243, -0.08, - 0.073, 0.039, 0.179, 0.106, 0.005, 0.086, 0.044, 0.321, 0.232, 0.195, 0.145, -0.074, -0.069, - -0.057, 0.021, -0.1, -0.165, 0.063, 0.139, 0.12, 0.091, 0.134, 0.082, 0.064, -0.056, -0.118, - -0.146, -0.004, -0.123, -0.142, -0.092, -0.121, 0.172, 0.209, 0.083, -0.15, -0.088, -0.128, - -0.152, -0.196, 0.004, -0.017, -0.027, -0.037, -0.042, 0.021, 0.014, 0.009, 0.003, 0.082, 0.074, - 0.061, 0.048, 0.031, 0.013, -0.006, 0.081, 0.074, 0.055, -0.036, 0.041, 0.024, 0.006, -0.068, - -0.022, 0.073, 0.021, 0.055, 0.009, 0.022, 0.079, -0.019, 0.052, 0.08, 0.02, 0.073, 0.04, 0.01, - 0.224, 0.291, 0.218, -0.011, -0.137, -0.234, 0.091, 0.094, 0.095, 0.093, 0.062, 0.02, 0.061, - 0.003, 0.044, -0.063, 0.145, -0.012, -0.046, -0.011, 0.075, 0.117, 0.046, -0.033, 0.108, 0.084, - -0.011, -0.094, -0.024, -0.13, 0.075, 0.1, 0.124, -0.018, -0.058, -0.136, -0.149, -0.227, - -0.022, 0.105, 0.119, 0.113, 0.09, 0.076, 0.045, -0.045, 0.032, 0.029, 0.034, 0.051, 0.055, - 0.044, 0.028, -0.072, -0.095, -0.088, -0.06, -0.032, -0.005, 0.003, -0.016, -0.008, 0.039, - 0.085, 0.076, 0.061, 0.046, 0.035, 0.031, 0.022, 0.018, 0.014, 0.006, 0.014, 0.009, -0.002, - -0.002, 0.003, -0.003, -0.024, -0.018, 0.068, 0.212, 0.049, 0.187, 0.06, 0.024, 0.003, -0.084, - -0.173, 0.03, -0.138, -0.17, -0.157, 0.006, -0.007, -0.026, -0.034, -0.038, -0.045, 0.001, - -0.075, -0.067, 0.237, 0.215, 0.109, 0.055, -0.068, -0.066, -0.059, -0.054, -0.059, -0.062, - -0.065, -0.07, -0.072, -0.064, -0.054, -0.045, -0.035, -0.022, 0.059, 0.161, 0.071, 0.021, - -0.021, -0.027, -0.033, -0.039, -0.044, -0.038, -0.029, -0.034, -0.057, -0.078, -0.075, -0.071, - -0.076, -0.085, -0.083, -0.057, -0.03, -0.018 - ] -} diff --git a/src/app/features/scene/ridge/view.test.ts b/src/app/features/scene/ridge/view.test.ts new file mode 100644 index 00000000..5e796c11 --- /dev/null +++ b/src/app/features/scene/ridge/view.test.ts @@ -0,0 +1,344 @@ +import { describe, expect, it } from 'vitest'; +import { + cardArc, + cardPose, + FALLBACK_VIEW, + groundRowsNeeded, + HFOV_MAX_DEG, + HORIZON_AT, + maxSpeed, + offsetRange, + RIDGE_BAND_FRAC, + SEGMENT_S, + SPEED_CEILING_DEG_S, + sweepArc, + windowFor, +} from './view'; +import { KEEP_MARGIN_TILES, residentTiles, runTiles } from './ring'; +import { parseManifest } from './manifest'; +import { wireManifest } from './manifest.fixture'; +import type { View } from './view'; + +const VIEWPORTS: [number, number][] = [ + [390, 844], + [1920, 1080], + [3440, 1440], +]; + +const manifest = parseManifest(wireManifest(), '/d/'); // distances: card 0 1000-1400 m, card 1 10-14 km, card 2 39-41 km +const withView = (over: Record) => + parseManifest(wireManifest({ view: { ...(wireManifest().view as object), ...over } }), '/d/'); +const DEG = Math.PI / 180; + +describe('windowFor', () => { + it('gives a 16:9 viewport the scale and the 65.45 degrees it had when a window was baked, and a phone the band scale', () => { + const v = FALLBACK_VIEW; + const wide = windowFor(v, 1920, 1080); + expect(wide.plane.scale).toBeCloseTo((1920 * 1.1) / 1280, 9); + expect(wide.camera.hfovDeg).toBeCloseTo(72 / 1.1, 9); + expect(HFOV_MAX_DEG).toBeCloseTo(65.4545, 4); + const phone = windowFor(v, 390, 844); + expect(phone.plane.scale).toBeCloseTo((RIDGE_BAND_FRAC * 844) / v.planeH, 9); + expect(phone.camera.hfovDeg).toBeCloseTo(390 / (phone.plane.scale * v.pxPerDegH), 9); + }); + + it.each(VIEWPORTS)( + "%i x %i: the camera never sees more than the widest field, the horizon is the plane's, the plane reaches the bottom", + (w, h) => { + const v = FALLBACK_VIEW; + const win = windowFor(v, w, h); + expect(win.camera.hfovDeg).toBeLessThanOrEqual(HFOV_MAX_DEG + 1e-9); + expect(win.plane.h).toBeLessThanOrEqual(h * 4); // sanity: scale is not runaway + const horizonY = h - win.plane.bottom - win.plane.h + win.plane.scale * v.horizonRow; + expect(Math.abs(horizonY - win.camera.horizonAt * h)).toBeLessThan(0.5); + expect(win.camera.azimuthDeg).toBe(v.lookAzDeg); + expect(win.camera.vfovDeg / win.camera.hfovDeg).toBeCloseTo(h / w, 9); // one scale on both axes + expect(win.plane.bottom).toBeLessThanOrEqual(0); + } + ); + + it('puts the horizon at one fraction of the height, whatever the viewport or the view', () => { + const other: View = { ...FALLBACK_VIEW, lookAzDeg: 10, horizonRow: 200, pxPerDegH: 10 }; + for (const v of [FALLBACK_VIEW, other]) + for (const [w, h] of [...VIEWPORTS, [1024, 768], [375, 812], [1100, 619]] as [number, number][]) + expect(windowFor(v, w, h).camera.horizonAt).toBe(HORIZON_AT); + expect(HORIZON_AT).toBeGreaterThan(0.5); + expect(HORIZON_AT).toBeLessThan(1); + }); + + it('shows about 31 degrees of sky above the horizon in a 16:9 desktop cell', () => { + const { camera } = windowFor(FALLBACK_VIEW, 1100, 619); + const sky = camera.horizonAt * camera.vfovDeg; + expect(sky).toBeGreaterThan(29); + expect(sky).toBeLessThan(34); + }); + + it('points the camera at the rest azimuth, and a north-crossing one is not wrapped', () => { + expect(windowFor({ ...FALLBACK_VIEW, lookAzDeg: 355 }, 1920, 1080).camera.azimuthDeg).toBe(355); + }); +}); + +describe('cardPose', () => { + const win = windowFor(manifest.view, 1920, 1080); + const rest = manifest.view.lookAzDeg; + const k = win.plane.scale * manifest.view.pxPerDegH; + + it('at phi 0 is the tangent R / (R - r) the camera pushed forward gives, a card pans with the heading, and the offset 0 leaves it at scale 1', () => { + // Heading 135 is tile 1's centre: card 1 stands 12 km away there. + const p = cardPose(manifest, 1, 135, 0, 200, win); + expect(p.scale).toBeCloseTo(12000 / (12000 - 200), 2); + expect(Math.abs(p.scale - 12000 / (12000 - 200))).toBeLessThan(0.002); + const flat = cardPose(manifest, 1, 135, 0, 0, win); + expect(flat.scale).toBeCloseTo(1, 9); + // The column the view faces lands on the centre: at scale s the container shifts by -s (h - rest) k. + expect(flat.shiftPx).toBeCloseTo(-(135 - rest) * k, 6); + }); + + it('is mirrored behind the centre: a backward offset shrinks the card and a larger one shrinks it more', () => { + const fwd = cardPose(manifest, 0, 45, 0, 100, win).scale; + const back = cardPose(manifest, 0, 45, 0, -100, win).scale; + expect(fwd).toBeGreaterThan(1); + expect(back).toBeLessThan(1); + expect(cardPose(manifest, 0, 45, 0, -200, win).scale).toBeLessThan(back); + }); + + it('at phi 90 shifts the card sideways by r / R x 57.3 degrees and leaves its size alone', () => { + const at = (phi: number) => cardPose(manifest, 1, 135, phi, 200, win); + const p = at(90); + // The sideways part of a pose: where the line meets the heading's own column, a0 = shift / k + s (h - rest). + const a0 = (q: { scale: number; shiftPx: number }) => q.shiftPx / k + q.scale * (135 - rest); + expect(a0(at(0))).toBeCloseTo(0, 6); + // A camera to the clockwise side of the heading (east of a north view) sees the card to the left of it, and one on the other side to the right. + expect(a0(p)).toBeLessThan(0); + expect(a0(at(-90))).toBeGreaterThan(0); + // r / R x 57.3 degrees at the heading's own column; the line fitted over the arc takes the mean of cos over it, about 0.93 of that. + const centre = (200 / 12000) * (180 / Math.PI); + expect(Math.abs(a0(p)) / centre).toBeGreaterThan(0.9); + expect(Math.abs(a0(p)) / centre).toBeLessThanOrEqual(1); + expect(p.scale).toBeCloseTo(1, 2); + }); + + it('is the same at a heading and a revolution on: nothing about it wraps', () => { + const a = cardPose(manifest, 0, 100, 10, 80, win); + const b = cardPose(manifest, 0, 100 + 360, 10, 80, win); + expect(b.scale).toBeCloseTo(a.scale, 9); + // The unwrapped heading moves the container a revolution, which is what keeps the tiles at their unwrapped azimuth. + expect(b.shiftPx - a.shiftPx).toBeCloseTo(-a.scale * 360 * k, 4); + }); + + it('is exact where the sheet is: a card seen from its own circle lands on the line it fits', () => { + // The fitted line passes through the exact angle at the middle of the arc within a card pixel at a small offset. + const R = 12000; + const r = 150; + const p = cardPose(manifest, 1, 135, 0, r, win); + const exact = Math.atan2(R * Math.sin(10 * DEG), R * Math.cos(10 * DEG) - r) / DEG; + const line = (p.shiftPx / k + p.scale * (135 - rest)) + p.scale * 10; + expect(Math.abs(exact - line) * k).toBeLessThan(0.5); + }); +}); + +describe('cardArc', () => { + const win = windowFor(manifest.view, 1920, 1080); + it('is the viewport arc at the rest heading with no offset, and follows the heading and the scale', () => { + const rest = manifest.view.lookAzDeg; + const half = win.camera.hfovDeg / 2; + const flat = cardArc(manifest.view, win, 1920, cardPose(manifest, 1, rest, 0, 0, win)); + expect(flat.fromDeg).toBeCloseTo(rest - half, 6); + expect(flat.toDeg).toBeCloseTo(rest + half, 6); + const turned = cardArc(manifest.view, win, 1920, cardPose(manifest, 1, rest + 400, 0, 0, win)); + expect(turned.fromDeg).toBeCloseTo(rest + 400 - half, 6); + // A card that is larger on screen shows less of itself. + const near = cardPose(manifest, 0, 45, 0, 100, win); + const arc = cardArc(manifest.view, win, 1920, near); + expect(arc.toDeg - arc.fromDeg).toBeCloseTo((2 * half) / near.scale, 6); + }); +}); + +describe('offsetRange', () => { + it('is the bake worst-case bound either way round in the offset-only mode, whose camera circles the whole ring of angles', () => { + for (const [w, h] of VIEWPORTS) { + const win = windowFor(manifest.view, w, h); + expect(offsetRange(manifest, win, 'offset')).toEqual([-manifest.camera.rMaxM, manifest.camera.rMaxM]); + // The angle the camera stands at does not matter there: it is going to all of them. + expect(offsetRange(manifest, win, 'offset', 0)).toEqual(offsetRange(manifest, win, 'offset', 123)); + } + }); + + it('lets a forward offset go as far as the bake phi 0 bound where the offset turns with the view, and a backward one only as far as the worst case', () => { + for (const [w, h] of VIEWPORTS) { + const win = windowFor(manifest.view, w, h); + for (const mode of ['both', 'still'] as const) { + const [lo, hi] = offsetRange(manifest, win, mode); + expect(hi).toBe(manifest.camera.rMaxForwardM); + expect(lo).toBe(-manifest.camera.rMaxM); + } + } + expect(manifest.camera.rMaxForwardM).toBeGreaterThan(manifest.camera.rMaxM); + }); + + it('a camera held at an angle of its circle is bounded as the circle is: the bound follows where the camera stands, not only the mode', () => { + const win = windowFor(manifest.view, 1920, 1080); + expect(offsetRange(manifest, win, 'still', 0)[1]).toBe(manifest.camera.rMaxForwardM); + expect(offsetRange(manifest, win, 'still', 360)[1]).toBe(manifest.camera.rMaxForwardM); + expect(offsetRange(manifest, win, 'still', 137)).toEqual([-manifest.camera.rMaxM, manifest.camera.rMaxM]); + }); + + it('keeps a default +200 m where phi stays 0 and the bake allows it, and takes it to the worst-case bound where the camera circles', () => { + const vienna = parseManifest( + wireManifest({ camera: { r_max_m: 98.2, r_max_forward_m: 205.4 } }), + '/d/' + ); + const win = windowFor(vienna.view, 1920, 1080); + const clamp = (mode: 'both' | 'offset' | 'still') => { + const [lo, hi] = offsetRange(vienna, win, mode); + return Math.min(hi, Math.max(lo, 200)); + }; + expect(clamp('both')).toBe(200); + expect(clamp('still')).toBe(200); + expect(clamp('offset')).toBe(98.2); + }); + + it('gives up part of its backward half where the nearest card shrunk by R / (R + r) would lift its foot above the viewport bottom, and all of it past that', () => { + // A phone, 390 x 844, where the plane is only as tall as the band needs: keep = (1 - HORIZON_AT) 844 / (scale (planeH - horizonRow)). Put the horizon row so that keep is 0.95 (158 rows under it, above the 150 the manifest guarantees), and the nearest card is 1000 m away. + const scale = windowFor(manifest.view, 390, 844).plane.scale; + const near = withView({ horizon_row: 600 - (0.15 * 844) / 0.95 / scale }); + const win = windowFor(near.view, 390, 844); + const [lo, hi] = offsetRange(near, win, 'both'); + expect(hi).toBe(180); + expect(lo).toBeCloseTo(-1000 * (1 / 0.95 - 1), 6); + // At that offset the card's foot is exactly at the viewport bottom. + const s = 1000 / (1000 - lo); + expect(s * win.plane.scale * (near.view.planeH - near.view.horizonRow)).toBeCloseTo(0.15 * 844, 6); + // A plane with exactly the ground rows the manifest guarantees (keep 1): the backward bound is 0 from the same formula, with no case of its own. + const exact = withView({ horizon_row: 600 - groundRowsNeeded(600) }); + const [elo, ehi] = offsetRange(exact, windowFor(exact.view, 390, 844), 'both'); + expect(elo).toBeCloseTo(0, 9); + expect(ehi).toBe(180); + }); + + it('on a desktop viewport, where the width binds the scale and keep is well under 1, the backward offset stops where the nearest card shrunk by R / (R + r) lifts its foot to the bottom edge', () => { + // 1920 x 1080 with the ground rows the manifest guarantees: scale 1.65 (the width term), so keep = 0.15 x 1080 / (1.65 x 150) = 0.65, far under the 0.75 a clamped keep would stop at. The bake's r_max is made large enough that the foot, not r_max, binds. + const wide = parseManifest(wireManifest({ view: { ...(wireManifest().view as object), horizon_row: 450 }, camera: { r_max_m: 600, r_max_forward_m: 700 } }), '/d/'); + const win = windowFor(wide.view, 1920, 1080); + const keep = (0.15 * 1080) / (win.plane.scale * 150); + expect(keep).toBeGreaterThan(0.6); + expect(keep).toBeLessThan(0.7); + const [lo, hi] = offsetRange(wide, win, 'both'); + expect(lo).toBeCloseTo(-1000 * (1 / keep - 1), 6); // about -538 m + expect(-lo).toBeLessThan(600); + expect(hi).toBe(700); + expect(offsetRange(wide, win, 'offset')).toEqual([lo, -lo]); + }); + + it('on a 3440 x 1440 ultrawide, where keep is about 0.49, the backward offset still follows keep and is not floored at 0.5', () => { + const wide = parseManifest(wireManifest({ view: { ...(wireManifest().view as object), horizon_row: 450 }, camera: { r_max_m: 1500, r_max_forward_m: 1600 } }), '/d/'); + const win = windowFor(wide.view, 3440, 1440); + const keep = (0.15 * 1440) / (win.plane.scale * 150); + expect(keep).toBeGreaterThan(0.45); + expect(keep).toBeLessThan(0.5); + const [lo] = offsetRange(wide, win, 'both'); + expect(lo).toBeCloseTo(-1000 * (1 / keep - 1), 6); // a keep floored at 0.5 would stop at -1000 m + expect(-lo).toBeGreaterThan(1000); + }); + + it('reads the ground rows from the runtime constants: 150 of 600, so the plane reaches the bottom of every viewport at rest', () => { + expect(groundRowsNeeded(600)).toBeCloseTo(150, 9); + const exact = withView({ horizon_row: 600 - groundRowsNeeded(600) }); + for (const [w, h] of VIEWPORTS) { + expect(windowFor(exact.view, w, h).plane.bottom).toBeLessThanOrEqual(1e-9); + } + }); + + it('gives up the same part of its forward half in the offset-only mode: the camera circles round to phi 180 and the nearest card shrinks as it does for a backward offset', () => { + const scale = windowFor(manifest.view, 390, 844).plane.scale; + const near = withView({ horizon_row: 600 - (0.15 * 844) / 0.95 / scale }); + const win = windowFor(near.view, 390, 844); + const [lo, hi] = offsetRange(near, win, 'offset'); + expect(hi).toBeCloseTo(1000 * (1 / 0.95 - 1), 6); + expect(lo).toBe(-hi); + // The camera at phi 180 and offset hi puts the nearest card at the scale that leaves its foot on the bottom edge. + const R = 1000; + const p = cardPose(near, 0, near.view.lookAzDeg, 180, hi, win); + expect(Math.abs(p.scale - R / (R + hi))).toBeLessThan(0.02); // the fitted line is within a hair of the tangent the clamp uses + const exact = withView({ horizon_row: 600 - groundRowsNeeded(600) }); + const [elo, ehi] = offsetRange(exact, windowFor(exact.view, 390, 844), 'offset'); + expect(elo).toBeCloseTo(0, 9); + expect(ehi).toBeCloseTo(0, 9); + }); +}); + +describe('maxSpeed', () => { + const ring = parseManifest(wireManifest({}, 3, 32), '/d/'); // the ring as the baker cuts it: 32 tiles of 11.25 degrees, rmin 1000 m, r_max 100, forward 180 + const win = windowFor(ring.view, 1920, 1080); + const poses = (v: number, h: number, off: number) => (card: number, ms: number) => + cardPose(ring, card, h + (v * ms) / 1000, 0, off, win); + /** The most tiles the loader would hold for a view turning at v, over a sweep of headings and the offsets the mode allows. */ + const mostHeld = (v: number): number => { + const [lo, hi] = offsetRange(ring, win, 'both'); + let most = 0; + for (const off of [lo, 0, hi]) { + for (let h = 0; h < 360; h += 3.7) { + const arc = sweepArc(ring.view, win, 1920, 3, poses(v, h, off), 0); + const keep = residentTiles( + ring.view, + (arc.fromDeg + arc.toDeg) / 2, + (arc.toDeg - arc.fromDeg) / 2 + KEEP_MARGIN_TILES * 11.25 + ); + most = Math.max(most, keep.length); + } + } + return most; + }; + const N = runTiles(ring.view, HFOV_MAX_DEG, ring.camera.rMaxForwardM, 1000); + + it('is what the baked resident count leaves in the mode where the view turns, and the ceiling where it does not', () => { + const v = maxSpeed(ring, 'both'); + expect(v).toBeGreaterThan(0); + expect(v).toBeLessThan(SPEED_CEILING_DEG_S); + expect(maxSpeed(ring, 'offset')).toBe(SPEED_CEILING_DEG_S); + expect(maxSpeed(ring, 'still')).toBe(SPEED_CEILING_DEG_S); + // Held to N by the sweep of SEGMENT_S seconds at the bound, and over it a little above. + expect(mostHeld(v)).toBeLessThanOrEqual(N); + expect(mostHeld(v * 1.6)).toBeGreaterThan(N); + expect(SEGMENT_S).toBe(30); + }); + + it('is never above the ceiling, whatever room the ring has, and never below 0', () => { + const open = parseManifest(wireManifest({ camera: { r_max_m: 0.1, r_max_forward_m: 0.1 } }, 3, 32), '/d/'); + expect(maxSpeed(open, 'both')).toBeLessThanOrEqual(SPEED_CEILING_DEG_S); + const tight = parseManifest(wireManifest({ camera: { r_max_m: 100, r_max_forward_m: 100 } }, 3, 32), '/d/'); + expect(maxSpeed(tight, 'both')).toBeGreaterThanOrEqual(0); + }); +}); + +describe('sweepArc', () => { + const ring = parseManifest(wireManifest({}, 3, 32), '/d/'); + const win = windowFor(ring.view, 1920, 1080); + // The offset-only mode at 12 degrees a second and the offset own bound: the nearest card swings out and back over the stretch. + const v = 12; + const [, hi] = offsetRange(ring, win, 'offset'); + const poseAt = (card: number, ms: number) => cardPose(ring, card, 100, 30 + (v * ms) / 1000, hi, win); + + it('covers every pose the stretch passes through, not the two it begins and ends with', () => { + const swept = sweepArc(ring.view, win, 1920, 3, poseAt, 0); + let from = Infinity; + let to = -Infinity; + for (let ms = 0; ms <= SEGMENT_S * 1000; ms += 50) { + for (let i = 0; i < 3; i += 1) { + const a = cardArc(ring.view, win, 1920, poseAt(i, ms)); + from = Math.min(from, a.fromDeg); + to = Math.max(to, a.toDeg); + } + } + // Within a hundredth of a degree of the dense answer, either side: it covers the swing and is not the whole ring. + expect(Math.abs(swept.fromDeg - from)).toBeLessThan(0.01); + expect(Math.abs(swept.toDeg - to)).toBeLessThan(0.01); + // The two ends alone fall short of the dense answer by whole degrees. + const ends = [0, SEGMENT_S * 1000].flatMap((ms) => + [0, 1, 2].map((i) => cardArc(ring.view, win, 1920, poseAt(i, ms))) + ); + const endFrom = Math.min(...ends.map((a) => a.fromDeg)); + const endTo = Math.max(...ends.map((a) => a.toDeg)); + expect(endFrom - from > 1 || to - endTo > 1).toBe(true); + }); +}); diff --git a/src/app/features/scene/ridge/view.ts b/src/app/features/scene/ridge/view.ts new file mode 100644 index 00000000..a750b565 --- /dev/null +++ b/src/app/features/scene/ridge/view.ts @@ -0,0 +1,267 @@ +// The one View: where the sky's camera stands and looks, and where the ridge cards sit against it. A baked place's manifest +// (`view` and `place`, manifest schema 3) is a View; a sky with no planes uses FALLBACK_VIEW. `windowFor` is the single owner of the +// registration between sky and ridge: one View and a viewport in, the sky Camera and the plane's placement out. `offsetRange` is the one +// clamp on the camera's offset and `cardPose` the one place a card's scale and shift are derived (ruling ridge-camera-on-circle). Nothing +// else chooses a field of view, a horizon row, an azimuth, a scale or a shift. +import { distanceAt, KEEP_MARGIN_TILES, norm, runTiles } from './ring'; +import type { RidgeManifest } from './manifest'; +import type { RotationMode } from './heading'; + +/** Where the observer stands. `id` names the baked place (it keys a rebuild); `altitudeKm` is the ground height, eye height excluded. */ +export interface Place { + id: string; + lat: number; + lon: 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 ring the planes cover, all 360 degrees, absolute compass (column 0 = north), cut into `tiles` azimuth tiles of `tileW` columns + * (`apron` real neighbour columns each side in a tile's files). Angles are degrees, planes are in plane pixels. + */ +export interface ManifestView { + /** The rest azimuth: the compass azimuth the view faces before anything turns it, degrees clockwise from north. */ + lookAzDeg: number; + ringW: number; + tileW: number; + tiles: number; + apron: number; + planeH: number; + pxPerDegH: number; + /** Plane pixels per degree of elevation (the baker draws the vertical exaggerated: it is not `pxPerDegH`). */ + pxPerDegV: number; + /** Row of the horizon in the plane, from its top. */ + horizonRow: number; +} + +export interface View extends ManifestView { + place: Place; +} + +/** + * The camera of the sky. Angle-linear, as the planes are (`pxPerDegH` is constant across a plane): a pixel's azimuth is + * `azimuthDeg + (x - 0.5) * hfovDeg` and its elevation is `(horizonAt - y) * vfovDeg`, x and y as fractions of the viewport. + */ +export interface Camera { + /** Compass azimuth at the centre column. */ + azimuthDeg: number; + hfovDeg: number; + vfovDeg: number; + /** Where the horizon sits down the viewport, as a fraction of its height (0 top). */ + horizonAt: number; +} + +/** The sky of a scene with no planes (a failed load): Vienna facing south-west, with the numbers of the Vienna ring bake. */ +export const FALLBACK_VIEW: View = { + place: { id: 'vienna', lat: 48.1929826, lon: 16.3534237, altitudeKm: 0.183, tz: 'Europe/Vienna' }, + lookAzDeg: 214, + ringW: 6400, + tileW: 200, + tiles: 32, + apron: 2, + planeH: 600, + pxPerDegH: 6400 / 360, + pxPerDegV: 171.73831979090915, + horizonRow: 357.01990847502145, +}; + +/** The share of the viewport height the plane's height is at least scaled to. Authored, tunable by eye. */ +export const RIDGE_BAND_FRAC = 0.6; +/** The widest field of view a viewport may show: a 16:9 viewport with 1.1 widths of plane (72 / 1.1 degrees), as export.py HFOV_MAX_DEG. */ +export const HFOV_MAX_DEG = 72 / 1.1; +/** + * Where the horizon sits down the viewport, as a fraction of its height: one constant for every sky state and every viewport (ruling + * ridge-frame-more-sky-fixed-pitch: the camera pitch never changes between day and night). The plane extends below the viewport bottom and + * the near plain is cropped. 0.85 (operator, 2026-11-20) shows about 31 degrees of sky above the horizon in a 16:9 cell. Authored, tunable by eye. + */ +export const HORIZON_AT = 0.85; +/** + * The rows a plane of `planeH` rows must keep under its horizon row so that at the smallest scale a viewport takes (the plane's height is at least `RIDGE_BAND_FRAC` + * of the viewport) it still reaches the viewport bottom: (1 - HORIZON_AT) planeH / RIDGE_BAND_FRAC, 150 of 600 rows. The baker refuses a bake with fewer + * (export.py GROUND_ROWS_MIN) and `parseManifest` refuses one that slipped through, so `offsetRange` need not handle a plane that stops short. + */ +export const groundRowsNeeded = (planeH: number): number => ((1 - HORIZON_AT) * planeH) / RIDGE_BAND_FRAC; + +export interface Window { + camera: Camera; + /** The planes in viewport pixels: the scale of a plane pixel, the plane's height, and `bottom`, the distance of its foot above the viewport's bottom edge (negative: the plane runs on below it). The horizon row lands at `HORIZON_AT`. */ + plane: { scale: number; h: number; bottom: number }; +} + +export function windowFor(view: View, viewportW: number, viewportH: number): Window { + const scale = Math.max( + (RIDGE_BAND_FRAC * viewportH) / view.planeH, + viewportW / (HFOV_MAX_DEG * view.pxPerDegH) + ); + const hfovDeg = viewportW / (scale * view.pxPerDegH); + return { + camera: { + azimuthDeg: view.lookAzDeg, + hfovDeg, + vfovDeg: (hfovDeg * viewportH) / viewportW, + horizonAt: HORIZON_AT, + }, + plane: { + scale, + h: scale * view.planeH, + bottom: (1 - HORIZON_AT) * viewportH - scale * (view.planeH - view.horizonRow), + }, + }; +} + +/** Nearest card's nearest tile distance, metres: where the camera first meets a card. */ +const nearestM = (manifest: RidgeManifest): number => + Math.min(...manifest.tiles.map((row) => row[0]?.distanceM ?? Infinity)); + +/** Whether the camera stands on its heading (phi 0, a whole turn off it included): a mode where the offset turns with the view puts it there. */ +const onHeading = (mode: RotationMode, phiDeg: number): boolean => + mode !== 'offset' && Math.abs(norm(phiDeg + 180) - 180) < 1e-6; + +/** + * The offsets the camera may take on its circle, metres, forward positive: the one clamp (ruling ridge-offset-range-fit, "the slider stops where the linear + * map holds"). How well a card's linear slide fits depends on the camera's angle `phiDeg` on its circle, so the bound depends on where the mode keeps it. With + * the camera on its heading (modes 'still' and 'both', `phi` 0) a forward offset goes to the bake's `rMaxForwardM`, the largest every card fits at phi 0; + * everywhere else (the offset-only mode swings the camera round the whole circle, and a backward offset at phi 0 is the camera at phi 180) the bound is + * `rMaxM`, the worst over every phi. The nearest card, shrunk by R / (R + r) about the horizon, would lift its foot above the viewport bottom and show the + * sky under it past the point where `1 / keep - 1` of its distance is the offset: applied to every position the camera can reach at the offset's sign + * (backward always, forward too where the circle takes it round to phi 180). The manifest guarantees `keep <= 1` (`groundRowsNeeded`: the plane reaches the + * viewport bottom at rest), so the formula needs no case for a plane that stops short; at `keep` 1 it gives 0. + */ +export function offsetRange( + manifest: RidgeManifest, + win: Window, + mode: RotationMode, + phiDeg = 0 +): [number, number] { + const { rMaxM, rMaxForwardM } = manifest.camera; + const { planeH, horizonRow } = manifest.view; + const below = win.plane.scale * (planeH - horizonRow); + const keep = 1 + win.plane.bottom / below; // the smallest scale at which the foot stays under the viewport bottom + const foot = Math.max(0, nearestM(manifest) * (1 / keep - 1)); // the max only absorbs the rounding of a keep that is 1 to the last bit + const back = Math.min(rMaxM, foot); + return onHeading(mode, phiDeg) ? [-back, rMaxForwardM] : [-back, back]; +} + +/** The longest stretch of motion the rig issues at once, seconds: the loader holds the tiles it passes over, so it also bounds how far a turn may sweep. */ +export const SEGMENT_S = 30; +/** The fastest the view or the camera may turn, degrees per second, whatever the loader holds: a keyframe a second must not skip a whole tile (11.25 degrees at 32 tiles). */ +export const SPEED_CEILING_DEG_S = 12; + +/** + * The largest speed (degrees per second, either direction) the baked resident count sustains in `mode`: the loader holds the tiles of the arc a card shows + * over the next SEGMENT_S seconds and two tiles beyond it each side, and the bake's gate (`ring.ts` `runTiles`, `export.py`) priced N of them. Turning the view + * widens that arc by speed x SEGMENT_S, so in 'both' the speed is what N leaves after the widest card arc (the viewport over the smallest slide rate, at the + * backward offset `rMaxM`) and the margin tiles. The offset-only mode sweeps the camera over a circle the gate already counts whatever the speed, and a still + * view has none: those take the ceiling, as does a ring the gate priced whole. + */ +export function maxSpeed(manifest: RidgeManifest, mode: RotationMode): number { + if (mode !== 'both') return SPEED_CEILING_DEG_S; + const { view, camera } = manifest; + const tileDeg = 360 / view.tiles; + const rmin = nearestM(manifest); + const n = runTiles(view, HFOV_MAX_DEG, camera.rMaxForwardM, rmin); + if (n >= view.tiles) return SPEED_CEILING_DEG_S; // the gate counted the whole ring: nothing the loader holds can exceed it + const sMin = rmin / (rmin + camera.rMaxM); + const room = (n - 1 - 2 * KEEP_MARGIN_TILES) * tileDeg - HFOV_MAX_DEG / sMin; + return Math.min(SPEED_CEILING_DEG_S, Math.max(0, room / SEGMENT_S)); +} + +/** What a card does on screen: its scale about the horizon and how far it is shifted sideways, viewport px, at a heading and camera angle. */ +export interface CardPose { + scale: number; + shiftPx: number; +} + +const RAD = Math.PI / 180; +const FIT_SAMPLES = 9; + +/** + * Where a card goes on a viewport: the camera stands on its circle of radius `offsetM` (signed, forward positive) at angle `phiDeg` against the heading + * `headingDeg`; a card at distance R (`ring.ts` `distanceAt` at the heading) seen from there is at angle `atan2(R sin b - r sin phi, R cos b - r cos phi)` + * from the heading for a point `b` degrees off it. A card is one flat sheet (ruling ridge-cards-per-card-slide), so that curve is fitted by the line + * `a + s b` over the viewport's arc, and the card is scaled by `s` about the horizon and shifted so the column at azimuth `az` lands at `a + s (az - heading)`. + * `shiftPx` is the translate of a container whose tiles sit at `(az - rest) x px per degree`, rest being the View's rest azimuth. + */ +export function cardPose( + manifest: RidgeManifest, + card: number, + headingDeg: number, + phiDeg: number, + offsetM: number, + win: Window +): CardPose { + const R = distanceAt(manifest, card, headingDeg); + const half = win.camera.hfovDeg / 2; + const phi = phiDeg * RAD; + let sb = 0; + let sa = 0; + let sbb = 0; + let sba = 0; + for (let i = 0; i < FIT_SAMPLES; i += 1) { + const b = (-half + (2 * half * i) / (FIT_SAMPLES - 1)) * RAD; + const a = Math.atan2(R * Math.sin(b) - offsetM * Math.sin(phi), R * Math.cos(b) - offsetM * Math.cos(phi)) / RAD; + const bd = b / RAD; + sb += bd; + sa += a; + sbb += bd * bd; + sba += bd * a; + } + const n = FIT_SAMPLES; + const s = (n * sba - sb * sa) / (n * sbb - sb * sb); + const a0 = (sa - s * sb) / n; + const { view } = manifest; + return { + scale: s, + shiftPx: win.plane.scale * view.pxPerDegH * (a0 - s * (headingDeg - view.lookAzDeg)), + }; +} + +/** + * The compass azimuths, unwrapped, of the card columns a pose puts on a viewport `viewportW` px wide: a column at `az` lands at `shiftPx + scale x (az - rest) + * x px per degree` from the centre. This is the arc the loader must hold for that card. + */ +export function cardArc( + view: View, + win: Window, + viewportW: number, + pose: CardPose +): { fromDeg: number; toDeg: number } { + const per = pose.scale * win.plane.scale * view.pxPerDegH; + return { + fromDeg: view.lookAzDeg + (-viewportW / 2 - pose.shiftPx) / per, + toDeg: view.lookAzDeg + (viewportW / 2 - pose.shiftPx) / per, + }; +} + +/** How often the pose is sampled to find the arc a stretch of motion passes over, seconds: finer than the rig's keyframe a second, so no swing between two keyframes is missed. */ +const SWEEP_STEP_S = 0.25; + +/** + * The arc of azimuth any of `cards` cards shows at any instant of the `seconds` after `t0` (ms), by `poseAt(card, ms)`: the union of `cardArc` over the whole + * stretch, not its ends. A pose is not monotone in time (offset-only rotation carries the nearest card out and back as the camera circles), so a card's reach + * peaks mid-stretch, and the tiles it needs there are the ones to mount and to ask the loader for. + */ +export function sweepArc( + view: View, + win: Window, + viewportW: number, + cards: number, + poseAt: (card: number, ms: number) => CardPose, + t0: number, + seconds: number = SEGMENT_S +): { fromDeg: number; toDeg: number } { + let fromDeg = Infinity; + let toDeg = -Infinity; + const steps = Math.ceil(seconds / SWEEP_STEP_S); + for (let n = 0; n <= steps; n += 1) { + const t = t0 + Math.min(seconds, n * SWEEP_STEP_S) * 1000; + for (let i = 0; i < cards; i += 1) { + const a = cardArc(view, win, viewportW, poseAt(i, t)); + fromDeg = Math.min(fromDeg, a.fromDeg); + toDeg = Math.max(toDeg, a.toDeg); + } + } + return { fromDeg, toDeg }; +} diff --git a/src/app/features/scene/ridge/weatherFeed.test.ts b/src/app/features/scene/ridge/weatherFeed.test.ts index 0f490cad..81eefb44 100644 --- a/src/app/features/scene/ridge/weatherFeed.test.ts +++ b/src/app/features/scene/ridge/weatherFeed.test.ts @@ -1,5 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { viennaSun } from './vienna'; +import { sunAt } from './sunAt'; +import { FALLBACK_VIEW } from './view'; +import { ELSEWHERE_VIEW } from './manifest.fixture'; import { CLEAR_SKY, currentWeather, @@ -7,7 +9,9 @@ import { parseWeatherFile, OBSERVATION_STALE_MS, STALE_MS, - WEATHER_ATTRIBUTION, + WEATHER_FEEDS, + creditLine, + feedFor, weatherFromFile, clearSkyGhi, cloudEstimate, @@ -15,6 +19,8 @@ import { WeatherFile, } from './weatherFeed'; +const VIENNA = WEATHER_FEEDS.vienna; + const file = (over: Partial = {}): WeatherFile => ({ fetched_at: '2026-11-11T10:45:00Z', observed_at: '2026-11-11T10:40:00Z', @@ -23,18 +29,12 @@ const file = (over: Partial = {}): WeatherFile => ({ humidity_pct: 60, glow_wm2: null, sunshine_s_10min: null, - attribution: WEATHER_ATTRIBUTION, + attribution: creditLine(VIENNA), ...over, }); const NOW = new Date('2026-11-11T10:50:00Z'); describe('weather from the file', () => { - it('credits GeoSphere as its legal page asks, and claims no licence', () => { - expect(WEATHER_ATTRIBUTION).toBe( - 'Datenquelle: GeoSphere Austria - https://data.hub.geosphere.at' - ); - expect(WEATHER_ATTRIBUTION).not.toMatch(/CC/); - }); it('rain is 0.8..1, by rate', () => { expect(weatherFromFile(file({ precip_mm_10min: 0.1 }), 20)).toBeCloseTo(0.813, 2); expect(weatherFromFile(file({ precip_mm_10min: 3 }), -20)).toBe(1); @@ -85,8 +85,8 @@ describe('weather from the file', () => { expect(weatherFromFile(file({ glow_wm2: 0, humidity_pct: 100 }), -20)).toBe(0.75); }); it('the 2026-11-10 midday fixture, GLOW 56-89 W/m2 under an overcast sky, is full cloud; the clear midday of 2026-10-15, 546-569, is none', () => { - const nov = viennaSun(new Date('2026-11-10T10:40:00Z')).elevation; - const oct = viennaSun(new Date('2026-10-15T10:50:00Z')).elevation; + const nov = sunAt(FALLBACK_VIEW.place, new Date('2026-11-10T10:40:00Z')).elevation; + const oct = sunAt(FALLBACK_VIEW.place, new Date('2026-10-15T10:50:00Z')).elevation; for (const g of [56, 72, 89]) expect(cloudFromGlow(g, nov)).toBeGreaterThan(0.95); for (const g of [546, 569]) expect(cloudFromGlow(g, oct)).toBe(0); expect(weatherFromFile(file({ glow_wm2: 72, sunshine_s_10min: 0 }), nov)).toBeGreaterThan(0.65); @@ -120,17 +120,18 @@ describe('weather from the file', () => { describe('the weather now', () => { it('uses the file while it is fresh', () => { - expect(currentWeather(file({ glow_wm2: 0, humidity_pct: 95 }), NOW)).toBeCloseTo(0.7, 2); + expect(currentWeather(file({ glow_wm2: 0, humidity_pct: 95 }), FALLBACK_VIEW.place, NOW)).toBeCloseTo(0.7, 2); }); it('falls back to a clear sky when the file was fetched more than 30 minutes ago', () => { const f = file({ humidity_pct: 100, fetched_at: '2026-11-11T10:19:00Z' }); expect(NOW.getTime() - Date.parse(f.fetched_at)).toBeGreaterThan(STALE_MS); - expect(currentWeather(f, NOW)).toBe(CLEAR_SKY); + expect(currentWeather(f, FALLBACK_VIEW.place, NOW)).toBe(CLEAR_SKY); }); it('the 30 minute mark itself is still fresh', () => { expect( currentWeather( file({ glow_wm2: 0, humidity_pct: 100, fetched_at: '2026-11-11T10:20:00Z' }), + FALLBACK_VIEW.place, NOW ) ).toBe(0.75); @@ -138,19 +139,34 @@ describe('the weather now', () => { it('falls back to a clear sky when the observation is more than 40 minutes old, though the file is fresh', () => { const f = file({ precip_mm_10min: 2, observed_at: '2026-11-11T10:09:00Z' }); expect(NOW.getTime() - Date.parse(f.observed_at)).toBeGreaterThan(OBSERVATION_STALE_MS); - expect(currentWeather(f, NOW)).toBe(CLEAR_SKY); + expect(currentWeather(f, FALLBACK_VIEW.place, NOW)).toBe(CLEAR_SKY); expect( - currentWeather(file({ precip_mm_10min: 2, observed_at: '2026-11-11T10:11:00Z' }), NOW) + currentWeather(file({ precip_mm_10min: 2, observed_at: '2026-11-11T10:11:00Z' }), FALLBACK_VIEW.place, NOW) ).toBeGreaterThan(0.8); }); it('falls back to a clear sky with no file, and with a fetch time from the future', () => { - expect(currentWeather(null, NOW)).toBe(CLEAR_SKY); + expect(currentWeather(null, FALLBACK_VIEW.place, NOW)).toBe(CLEAR_SKY); expect( - currentWeather(file({ precip_mm_10min: 2, fetched_at: '2026-11-12T10:40:00Z' }), NOW) + currentWeather(file({ precip_mm_10min: 2, fetched_at: '2026-11-12T10:40:00Z' }), FALLBACK_VIEW.place, NOW) ).toBe(CLEAR_SKY); }); }); +describe('the sun the weather is read against is the place it is given', () => { + it("sets radiation against the sun over that place: by day in Vienna it reads cloud, at the other side of the world, in the night, it reads the humidity", () => { + const f = file({ glow_wm2: 100, sunshine_s_10min: null, humidity_pct: 60 }); + const sunEl = (place: typeof FALLBACK_VIEW.place) => + sunAt(place, new Date(Date.parse(f.observed_at) - 5 * 60_000)).elevation; + expect(sunEl(FALLBACK_VIEW.place)).toBeGreaterThan(20); + expect(sunEl(ELSEWHERE_VIEW.place)).toBeLessThan(0); + const vienna = currentWeather(f, FALLBACK_VIEW.place, NOW); + const elsewhere = currentWeather(f, ELSEWHERE_VIEW.place, NOW); + expect(vienna).toBe(weatherFromFile(f, sunEl(FALLBACK_VIEW.place))); + expect(elsewhere).toBe(weatherFromFile(f, sunEl(ELSEWHERE_VIEW.place))); + expect(vienna).not.toBe(elsewhere); + }); +}); + describe('bad instrument values', () => { it('a negative sunshine is no reading, not full cloud', () => { expect(cloudEstimate(file({ glow_wm2: null, sunshine_s_10min: -5 }), 21)).toBeNull(); @@ -164,7 +180,7 @@ describe('bad instrument values', () => { sunshine_s_10min: null, humidity_pct: 50, }); - const at = (m: number) => currentWeather(f, new Date(Date.parse(f.observed_at) + m * 60_000)); + const at = (m: number) => currentWeather(f, FALLBACK_VIEW.place, new Date(Date.parse(f.observed_at) + m * 60_000)); expect(at(0)).toBe(at(29)); }); }); @@ -174,7 +190,7 @@ describe('reading weather.json', () => { const night = JSON.parse( '{"fetched_at":"2026-11-11T22:48:22Z","observed_at":"2026-11-11T22:40:00Z","station":11035,"precip_mm_10min":0.1,"humidity_pct":100.0,"sunshine_s_10min":0.0,"glow_wm2":0.0,"attribution":"Datenquelle: GeoSphere Austria - https://data.hub.geosphere.at"}' ); - expect(parseWeatherFile(night)).toMatchObject({ + expect(parseWeatherFile(night, VIENNA)).toMatchObject({ precip_mm_10min: 0.1, humidity_pct: 100, glow_wm2: 0, @@ -186,47 +202,50 @@ describe('reading weather.json', () => { humidity_pct: null, sunshine_s_10min: null, glow_wm2: null, - }); + }, VIENNA); expect(gap).toMatchObject({ precip_mm_10min: null, humidity_pct: null, sunshine_s_10min: null, glow_wm2: null, }); - expect(currentWeather(gap, new Date('2026-11-11T22:50:00Z'))).toBe(CLEAR_SKY); + expect(currentWeather(gap, FALLBACK_VIEW.place, new Date('2026-11-11T22:50:00Z'))).toBe(CLEAR_SKY); }); - it("is not another station's file", () => { - expect(parseWeatherFile({ ...file(), station: 11036 })).toBeNull(); + it("is not another station's file: the check is the place's feed's station", () => { + expect(parseWeatherFile({ ...file(), station: 11036 }, VIENNA)).toBeNull(); + const other = { ...VIENNA, station: 11036 }; + expect(parseWeatherFile({ ...file(), station: 11036 }, other)).toMatchObject({ station: 11036 }); + expect(parseWeatherFile(file(), other)).toBeNull(); }); it('parses the agreed shape, keeping nulls and the sunshine it never reads', () => { const raw = { ...file(), precip_mm_10min: null, glow_wm2: 12, sunshine_s_10min: 0 }; - expect(parseWeatherFile(raw)).toEqual(raw); + expect(parseWeatherFile(raw, VIENNA)).toEqual(raw); }); it('rejects a body without usable times, and anything not an object', () => { - expect(parseWeatherFile({ ...file(), observed_at: 'yesterday' })).toBeNull(); - expect(parseWeatherFile({ ...file(), fetched_at: undefined })).toBeNull(); - expect(parseWeatherFile(null)).toBeNull(); - expect(parseWeatherFile('x')).toBeNull(); + expect(parseWeatherFile({ ...file(), observed_at: 'yesterday' }, VIENNA)).toBeNull(); + expect(parseWeatherFile({ ...file(), fetched_at: undefined }, VIENNA)).toBeNull(); + expect(parseWeatherFile(null, VIENNA)).toBeNull(); + expect(parseWeatherFile('x', VIENNA)).toBeNull(); }); it("rejects a time with no zone: it would be read in the client's local time", () => { - expect(parseWeatherFile({ ...file(), observed_at: '2026-11-10T10:40:00' })).toBeNull(); + expect(parseWeatherFile({ ...file(), observed_at: '2026-11-10T10:40:00' }, VIENNA)).toBeNull(); expect( - parseWeatherFile({ ...file(), observed_at: '2026-11-10T11:40:00+01:00' }) + parseWeatherFile({ ...file(), observed_at: '2026-11-10T11:40:00+01:00' }, VIENNA) ).not.toBeNull(); }); it('is no observation when the file is missing, fails, or is not JSON', async () => { expect( - await fetchWeatherFile('/weather.json', (async () => ({ + await fetchWeatherFile('/weather.json', VIENNA, (async () => ({ ok: false, })) as unknown as typeof fetch) ).toBeNull(); expect( - await fetchWeatherFile('/weather.json', (async () => { + await fetchWeatherFile('/weather.json', VIENNA, (async () => { throw new Error('offline'); }) as unknown as typeof fetch) ).toBeNull(); expect( - await fetchWeatherFile('/weather.json', (async () => ({ + await fetchWeatherFile('/weather.json', VIENNA, (async () => ({ ok: true, json: async () => { throw new Error('bad'); @@ -236,6 +255,21 @@ describe('reading weather.json', () => { }); it('reads a good file', async () => { const f = (async () => ({ ok: true, json: async () => file() })) as unknown as typeof fetch; - expect(await fetchWeatherFile('/weather.json', f)).toEqual(file()); + expect(await fetchWeatherFile('/weather.json', VIENNA, f)).toEqual(file()); + }); +}); + +describe('the feed table', () => { + it('serves Vienna and names no other place', () => { + expect(Object.keys(WEATHER_FEEDS)).toEqual(['vienna']); + expect(feedFor('vienna')).toBe(VIENNA); + ['fuji', 'matterhorn', 'amadablam', 'grandcanyon', '', 'constructor', 'toString'].forEach((id) => + expect(feedFor(id)).toBeUndefined() + ); + }); + it("credits GeoSphere with its requested line, and states a licence only with the dataset named", () => { + expect(creditLine(VIENNA)).toBe(`Datenquelle: GeoSphere Austria - ${VIENNA.url}`); + expect(creditLine(VIENNA)).not.toMatch(/CC BY/); + expect(VIENNA.dataset).toMatch(/TAWES.*10-minute.*CC BY 4\.0/); }); }); diff --git a/src/app/features/scene/ridge/weatherFeed.ts b/src/app/features/scene/ridge/weatherFeed.ts index b2b4a7b0..b6ba9d0d 100644 --- a/src/app/features/scene/ridge/weatherFeed.ts +++ b/src/app/features/scene/ridge/weatherFeed.ts @@ -1,21 +1,46 @@ // The weather over the viewpoint as one `weather.ts` number, read from a static `weather.json` next to the page (config.json's // neighbour). The browser never calls a weather service: Eureka's refresher (gamecult-ops, docs/weather-feed.md; the only writer) -// writes the file from GeoSphere Austria's TAWES 10-minute observations (station 11035, Wien Hohe -// Warte). Rain is the gauge. CLOUD IS AN ESTIMATE: TAWES has no cloud cover. By day it is the measured global radiation (GLOW) against +// writes the file from GeoSphere Austria's TAWES 10-minute observations (the Wien Hohe Warte station, WEATHER_FEEDS below). Rain is the gauge. CLOUD IS AN ESTIMATE: TAWES has no cloud cover. By day it is the measured global radiation (GLOW) against // what a clear sky gives at the sun's position now (`clearSkyGhi`, Haurwitz), cross-checked by the sunshine duration (`SO`, seconds of // 600 the direct beam was strong enough to burn the card); with the sun low or down it is a ramp of the humidity. A file that is -// missing, unreadable, malformed or stale (below) is no observation, and no observation is a clear sky. -import { WEATHER_CREDIT } from './credits'; -import { viennaSun } from './vienna'; +// missing, unreadable, malformed or stale (below) is no observation, and no observation is a clear sky. A place with no row in WEATHER_FEEDS has no +// observation source at all: it is drawn clear and the file is not read for it. +import { sunAt } from './sunAt'; +import type { Place } from './view'; /** Reader rule of docs/weather-feed.md: the file is stale 30 minutes after it was fetched or 40 after the observation it holds (the station reports every 10). */ export const STALE_MS = 30 * 60_000; export const OBSERVATION_STALE_MS = 40 * 60_000; -export const STATION = 11035; const SKEW_MS = 5 * 60_000; export const CLEAR_SKY = 0; -/** The credit GeoSphere's legal page asks for. */ -export const WEATHER_ATTRIBUTION = WEATHER_CREDIT; + +/** What a place's observation source owes: the station its rows are read from, the credit GeoSphere's legal page asks for (`credit`, then `url`: it names no licence, the dataset's below does) and the dataset with its licence as the dataset page names it. */ +export interface WeatherFeed { + station: number; + credit: string; + url: string; + dataset: string; +} + +/** + * The places that have a weather source, by place id. A new place gets weather by adding its row here and a source in the refresher (gamecult-ops + * `docs/weather-feed.md`); no other edit. Every place without a row is drawn with a clear sky (`skyForState.ts` `loadWeather`). + */ +export const WEATHER_FEEDS: Readonly> = { + vienna: { + station: 11035, + credit: 'Datenquelle: GeoSphere Austria', + url: 'https://data.hub.geosphere.at', + dataset: 'TAWES weather stations, 10-minute data (station 11035), CC BY 4.0', + }, +}; + +/** The feed that serves a place, or undefined for a place with none. */ +export const feedFor = (placeId: string): WeatherFeed | undefined => + Object.prototype.hasOwnProperty.call(WEATHER_FEEDS, placeId) ? WEATHER_FEEDS[placeId] : undefined; + +/** The credit as one line: the source and where it is. */ +export const creditLine = (f: WeatherFeed): string => `${f.credit} - ${f.url}`; /** The file's shape; every measurement is null when the station did not report it. Times are ISO 8601. */ export interface WeatherFile { @@ -37,21 +62,21 @@ const num = (v: unknown): number | null => (typeof v === 'number' && Number.isFi const isZonedTime = (v: unknown): v is string => typeof v === 'string' && /(Z|[+-]\d\d:?\d\d)$/.test(v) && !Number.isNaN(Date.parse(v)); -/** A `WeatherFile` from parsed JSON, or null when it does not have the shape (times missing or unparseable). */ -export function parseWeatherFile(json: unknown): WeatherFile | null { +/** A `WeatherFile` from parsed JSON, or null when it does not have the shape (times missing or unparseable) or is not the feed's station's. */ +export function parseWeatherFile(json: unknown, feed: WeatherFeed): WeatherFile | null { const j = json as Record | null; if (!j || typeof j !== 'object') return null; if (!isZonedTime(j.observed_at) || !isZonedTime(j.fetched_at)) return null; - if (j.station !== STATION) return null; + if (j.station !== feed.station) return null; return { fetched_at: j.fetched_at, observed_at: j.observed_at, - station: STATION, + station: feed.station, precip_mm_10min: num(j.precip_mm_10min), humidity_pct: num(j.humidity_pct), glow_wm2: num(j.glow_wm2), sunshine_s_10min: num(j.sunshine_s_10min), - attribution: typeof j.attribution === 'string' ? j.attribution : WEATHER_ATTRIBUTION, + attribution: typeof j.attribution === 'string' ? j.attribution : creditLine(feed), }; } @@ -104,8 +129,8 @@ export function weatherFromFile(f: WeatherFile, sunEl: number): number { return Math.max(0.7 * cloud, mist); } -/** The weather number now: the file's, or a clear sky when there is none or it is stale (see STALE_MS) or from the future. */ -export function currentWeather(f: WeatherFile | null, now: Date = new Date()): number { +/** The weather number now, its sun taken at `place` (the View's): the file's, or a clear sky when there is none or it is stale (see STALE_MS) or from the future. */ +export function currentWeather(f: WeatherFile | null, place: Place, now: Date = new Date()): number { if (!f) return CLEAR_SKY; const fetched = now.getTime() - Date.parse(f.fetched_at); const observed = now.getTime() - Date.parse(f.observed_at); @@ -119,17 +144,18 @@ export function currentWeather(f: WeatherFile | null, now: Date = new Date()): n ) return CLEAR_SKY; // GLOW and SO are means of the ten minutes ending at observed_at: the sun of their midpoint is the one to set them against. - return weatherFromFile(f, viennaSun(new Date(Date.parse(f.observed_at) - 5 * 60_000)).elevation); + return weatherFromFile(f, sunAt(place, new Date(Date.parse(f.observed_at) - 5 * 60_000)).elevation); } -/** Fetch and parse `weather.json`; null on any failure. */ +/** Fetch and parse `weather.json` as the feed's station's; null on any failure. */ export async function fetchWeatherFile( url: string, + feed: WeatherFeed, fetcher: typeof fetch = fetch ): Promise { try { const res = await fetcher(url, { cache: 'no-store' }); - return res.ok ? parseWeatherFile(await res.json()) : null; + return res.ok ? parseWeatherFile(await res.json(), feed) : null; } catch { return null; } diff --git a/src/app/features/scene/sceneDrawn.test.ts b/src/app/features/scene/sceneDrawn.test.ts new file mode 100644 index 00000000..9e555cad --- /dev/null +++ b/src/app/features/scene/sceneDrawn.test.ts @@ -0,0 +1,54 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { + SCENE_ACTIVE_ATTRIBUTE, + getDrawnSky, + getSceneDrawn, + setSceneDrawn, + subscribeSceneDrawn, +} from './sceneDrawn'; + +const attrs = new Set(); +vi.stubGlobal('document', { + documentElement: { + setAttribute: (n: string) => attrs.add(n), + removeAttribute: (n: string) => attrs.delete(n), + }, +}); + +afterEach(() => setSceneDrawn(false)); + +describe('sceneDrawn: one store owns the flag and html[data-scene]', () => { + it('starts off, and on/off move the flag, the attribute and the subscribers together', () => { + const cb = vi.fn(); + const off = subscribeSceneDrawn(cb); + expect(getSceneDrawn()).toBe(false); + setSceneDrawn(true); + expect(getSceneDrawn()).toBe(true); + expect(attrs.has(SCENE_ACTIVE_ATTRIBUTE)).toBe(true); + setSceneDrawn(true); + expect(cb).toHaveBeenCalledTimes(1); + setSceneDrawn(false); + expect(getSceneDrawn()).toBe(false); + expect(attrs.has(SCENE_ACTIVE_ATTRIBUTE)).toBe(false); + expect(cb).toHaveBeenCalledTimes(2); + off(); + setSceneDrawn(true); + expect(cb).toHaveBeenCalledTimes(2); + }); + + it('owns the sky the scene that is up draws: set with the scene, told to subscribers when it changes, gone with the scene', () => { + const cb = vi.fn(); + const off = subscribeSceneDrawn(cb); + expect(getDrawnSky()).toBeUndefined(); + setSceneDrawn(true, 'day'); + expect(getDrawnSky()).toBe('day'); + setSceneDrawn(true, 'day'); + expect(cb).toHaveBeenCalledTimes(1); + setSceneDrawn(true, 'night'); // a rebuilt scene replaced the one shown + expect(getDrawnSky()).toBe('night'); + expect(cb).toHaveBeenCalledTimes(2); + setSceneDrawn(false, 'night'); // no scene draws no sky + expect(getDrawnSky()).toBeUndefined(); + off(); + }); +}); diff --git a/src/app/features/scene/sceneDrawn.ts b/src/app/features/scene/sceneDrawn.ts new file mode 100644 index 00000000..b1a98875 --- /dev/null +++ b/src/app/features/scene/sceneDrawn.ts @@ -0,0 +1,37 @@ +// Whether a background scene is drawing a sky right now, and which sky (day, dusk or night) the scene that is up draws. BackgroundScene is the only +// writer: it sets this when a scene is up (told the band of the scene it shows, so a rebuild still loading changes nothing here until it replaces it), +// and clears it when the scene stops, fails to start, or loses its WebGL context (a restored context sets it again). The page theme and ink follow +// this sky, never the band the clock or the choice announces (ruling ink-follows-drawn-sky). This store also owns html[data-scene], so the attribute +// the CSS reads and the flag the theme hooks read cannot disagree. The configured tier only says a scene may run; this says one does. +import type { FixedSkyState } from './ridge/skyMoment'; + +/** Set on while a scene is drawn, so signed-out screens can let it show through. */ +export const SCENE_ACTIVE_ATTRIBUTE = 'data-scene'; + +let drawn = false; +let drawnSky: FixedSkyState | undefined; +const listeners = new Set<() => void>(); + +export const getSceneDrawn = (): boolean => drawn; + +/** The sky the scene that is up draws; undefined with no scene, or a scene whose sky is not known. */ +export const getDrawnSky = (): FixedSkyState | undefined => drawnSky; + +export const subscribeSceneDrawn = (cb: () => void): (() => void) => { + listeners.add(cb); + return () => { + listeners.delete(cb); + }; +}; + +export function setSceneDrawn(on: boolean, sky?: FixedSkyState): void { + if (typeof document !== 'undefined') { + if (on) document.documentElement.setAttribute(SCENE_ACTIVE_ATTRIBUTE, ''); + else document.documentElement.removeAttribute(SCENE_ACTIVE_ATTRIBUTE); + } + const next = on ? sky : undefined; + if (on === drawn && next === drawnSky) return; + drawn = on; + drawnSky = next; + [...listeners].forEach((cb) => cb()); +} diff --git a/src/app/features/scene/sceneShell.css.ts b/src/app/features/scene/sceneShell.css.ts index 18911a1b..2d2ef01d 100644 --- a/src/app/features/scene/sceneShell.css.ts +++ b/src/app/features/scene/sceneShell.css.ts @@ -1,4 +1,4 @@ -import { createVar, fallbackVar, globalStyle } from '@vanilla-extract/css'; +import { createVar, fallbackVar, globalStyle, style } from '@vanilla-extract/css'; import { color } from 'folds'; // While the background scene runs (html[data-scene], set by BackgroundScene) the signed-in shell @@ -28,3 +28,13 @@ globalStyle(':root[data-scene] #root', { const surfaceInkVar = createVar(); globalStyle(':root[data-scene] body', { vars: { [surfaceInkVar]: color.Surface.Container } }); export const surfaceInk = fallbackVar(surfaceInkVar, color.Surface.Container); + +// While the scene view is open (sceneView.ts) the app stays mounted, so the chat keeps its scroll and its composer, but it is hidden (and inert, set by sceneView.ts). +globalStyle(':root[data-scene-view] #root', { visibility: 'hidden' }); + +// Return while the scene view's code is still loading (SceneViewHost.tsx): the view's own rail is not there yet, so this one button stands where its Return will be. +export const LoadingReturn = style({ + position: 'fixed', + top: 'max(0.5rem, env(safe-area-inset-top))', + left: 'max(0.5rem, env(safe-area-inset-left))', +}); diff --git a/src/app/features/scene/sceneStyle.ts b/src/app/features/scene/sceneStyle.ts deleted file mode 100644 index 7c31233e..00000000 --- a/src/app/features/scene/sceneStyle.ts +++ /dev/null @@ -1,28 +0,0 @@ -// Temporary: which background the viewer picked (terrain or ridges), kept in one localStorage key so the two scenes we -// serve can be compared on any device. Absent, the client config's backgroundScene.style decides. -import type { SceneStyle } from './tier'; - -export type ServedSceneStyle = Extract; -export const SERVED_SCENE_STYLES: readonly ServedSceneStyle[] = ['terrain', 'ridge']; -export const SCENE_STYLE_KEY = 'ratatoskr.sceneStyle'; - -export function getSceneStyleOverride(): ServedSceneStyle | undefined { - try { - const v = localStorage.getItem(SCENE_STYLE_KEY); - return SERVED_SCENE_STYLES.includes(v as ServedSceneStyle) - ? (v as ServedSceneStyle) - : undefined; - } catch { - return undefined; - } -} - -/** Store the pick and reload, so the scene host mounts the other scene from a clean page. */ -export function setSceneStyle(s: ServedSceneStyle): void { - try { - localStorage.setItem(SCENE_STYLE_KEY, s); - } catch { - return; - } - window.location.reload(); -} diff --git a/src/app/features/scene/sceneView.test.ts b/src/app/features/scene/sceneView.test.ts new file mode 100644 index 00000000..798c9aa5 --- /dev/null +++ b/src/app/features/scene/sceneView.test.ts @@ -0,0 +1,193 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { getCamera, holdCamera, isHeld, resetCamera } from './cameraState'; +import { + SCENE_VIEW_ATTRIBUTE, + SCENE_VIEW_HISTORY_MARK, + closeSceneView, + getSceneView, + loadSceneView, + loadSceneViewOrClose, + restoreEntryFocus, + openSceneView, + setSubmenu, + subscribeSceneView, +} from './sceneView'; + +// No DOM here: the few things the module touches (, #root, the focused element, the history stack and the window's popstate) are stand-ins. +class Entry { + focused = 0; + focus() { + this.focused += 1; + } +} +const entryEl = new Entry(); +let attrs: Set; +let rootAttrs: Set; +let stack: Array | null>; +let pops: Set<() => void>; +let back: number; + +beforeEach(() => { + attrs = new Set(); + rootAttrs = new Set(); + stack = [{ idx: 0 }]; + pops = new Set(); + back = 0; + entryEl.focused = 0; + vi.stubGlobal('HTMLElement', Entry); + vi.stubGlobal('document', { + activeElement: entryEl, + documentElement: { + setAttribute: (k: string) => attrs.add(k), + removeAttribute: (k: string) => attrs.delete(k), + }, + getElementById: (id: string) => + id === 'root' + ? { + setAttribute: (k: string) => rootAttrs.add(k), + removeAttribute: (k: string) => rootAttrs.delete(k), + } + : null, + }); + const history = { + get state() { + return stack[stack.length - 1]; + }, + pushState: (s: Record) => stack.push(s), + back: () => { + back += 1; + stack.pop(); + [...pops].forEach((cb) => cb()); + }, + }; + vi.stubGlobal('window', { + history, + addEventListener: (t: string, cb: () => void) => t === 'popstate' && pops.add(cb), + removeEventListener: (t: string, cb: () => void) => t === 'popstate' && pops.delete(cb), + }); + vi.stubGlobal('localStorage', { + getItem: () => null, + setItem: () => undefined, + removeItem: () => undefined, + }); + resetCamera(); +}); + +afterEach(() => { + closeSceneView(); + vi.unstubAllGlobals(); +}); + +describe('the scene view', () => { + it('opens with one history entry that keeps what the router keeps, the app inert and the page marked', () => { + openSceneView(); + openSceneView(); + expect(getSceneView()).toEqual({ open: true, submenu: undefined }); + expect(stack).toHaveLength(2); + expect(stack[1]).toEqual({ idx: 0, [SCENE_VIEW_HISTORY_MARK]: true }); + expect(rootAttrs.has('inert')).toBe(true); + expect(attrs.has(SCENE_VIEW_ATTRIBUTE)).toBe(true); + }); + + it('the Return icon closes it, takes its entry off the stack, frees the app and owes the focus to the entry', () => { + openSceneView(); + closeSceneView(); + expect(getSceneView().open).toBe(false); + expect(stack).toHaveLength(1); + expect(back).toBe(1); + expect(rootAttrs.size).toBe(0); + expect(attrs.size).toBe(0); + closeSceneView(); + expect(back).toBe(1); + }); + + it("the browser's Back button closes it (the entry is already gone), once", () => { + openSceneView(); + const seen = vi.fn(); + subscribeSceneView(seen); + window.history.back(); + expect(getSceneView().open).toBe(false); + expect(stack).toHaveLength(1); + expect(back).toBe(1); // that one was the browser's; the close did not go back again + expect(seen).toHaveBeenCalledTimes(1); + expect(rootAttrs.size).toBe(0); + }); + + it('shows one submenu at a time, and choosing the one shown closes its panel', () => { + setSubmenu('view'); + expect(getSceneView().submenu).toBeUndefined(); // closed: nothing to show + openSceneView(); + setSubmenu('view'); + expect(getSceneView().submenu).toBe('view'); + setSubmenu('time'); + expect(getSceneView().submenu).toBe('time'); + setSubmenu('time'); + expect(getSceneView().submenu).toBeUndefined(); + setSubmenu('sky'); + closeSceneView(); + openSceneView(); + expect(getSceneView().submenu).toBeUndefined(); + }); + + it('Return resumes a rotation a manual turn held, through the camera store', () => { + openSceneView(); + holdCamera(0); + expect(isHeld()).toBe(true); + const mode = getCamera().mode; + closeSceneView(); + expect(isHeld()).toBe(false); + expect(getCamera().mode).toBe(mode); + }); +}); + +describe('the view code failing to load', () => { + it('closes an open view: the app is live again, nothing stays hidden, and the next open can ask again', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined); + openSceneView(); + const got = await loadSceneViewOrClose(() => Promise.reject(new Error('chunk'))); + expect(got).toBeUndefined(); + expect(getSceneView().open).toBe(false); + expect(rootAttrs.size).toBe(0); + expect(attrs.size).toBe(0); + openSceneView(); + expect(getSceneView().open).toBe(true); + }); + + it('a load that succeeds leaves the view open and hands back the module', async () => { + openSceneView(); + const mod = { default: () => null } as unknown as Awaited>; + expect(await loadSceneViewOrClose(() => Promise.resolve(mod))).toBe(mod); + expect(getSceneView().open).toBe(true); + }); +}); + +describe('the focus after a close', () => { + const closes: Array<[string, () => void]> = [ + ['Return', () => closeSceneView()], + ['Escape (the view calls closeSceneView)', () => closeSceneView()], + ['Back', () => window.history.back()], + ]; + it.each(closes)( + '%s: the close does not touch the focus (the trap is still mounted); restoreEntryFocus gives it to the entry, once', + (_name, close) => { + openSceneView(); + close(); + expect(getSceneView().open).toBe(false); + expect(entryEl.focused).toBe(0); + restoreEntryFocus(); + expect(entryEl.focused).toBe(1); + restoreEntryFocus(); + expect(entryEl.focused).toBe(1); + } + ); + + it('nothing is owed while the view is open, and a reopen forgets an unclaimed focus', () => { + openSceneView(); + restoreEntryFocus(); + expect(entryEl.focused).toBe(0); + closeSceneView(); + openSceneView(); + restoreEntryFocus(); + expect(entryEl.focused).toBe(0); + }); +}); diff --git a/src/app/features/scene/sceneView.ts b/src/app/features/scene/sceneView.ts new file mode 100644 index 00000000..00027d7e --- /dev/null +++ b/src/app/features/scene/sceneView.ts @@ -0,0 +1,129 @@ +// The scene view: whether the fullscreen view of the scene is open, and which submenu it shows. The one owner of both (ruling ridge-scene-view-fullscreen). Opening +// pushes one history entry, so the browser's Back button, Escape and the Return icon are all the same act, closing; while it is open the app (#root) is inert and +// hidden but stays mounted, so the chat keeps its scroll and its composer. Closing is Return: the rotation a manual turn held resumes through `cameraState` +// (ruling ridge-view-turn-handback). The view's controls write the stores that own what they set (cameraState.ts, skyState.ts) and hold no copy of them. +// Main-chunk safe (no React, no ridge code), as skyState.ts and cameraState.ts are. +import { getCamera, setCamera } from './cameraState'; + +export type Submenu = 'view' | 'time' | 'sky' | 'place'; + +export interface SceneViewState { + open: boolean; + /** The submenu whose panel is up, if any: one at a time. */ + submenu: Submenu | undefined; +} + +/** Set on while the view is open: the shell is hidden and the view is the only thing over the scene. */ +export const SCENE_VIEW_ATTRIBUTE = 'data-scene-view'; +/** The mark the view's history entry carries beside whatever the router keeps in `history.state`. */ +export const SCENE_VIEW_HISTORY_MARK = 'ratatoskrSceneView'; + +let state: SceneViewState = { open: false, submenu: undefined }; +const listeners = new Set<() => void>(); +/** The control that opened the view. */ +let entry: HTMLElement | null = null; +/** The control that is owed the focus: set by a close, taken by `restoreEntryFocus` once the view's focus trap is gone. */ +let owed: HTMLElement | null = null; +/** Whether this view pushed a history entry that is still on top of the stack. */ +let pushed = false; + +export const getSceneView = (): SceneViewState => state; + +export const subscribeSceneView = (cb: () => void): (() => void) => { + listeners.add(cb); + return () => { + listeners.delete(cb); + }; +}; + +const set = (next: SceneViewState): void => { + state = next; + [...listeners].forEach((cb) => cb()); +}; + +const root = (): HTMLElement | null => document.getElementById('root'); + +/** Browser Back (or Forward over the entry) while the view is open: it is Return, and the entry is already gone. */ +const onPopState = (): void => { + pushed = false; + finish(); +}; + +/** Open the view: one history entry, the app inert and hidden behind it. A second call while open changes nothing. */ +export function openSceneView(): void { + if (state.open) return; + entry = document.activeElement instanceof HTMLElement ? document.activeElement : null; + owed = null; + try { + window.history.pushState( + { ...(window.history.state ?? {}), [SCENE_VIEW_HISTORY_MARK]: true }, + '' + ); + pushed = true; + } catch { + pushed = false; // no history to push to: Return and Escape still close it + } + window.addEventListener('popstate', onPopState); + document.documentElement.setAttribute(SCENE_VIEW_ATTRIBUTE, ''); + root()?.setAttribute('inert', ''); + set({ open: true, submenu: undefined }); +} + +/** Everything closing does, whichever way it came: the app live again, the rotation a manual turn held resumed, the focus owed back to the entry (`restoreEntryFocus`). */ +function finish(): void { + if (!state.open) return; + window.removeEventListener('popstate', onPopState); + document.documentElement.removeAttribute(SCENE_VIEW_ATTRIBUTE); + root()?.removeAttribute('inert'); + // Picking the mode already chosen ends a hold (cameraState.ts): the scene behind the chat turns again from where the viewer left it. + setCamera({ mode: getCamera().mode }); + owed = entry; + entry = null; + set({ open: false, submenu: undefined }); +} + +/** + * Give the focus back to the control that opened the view. The one owner of that focus, called by the host once the view has unmounted: while the view's focus + * trap is still mounted it pulls focus back to Return, and its unmount then drops it to the body. Nothing is owed while the view is open or once it has been + * restored, so a call at any other time changes nothing. + */ +export function restoreEntryFocus(): void { + const to = owed; + owed = null; + to?.focus?.(); +} + +/** Return: close the view, and take its history entry off the stack when it is still the top one. */ +export function closeSceneView(): void { + if (!state.open) return; + const wasPushed = pushed; + finish(); // takes the popstate listener off first, so the back below does not close twice + if (wasPushed && window.history.state?.[SCENE_VIEW_HISTORY_MARK]) window.history.back(); + pushed = false; +} + +/** Show a submenu's panel, or none; choosing the one already shown closes its panel. */ +export function setSubmenu(submenu: Submenu | undefined): void { + if (!state.open) return; + set({ open: true, submenu: submenu === state.submenu ? undefined : submenu }); +} + +/** The view's code, a chunk of its own: asked for when the entry is hovered or focused, and by the host when the view opens. */ +export const loadSceneView = () => import('./view/SceneView'); + +/** + * The view's code for the host: a failed load closes the view (the app live again, the focus back on the entry), so nothing stays hidden behind a view that + * will not come. The next open asks for the chunk again. Resolves to the module, or undefined when the load failed. + */ +export async function loadSceneViewOrClose( + load: typeof loadSceneView = loadSceneView +): Promise> | undefined> { + try { + return await load(); + } catch (e) { + // eslint-disable-next-line no-console + console.warn('Scene view unavailable:', e); + closeSceneView(); + return undefined; + } +} diff --git a/src/app/features/scene/skyBand.test.ts b/src/app/features/scene/skyBand.test.ts deleted file mode 100644 index e38f676a..00000000 --- a/src/app/features/scene/skyBand.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { displayedLuminance, hexToLinear, luma, shapeToBand, SKY_BAND } from './skyBand'; -import type { Linear } from './skyBand'; -import { GRID_FRAG, SHAPE_SKY_GLSL, SKY_FRAG } from './terrain/terrainShaders'; - -const near = (a: number, b: number) => Math.abs(a - b) < 1e-9; - -describe('shapeToBand', () => { - const dark: Linear = [0.02, 0.05, 0.2]; // a deep blue - const { day } = SKY_BAND; - - it('lifts a sky below the floor onto the floor, mixing toward the tint so the hue is kept', () => { - const c = shapeToBand(dark, day); - expect(near(luma(c), day.floor)).toBe(true); - // Between the sky and the tint on every channel: a mix, not a grey clamp. - [0, 1, 2].forEach((i) => { - expect(c[i]).toBeGreaterThanOrEqual(Math.min(dark[i], day.lift[i])); - expect(c[i]).toBeLessThanOrEqual(Math.max(dark[i], day.lift[i])); - }); - expect(c[2]).toBeGreaterThan(c[0]); // still blue - }); - - it('lifts black to the tint scaled in, not to grey', () => { - const c = shapeToBand([0, 0, 0], SKY_BAND.dusk); - expect(near(luma(c), SKY_BAND.dusk.floor)).toBe(true); - expect(c[2]).toBeGreaterThan(c[0]); // the dusk tint is Day's pale blue - }); - - it('leaves a sky already in the band as it is, and is continuous at the floor', () => { - const ok: Linear = [0.5, 0.6, 0.7]; - expect(shapeToBand(ok, day)).toEqual(ok); - const lo = shapeToBand([0.31, 0.31, 0.31], day); - const below = shapeToBand([0.3099, 0.3099, 0.3099], day); - expect(Math.abs(lo[0] - below[0])).toBeLessThan(1e-3); - }); - - it('scales a sky above the ceiling down to it, keeping its hue', () => { - const c = shapeToBand([0.9, 0.8, 1], SKY_BAND.night); - expect(near(luma(c), SKY_BAND.night.ceiling)).toBe(true); - expect(near(c[0] / c[2], 0.9)).toBe(true); - }); - - it('clamps to 0..1 as the screen does, and never leaves the band when shaped twice', () => { - expect(shapeToBand([4, 4, 4], day)).toEqual([1, 1, 1]); - const once = shapeToBand(dark, day); - shapeToBand(once, day).forEach((v, i) => expect(v).toBeCloseTo(once[i], 12)); - }); -}); - -describe('the bands', () => { - it('have a tint above the floor to lift toward', () => { - Object.values(SKY_BAND).forEach((b) => expect(luma(b.lift)).toBeGreaterThan(b.floor)); - }); - - it('keep the floor above the 0.2983 text bound by what gamma 2.2, 8-bit rounding and dither can take', () => { - const grey = shapeToBand([0, 0, 0], SKY_BAND.day); - const shown = displayedLuminance(grey, 'low'); - expect(shown).toBeGreaterThanOrEqual(0.2983); - expect(shown).toBeLessThan(SKY_BAND.day.floor); - }); - - it('decode hex as linear light', () => { - expect(hexToLinear('#ffffff')).toEqual([1, 1, 1]); - }); -}); - -describe('the GLSL twin', () => { - it('shapes with the same arithmetic: clamp, luma weights, mix to the floor, scale to the ceiling', () => { - expect(SHAPE_SKY_GLSL).toContain('c = clamp(c, 0.0, 1.0);'); - expect(SHAPE_SKY_GLSL).toContain('const vec3 LUMA = vec3(0.2126, 0.7152, 0.0722);'); - expect(SHAPE_SKY_GLSL).toContain( - 'if (l < uBand.x) return mix(c, uLift, (uBand.x - l) / (dot(uLift, LUMA) - l));' - ); - expect(SHAPE_SKY_GLSL).toContain('if (l > uBand.y) return c * (uBand.y / l);'); - }); - - it('is applied to the sky colour in both shaders that draw it, the sky pass and the haze that fades into it', () => { - [SKY_FRAG, GRID_FRAG].forEach((src) => { - expect(src).toContain(SHAPE_SKY_GLSL); - expect(src).toMatch(/return shapeSky\(1\.0 - exp\(-45\.0 \* skyScatter\(d\)\)/); - }); - }); -}); diff --git a/src/app/features/scene/skyBand.ts b/src/app/features/scene/skyBand.ts deleted file mode 100644 index a74784b3..00000000 --- a/src/app/features/scene/skyBand.ts +++ /dev/null @@ -1,90 +0,0 @@ -// The luminance band each fixed sky state's drawn sky is shaped into, so the state's theme ink -// clears 4.5:1 on bare sky (WCAG relative luminance, the `luminance` of src/sky/skyTokens.js). -// -// day Noonday Sky's dark text ink #342d25 (L 0.0274) needs a backdrop of at least 0.2983. -// The floor is that text bound (0.30 as drawn); there is no ceiling, dark ink on light is fine. -// dusk The same ink, and its link #2a4f27 (L 0.0623), which needs a backdrop of at least 0.4554. The floor is -// the link bound (0.4744 as drawn), so text clears 4.5:1 with room (6.6) and the link clears too. -// night Midnight Sky's light text ink #aeccff (L 0.594) needs a backdrop of at most 0.0931. -// The baked night sky (0.058 to 0.077) is kept; the ceiling is the bound. -// -// Night's link ink is not part of the band: see skyTheme.ts. -// -// The terrain sky is a physical scatter function, so it is shaped downstream, on its final colour: -// `shapeToBand` here, and its GLSL twin (`SHAPE_SKY_GLSL`) in terrain/terrainShaders.ts, built from the -// same constants. The ridge sky is a three-stop gradient whose stops are chosen inside the band -// (ridge/skyColour.ts, skyForState.ts), and its test sweeps the blends. -export type FixedSkyState = 'day' | 'dusk' | 'night'; -export type Linear = readonly [number, number, number]; - -/** WCAG luma weights, applied to linear RGB. */ -export const LUMA: Linear = [0.2126, 0.7152, 0.0722]; -export const luma = (c: Linear): number => LUMA[0] * c[0] + LUMA[1] * c[1] + LUMA[2] * c[2]; - -/** sRGB hex `#rrggbb` to linear RGB 0..1. */ -export function hexToLinear(hex: string): Linear { - const ch = (at: number) => { - const s = parseInt(hex.slice(at, at + 2), 16) / 255; - return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4; - }; - return [ch(1), ch(3), ch(5)]; -} - -/** How a displayed colour is read: as encoded, or moved one 8-bit step down or up in every channel ('low', 'high'). */ -export type Reading = 'exact' | 'low' | 'high'; - -/** - * Relative luminance of what the terrain shaders put on screen for a linear colour: they encode with - * pow(1/2.2), not the sRGB curve, so the screen colour is read back through the sRGB curve. 'low' and 'high' move every - * encoded channel one 8-bit step down or up first: rounding to 8 bits (half a step) plus the sky pass's dither (half a - * step) cannot move a channel further, so they bound what the screen shows. A smooth bound, so a search can climb it. - */ -export function displayedLuminance(c: Linear, reading: Reading = 'exact'): number { - const shift = { exact: 0, low: -1 / 255, high: 1 / 255 }[reading]; - const ch = (v: number) => { - const e = Math.min(1, Math.max(0, Math.min(1, Math.max(0, v)) ** (1 / 2.2) + shift)); - return e <= 0.04045 ? e / 12.92 : ((e + 0.055) / 1.055) ** 2.4; - }; - return luma([ch(c[0]), ch(c[1]), ch(c[2])]); -} - -export interface SkyBand { - /** Linear luma the shaped colour is at least (0: no floor). */ - floor: number; - /** Linear luma the shaped colour is at most (1: no ceiling). */ - ceiling: number; - /** The colour a too-dark sky is mixed toward: the state's own tint, so the hue survives the lift. Its luma is above `floor`. */ - lift: Linear; -} - -/** - * The shaping targets, in linear luma. Day's floor sits 0.019 above the text bound (0.2983), Dusk's 0.019 above the link - * bound (0.4554), which skyForState.test.ts derives from the ink and ties to these: the screen encoding is - * gamma 2.2, which reads about 0.006 darker through the sRGB curve at this level, and 8-bit rounding with the sky - * pass's dither at its worst (one step in every channel) takes about 0.007 more. The night ceiling is lower than the text bound - * (0.0931) by more than that: 0.077394 is the luma at which one step up reads 0.08164, the lightest the baked night sky shows - * (skyState.ts), so a sky the page URL steers at night, scaled down to the ceiling, cannot show lighter than the baked one. - */ -export const SKY_BAND: Record = { - day: { floor: 0.317, ceiling: 1, lift: hexToLinear('#e2f4ff') }, - // Dusk lifts toward Day's pale blue rather than a rose: mixing a third of the sky toward rose washed the twilight pink, and - // a rose lighter than the floor shifts hues by 47 to 72 degrees where Day's tint shifts them by 18 (measured, PR body). - dusk: { floor: 0.4744, ceiling: 1, lift: hexToLinear('#e2f4ff') }, - night: { floor: 0, ceiling: 0.077394, lift: hexToLinear('#5a6a9a') }, -}; - -/** - * Shape a linear sky colour into the band. Below the floor it mixes toward `lift` by exactly the amount - * that lands on the floor (continuous at the floor, hue kept); above the ceiling it scales down to the - * ceiling. The colour is clamped to 0..1 first, as the screen does. - */ -export function shapeToBand(c: Linear, band: SkyBand): Linear { - const k = [0, 1, 2].map((i) => Math.min(1, Math.max(0, c[i]))) as unknown as Linear; - const l = luma(k); - if (l < band.floor) { - const t = (band.floor - l) / (luma(band.lift) - l); - return [0, 1, 2].map((i) => k[i] + (band.lift[i] - k[i]) * t) as unknown as Linear; - } - if (l > band.ceiling) return [0, 1, 2].map((i) => (k[i] * band.ceiling) / l) as unknown as Linear; - return k; -} diff --git a/src/app/features/scene/skyForState.test.ts b/src/app/features/scene/skyForState.test.ts index a04ac173..835bb302 100644 --- a/src/app/features/scene/skyForState.test.ts +++ b/src/app/features/scene/skyForState.test.ts @@ -1,373 +1,211 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { atStandardTime } from './standardTime.testkit'; -import { baked } from '../../../sky/baked'; -import { AA, luminance } from '../../../sky/skyTokens.js'; -import { skyColours } from './ridge/skyColour'; -import { chooseSky, skyColour } from './terrain/terrainSky'; -import { - DUSK_SUN_ELEVATION, - TERRAIN_REACH_DEG, - ridgeDrawn, - ridgeSkyFor, - ridgeSkyKey, - terrainDrawn, - terrainSkyFor, -} from './skyForState'; -import { displayedLuminance, luma, shapeToBand, SKY_BAND } from './skyBand'; -import type { FixedSkyState } from './skyBand'; -import { DAY_FROM, setSkyClock, skyBackdrop } from './skyState'; -import { view } from './terrain/terrainWorld'; -import { skyThemeId } from './skyTheme'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { FALLBACK_VIEW } from './ridge/view'; +import { ELSEWHERE_VIEW } from './ridge/manifest.fixture'; +import { atSolarTime } from './ridge/skyTestkit'; +import { CLEAR_SKY, ridgeDrawn, ridgeSkyFor, ridgeSkyKey, loadWeather } from './skyForState'; +import { setSkyClock } from './skyState'; +import { DAY_FROM } from './ridge/skyMoment'; +import type { SkyChoice } from './ridge/skyMoment'; +import { BUDGET } from './ridge/toneMap'; +import { ridgeWeather, setFedWeather } from './ridge/weather'; -const hex = (c: readonly number[]) => `#${c.map((v) => v.toString(16).padStart(2, '0')).join('')}`; -const EPS = 1e-9; -const STATES = ['day', 'dusk', 'night'] as const; -const SKY = { 'midnight-sky': baked.midnight, 'noonday-sky': baked.noonday } as const; - -/** - * The band each state needs, from the ink itself: dark ink needs a backdrop of at least - * AA * (L + 0.05) - 0.05, light ink at most (L + 0.05) / AA - 0.05. Day 0.2983, night 0.0931; dusk is bound by its - * link (0.4554), the darker ink to clear, whose floor also holds the text. - */ -const needs = (state: FixedSkyState) => { - const sky = SKY[skyThemeId(state)]; - const l = luminance(sky.tokens.Background.OnContainer); - const link = luminance(sky.link); - return state === 'night' - ? { floor: 0, ceiling: (l + 0.05) / AA - 0.05 } - : { floor: AA * ((state === 'dusk' ? link : l) + 0.05) - 0.05, ceiling: 1 }; -}; - -let search = ''; -beforeEach(() => { - search = ''; - vi.stubGlobal('window', { - get location() { - return { search }; - }, - }); +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(() => { setSkyClock(); + setFedWeather(undefined); vi.unstubAllGlobals(); }); -describe('the bands the text ink needs', () => { - it('are the numbers the shaping was set from', () => { - expect(needs('day').floor).toBeCloseTo(0.2983, 3); - expect(needs('dusk').floor).toBeCloseTo(0.4554, 3); - expect(needs('night').ceiling).toBeCloseTo(0.0931, 3); - }); - - // The drawn floor and the lift are tied to those bounds, not to themselves: nudge either constant and this fails. - it('give Dusk a floor 0.019 above the link bound (as Day has above the text bound) and a lift Day shares', () => { - expect(SKY_BAND.dusk.floor).toBeCloseTo(needs('dusk').floor + 0.019, 4); - expect(SKY_BAND.day.floor).toBeCloseTo(needs('day').floor + 0.019, 3); - expect(SKY_BAND.dusk.lift).toEqual(SKY_BAND.day.lift); - expect(luma(SKY_BAND.dusk.lift)).toBeGreaterThan(SKY_BAND.dusk.floor); - }); - - it.each(['day', 'dusk'] as const)( - '%s: the darkest the shaping can show reads at the bound and under the floor', - (state) => { - const shown = displayedLuminance(shapeToBand([0, 0, 0], SKY_BAND[state]), 'low'); - expect(shown).toBeGreaterThanOrEqual(needs(state).floor); - expect(shown).toBeLessThan(SKY_BAND[state].floor); - } - ); -}); - describe('ridgeSkyFor', () => { - it('carries the state band, which the layers are shaped into, and the physical sky of that state', () => { - for (const state of STATES) { - const sky = ridgeSkyFor(state, 0.3); - expect(sky.band).toEqual(SKY_BAND[state]); - expect(sky.physical?.state).toBe(state); - expect(sky.physical?.stops).toEqual({ top: sky.top, mid: sky.mid, horizon: sky.horizon }); - } + it.each(BANDS)('carries the physical sky of the %s moment', (band, choice) => { + const sky = ridgeSkyFor(choice, FALLBACK_VIEW, 0.3); + expect(sky.physical?.state).toBe(band); + expect(sky.physical?.stops).toEqual({ top: sky.top, mid: sky.mid, horizon: sky.horizon }); }); - it('draws the sky auto resolves to, never nothing', () => { - const key = (s: ReturnType) => [ - s.top, - s.mid, - s.horizon, - s.band, - s.physical?.sun, - ]; - setSkyClock(() => atStandardTime(12, 0)); - expect(key(ridgeSkyFor('auto', 0.3))).toEqual(key(ridgeSkyFor('day', 0.3))); - setSkyClock(() => atStandardTime(0, 0)); - expect(key(ridgeSkyFor('auto', 0.3))).toEqual(key(ridgeSkyFor('night', 0.3))); - setSkyClock(() => atStandardTime(18, 10)); - expect(key(ridgeSkyFor('auto', 0.3))).toEqual(key(ridgeSkyFor('dusk', 0.3))); + it('Auto draws the real sun now, never nothing', () => { + const key = (s: ReturnType) => [s.top, s.mid, s.horizon, s.physical?.sun.time]; + const noon = atSolarTime(12, 0); + expect(key(ridgeSkyFor(auto, FALLBACK_VIEW, 0.3, noon))[3]).toEqual(noon); + expect(ridgeSkyFor(auto, FALLBACK_VIEW, 0.3, noon).physical?.state).toBe('day'); + 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'); }); - it("is lit from the real sun over Vienna: a forced state's sun is inside the state, the clear noon sky is blue", () => { - const day = ridgeSkyFor('day', 0); + 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(named('noon'), FALLBACK_VIEW, 0); expect(day.physical?.sun.elevation).toBeGreaterThanOrEqual(DAY_FROM); expect(day.top[2]).toBeGreaterThan(day.top[0]); - const dusk = ridgeSkyFor('dusk', 0); - expect(Math.abs(dusk.physical?.sun.elevation ?? 99)).toBeLessThanOrEqual(DAY_FROM); - expect(ridgeSkyFor('night', 0).physical?.sun.elevation).toBeLessThanOrEqual(-DAY_FROM); - expect(day.ground).toEqual(skyColours().ground); + expect(Math.abs(ridgeSkyFor(named('dusk'), FALLBACK_VIEW, 0).physical?.sun.elevation ?? 99)).toBeLessThanOrEqual(DAY_FROM); + expect(ridgeSkyFor(named('night'), FALLBACK_VIEW, 0).physical?.sun.elevation).toBeLessThanOrEqual(-DAY_FROM); }); - it('keys a rebuild by state and weather, not by the moving sun', () => { - setSkyClock(() => atStandardTime(12, 0)); - expect(ridgeSkyKey('auto', 0.3)).toBe(ridgeSkyKey('day', 0.3)); - expect(ridgeSkyKey('day', 0.3)).not.toBe(ridgeSkyKey('day', 0.8)); - expect(ridgeSkyKey('day', 0.3)).not.toBe(ridgeSkyKey('night', 0.3)); + 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.each(STATES)('%s: the display is fitted to the budget its text ink needs', (state) => { - const { floor, ceiling } = needs(state); - const r = ridgeDrawn(state); - expect(r.darkest).toBeGreaterThanOrEqual(floor); - expect(r.lightest).toBeLessThanOrEqual(ceiling); - const fit = ridgeSkyFor(state, 0.3).physical?.fit; + it("is made over the View's place: the sun and the observer are the View's", () => { + const sky = ridgeSkyFor(named('noon'), ELSEWHERE_VIEW, 0); + expect(sky.physical?.view).toBe(ELSEWHERE_VIEW); + expect(sky.physical?.atm.observerKm).toBe(ELSEWHERE_VIEW.place.altitudeKm); + }); + + // Each band's ceiling is its budget's (night's is a tunable, NIGHT_CEILING: the operator tunes it by eye). + it.each(BANDS)('%s: the display is the curve of its budget: black lift at the floor, and its ceiling', (band, choice) => { + const r = ridgeDrawn(band); + expect(r.darkest).toBe(BUDGET[band].floor); + expect(r.lightest).toBeLessThanOrEqual(BUDGET[band].ceiling); + const fit = ridgeSkyFor(choice, FALLBACK_VIEW, 0.3).physical?.fit; expect(fit?.lo).toBeGreaterThanOrEqual(r.darkest - 1e-9); expect(fit?.hi).toBeLessThanOrEqual(r.lightest + 1e-9); }); }); -// Not the generator's grid: a golden-angle spiral over the upper sphere (no shared rows or columns) -// plus a 0.05 degree grid across the sun, five times finer than the generator's. -const dirAt = (el: number, az: number): [number, number, number] => { - const rad = Math.PI / 180; - return [ - Math.cos(el * rad) * Math.sin(az * rad), - Math.sin(el * rad), - -Math.cos(el * rad) * Math.cos(az * rad), - ]; -}; -/** Over the sweep: the darkest the 8-bit screen can show (dither at its worst), the lightest, and the darkest as encoded. */ -const sweepOf = (sky: ReturnType, N = 4000, maxEl = TERRAIN_REACH_DEG) => { - const rad = Math.PI / 180; - const out = { low: Infinity, high: -Infinity, exactMin: Infinity }; - const see = (el: number, az: number) => { - const c = skyColour(sky, dirAt(el, az)); - out.low = Math.min(out.low, displayedLuminance(c, 'low')); - out.high = Math.max(out.high, displayedLuminance(c, 'high')); - out.exactMin = Math.min(out.exactMin, displayedLuminance(c)); - }; - for (let i = 0; i < N; i += 1) { - const y = ((i + 0.5) / N) * Math.sin(maxEl * rad); // sin(elevation): uniform from the horizon to maxEl - see(Math.asin(y) / rad, (i * 137.50776405) % 360); - } - for (let dEl = -3; dEl <= 3; dEl += 0.05) { - for (let dAz = -3; dAz <= 3; dAz += 0.05) { - see(Math.min(maxEl, Math.max(0, sky.elevation + dEl)), sky.azimuth + dAz); - } - } - return out; -}; +describe('ridgeSkyKey', () => { + const noonNow = atSolarTime(12, 0); -describe('the terrain camera reach', () => { - it('covers the highest ray the frozen camera sees, at any aspect, with a small margin', () => { - const tanHalf = Math.tan((55 * Math.PI) / 360); - const tops = [0.4, 0.5, 1, 16 / 9, 2.4].flatMap((aspect) => - [0, 0.125, 0.25, 0.5, 0.75].flatMap((turns) => { - const v = view(aspect, turns); - return [-1, 0, 1].map((nx) => { - const d = [0, 1, 2].map( - (i) => v.forward[i] + nx * tanHalf * aspect * v.right[i] + tanHalf * v.up[i] - ); - return (Math.asin(d[1] / Math.hypot(d[0], d[1], d[2])) * 180) / Math.PI; - }); - }) + 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 ); - const top = Math.max(...tops); - expect(top).toBeCloseTo(14.5, 1); - expect(TERRAIN_REACH_DEG).toBeGreaterThanOrEqual(top); - expect(TERRAIN_REACH_DEG - top).toBeLessThan(2); - }); -}); - -describe('terrainSkyFor', () => { - it('draws the sky auto resolves to, with that state band', () => { - setSkyClock(() => atStandardTime(12, 0)); - expect(terrainSkyFor('auto')).toEqual(terrainSkyFor('day')); - setSkyClock(() => atStandardTime(0, 0)); - expect(terrainSkyFor('auto')).toEqual(terrainSkyFor('night')); - }); - - it('lets the page URL steer auto, shaped into the band of the state the clock resolves to', () => { - setSkyClock(() => atStandardTime(0, 0)); // night - search = '?sun=30&az=120'; - expect(terrainSkyFor('auto')).toEqual({ - sun: { elevation: 30, azimuth: 120 }, - band: SKY_BAND.night, - }); - search = '?sky=noonday'; - expect(terrainSkyFor('auto')).toEqual({ sky: 'noonday', band: SKY_BAND.night }); - search = '?sky=garbage'; - expect(terrainSkyFor('auto')).toEqual(terrainSkyFor('night')); - setSkyClock(() => atStandardTime(18, 10)); // dusk, URL azimuth honoured - search = '?sun=2&az=250'; - expect(terrainSkyFor('auto').sun).toEqual({ elevation: 2, azimuth: 250 }); - }); - - it('keeps a URL-chosen sun inside the band of the resolved state', () => { - setSkyClock(() => atStandardTime(12, 0)); // day: floor - search = '?sun=-30'; - const day = sweepOf(chooseSky(terrainSkyFor('auto'))); - expect(day.low).toBeGreaterThanOrEqual(needs('day').floor); - setSkyClock(() => atStandardTime(0, 0)); // night: ceiling - search = '?sun=60'; - const night = sweepOf(chooseSky(terrainSkyFor('auto'))); - expect(night.high).toBeLessThanOrEqual(needs('night').ceiling); - }); - - it('keeps a URL-steered sky at night no lighter than the Night backdrop the text was checked against', () => { - setSkyClock(() => atStandardTime(0, 0)); - ['?sun=60', '?sun=10&az=40', '?sun=2&az=250', '?sky=noonday'].forEach((q) => { - search = q; - expect(terrainDrawn('auto').lightest).toBeLessThanOrEqual(skyBackdrop('night').lightest); - }); - }); - - it('lets an explicit state beat the URL, as before auto had one', () => { - search = '?sun=30&az=120&sky=midnight'; - expect(terrainSkyFor('day')).toEqual({ sky: 'noonday', band: SKY_BAND.day }); - expect(terrainSkyFor('dusk').sun).toEqual({ elevation: DUSK_SUN_ELEVATION }); - }); - - it('names the baked sky for day and night, and a low sun for dusk, each with its band', () => { - expect(terrainSkyFor('day')).toEqual({ sky: 'noonday', band: SKY_BAND.day }); - expect(terrainSkyFor('night')).toEqual({ sky: 'midnight', band: SKY_BAND.night }); - expect(terrainSkyFor('dusk')).toEqual({ - sun: { elevation: DUSK_SUN_ELEVATION }, - band: SKY_BAND.dusk, - }); - }); -}); - -describe('the terrain sky lies in the band its text ink needs', () => { - const sweep = (state: FixedSkyState) => sweepOf(chooseSky(terrainSkyFor(state))); - - it('dusk needs its lift: the scatter sky alone dips below the text bound within the reach', () => { - const { sun } = terrainSkyFor('dusk'); - expect(sweepOf(chooseSky({ sun })).exactMin).toBeLessThan(needs('dusk').floor - 0.02); - expect(sweep('dusk').low).toBeGreaterThanOrEqual(needs('dusk').floor); - }); - - it.each(STATES)('%s', (state) => { - const { floor, ceiling } = needs(state); - const l = sweep(state); - expect(l.low).toBeGreaterThanOrEqual(floor); - expect(l.high).toBeLessThanOrEqual(ceiling); - }); - - it.each(STATES)('%s holds for a sun at any elevation, as ?sun= can put it', (state) => { - const { floor, ceiling } = needs(state); - for (let e = -90; e <= 90; e += 10) { - const l = sweepOf(chooseSky({ sun: { elevation: e }, band: SKY_BAND[state] }), 4000, 90); - expect(l.low).toBeGreaterThanOrEqual(floor); - expect(l.high).toBeLessThanOrEqual(ceiling); - } - }); - - it('and the terrain dusk still reaches the sun glow the ridge dusk does not', () => { - expect(skyBackdrop('dusk').lightest).toBeGreaterThan(0.9); - }); -}); - -describe('skyBackdrop holds the union of what the scenes draw', () => { - // An independent extremum of the screen reading ('low' for the darkest, 'high' for the lightest: one 8-bit step each way) over the terrain camera's reach: not terrainDrawn's grid and compass search but alternating golden-section - // line searches in elevation and azimuth from 60 starts (a golden-angle spiral and scatter about the sun), the bracket - // shrinking to 1e-3 degrees. A plateau (the shader clamps) cannot stall it: each line search always - // moves to the better end of its bracket. - const extremes = (state: FixedSkyState) => { - const sky = chooseSky(terrainSkyFor(state)); - const rad = Math.PI / 180; - const f = (el: number, az: number, reading: 'low' | 'high') => { - const e = Math.min(TERRAIN_REACH_DEG, Math.max(0, el)) * rad; - const a = az * rad; - return displayedLuminance( - skyColour(sky, [Math.cos(e) * Math.sin(a), Math.sin(e), -Math.cos(e) * Math.cos(a)]), - reading + 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 ); - }; - const P = 0.6180339887; - const line = (g: (x: number) => number, mid: number, w: number) => { - let a = mid - w; - let b = mid + w; - for (let k = 0; k < 40; k += 1) { - const c = b - P * (b - a); - const d = a + P * (b - a); - if (g(c) > g(d)) b = d; - else a = c; - } - return (a + b) / 2; - }; - const hunt = (sign: 1 | -1) => { - const reading = sign === 1 ? 'high' : 'low'; - let best = -Infinity; - for (let i = 0; i < 60; i += 1) { - let el = - i % 2 - ? sky.elevation + (((i * 7919) % 1600) - 800) / 100 - : Math.asin(((i + 0.5) / 60) * Math.sin(TERRAIN_REACH_DEG * rad)) / rad; - let az = - i % 2 ? sky.azimuth + (((i * 104729) % 1600) - 800) / 100 : (i * 137.50776405) % 360; - for (let w = 8; w > 1e-3; w /= 2) { - const [el0, az0] = [el, az]; - el = line((x) => sign * f(Math.max(0, x), az0, reading), el0, w); - const el1 = el; - az = line((x) => sign * f(el1, x, reading), az0, w); - best = Math.max(best, sign * f(el, az, reading)); - } - } - return sign * best; - }; - return { darkest: hunt(-1), lightest: hunt(1) }; - }; - - // At night a sky the page URL steers (?sun= ?sky=) is shaped to the band's ceiling, so the lightest it can show is one - // 8-bit step above the ceiling's own grey: the Night constant must cover it too, or text is checked against a sky - // lighter than the one it sits on. - const steeredNight = displayedLuminance( - [SKY_BAND.night.ceiling, SKY_BAND.night.ceiling, SKY_BAND.night.ceiling], - 'high' - ); - - const computed = (state: FixedSkyState) => { - const r = [ridgeDrawn(state), terrainDrawn(state)]; - const ind = extremes(state); - return { - darkest: Math.min(...r.map((x) => x.darkest), ind.darkest), - lightest: Math.max( - ...r.map((x) => x.lightest), - ind.lightest, - ...(state === 'night' ? [steeredNight] : []) - ), - }; - }; - - // The constants are the swept extremes rounded outward to six places, so each lies in [extreme, extreme + 1e-6): - // a constant 1e-6 low is under the extreme, one 2e-5 high is over the bound. SEARCH is the searches' own error. - const SEARCH = 1e-8; - it.each(STATES)( - '%s: the constant is the swept extreme rounded outward, within 1e-6 above it', - (state) => { - const c = computed(state); - const b = skyBackdrop(state); - expect(b.darkest).toBeLessThanOrEqual(c.darkest); - expect(b.lightest).toBeGreaterThanOrEqual(c.lightest); - expect(c.darkest - b.darkest).toBeLessThan(1e-6 + SEARCH); - expect(b.lightest - c.lightest).toBeLessThan(1e-6 + SEARCH); } - ); - - it.each(STATES)('%s: an independent sweep, no looser than 5e-4 from the constant', (state) => { - // The sweep is not the generator's grid (see above), so it cannot share its blind spots. - const l = sweepOf(chooseSky(terrainSkyFor(state)), 20000); - const b = skyBackdrop(state); - const r = ridgeDrawn(state); - expect(l.low).toBeGreaterThanOrEqual(b.darkest - EPS); - expect(l.high).toBeLessThanOrEqual(b.lightest + EPS); - expect(b.lightest - Math.max(l.high, r.lightest)).toBeLessThan(5e-4); - expect(Math.min(l.low, r.darkest) - b.darkest).toBeLessThan(5e-4); + }); +}); + +describe('loadWeather', () => { + const VIENNA = FALLBACK_VIEW.place; + const FUJI = { ...ELSEWHERE_VIEW.place, id: 'fuji' }; + const wx = (at: Date) => ({ + fetched_at: at.toISOString(), + observed_at: at.toISOString(), + station: 11035, + precip_mm_10min: 2, + humidity_pct: 99, + glow_wm2: null, + sunshine_s_10min: null, + attribution: 'x', + }); + const t = new Date('2030-01-01T10:00:00Z'); + + it('draws a place with no feed clear and does not fetch: the one file is for one station', async () => { + const fetched = vi.fn(async () => ({ ok: true, json: async () => wx(t) })); + vi.stubGlobal('fetch', fetched); + setFedWeather(0.9); + await loadWeather('/w.json', FUJI, t); + expect(fetched).toHaveBeenCalledTimes(0); + expect(ridgeWeather()).toBe(CLEAR_SKY); + }); + + it('draws Vienna with a fresh file, and reads the file again on coming back from a place without one', async () => { + const fetched = vi.fn(async () => ({ ok: true, json: async () => wx(t) })); + vi.stubGlobal('fetch', fetched); + await loadWeather('/w.json', VIENNA, t); + expect(fetched).toHaveBeenCalledTimes(1); + expect(ridgeWeather()).toBeGreaterThan(0.7); + await loadWeather('/w.json', VIENNA, new Date(t.getTime() + 60_000)); + expect(fetched).toHaveBeenCalledTimes(1); // inside the refresh window + await loadWeather('/w.json', FUJI, new Date(t.getTime() + 120_000)); + expect(fetched).toHaveBeenCalledTimes(1); + expect(ridgeWeather()).toBe(CLEAR_SKY); + await loadWeather('/w.json', VIENNA, new Date(t.getTime() + 180_000)); + expect(fetched).toHaveBeenCalledTimes(2); + expect(ridgeWeather()).toBeGreaterThan(0.7); + }); + + it("a fetch that resolves after the place has changed writes nothing: the place the viewer is on is drawn clear, not with the old place's rain", async () => { + let release = () => undefined as void; + vi.stubGlobal( + 'fetch', + vi.fn( + () => + new Promise((resolve) => { + release = () => resolve({ ok: true, json: async () => wx(later) }); + }) + ) + ); + const later = new Date(t.getTime() + 24 * 3_600_000); + setFedWeather(undefined); + const slow = loadWeather('/w.json', VIENNA, later); // Vienna's file is on the wire + await loadWeather('/w.json', FUJI, new Date(later.getTime() + 1_000)); // the viewer is on Fuji, which has no feed: clear + expect(ridgeWeather()).toBe(CLEAR_SKY); + release(); + await slow; + expect(ridgeWeather()).toBe(CLEAR_SKY); // Vienna's rain is not Fuji's + }); + + it("rejects a file whose station is not the place's feed's: a clear sky", async () => { + vi.stubGlobal('fetch', async () => ({ ok: true, json: async () => ({ ...wx(t), station: 99999 }) })); + await loadWeather('/w.json', VIENNA, t); + expect(ridgeWeather()).toBe(CLEAR_SKY); + }); +}); + +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 () => { + vi.stubGlobal('localStorage', { getItem: () => null, setItem: () => undefined, removeItem: () => undefined }); + vi.resetModules(); + const st = await import('./skyState'); + const f = await import('./skyForState'); + const now = atSolarTime(12, 0); + const off = f.ridgeSkyKey(named('night'), FALLBACK_VIEW, 0, now); + const dayOff = f.ridgeSkyKey(named('noon'), FALLBACK_VIEW, 0, now); + st.setConstellationLines(true); + expect(f.ridgeSkyKey(named('night'), FALLBACK_VIEW, 0, now)).toBe(`${off}:lines`); + expect(f.ridgeSkyKey(named('noon'), FALLBACK_VIEW, 0, now)).toBe(dayOff); }); }); diff --git a/src/app/features/scene/skyForState.ts b/src/app/features/scene/skyForState.ts index 8a5f9768..79110262 100644 --- a/src/app/features/scene/skyForState.ts +++ b/src/app/features/scene/skyForState.ts @@ -1,96 +1,79 @@ -// What each scene is told for a sky state. 'auto' is a choice, not a sky: both functions draw the sky it -// resolves to (`resolveSkyState`, the clock), so every scene paints one of day, dusk or night. Each is drawn -// inside that state's luminance band (skyBand.ts): the ridge sky from gradients whose stops and blends lie in -// it, the terrain sky shaped into it downstream of the scatter function. `skyBackdrop` bounds what comes out, -// and the login text was checked against that bound. -import { baked } from '../../../sky/baked'; -import { chooseSky, skyColour, urlSky } from './terrain/terrainSky'; -import type { SkyName } from './terrain/terrainSky'; -import type { SkyColours, Srgb } from './ridge/skyColour'; -import { skyColours } from './ridge/skyColour'; +// 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, +// 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). +import type { SkyColours } from './ridge/skyColour'; 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 { BUDGET } from './ridge/toneMap'; import { ridgeWeather, setFedWeather } from './ridge/weather'; -import { currentWeather, fetchWeatherFile } from './ridge/weatherFeed'; -import { resolveSkyState, skyNow } from './skyState'; -import type { SkyState } from './skyState'; -import { displayedLuminance, SKY_BAND } from './skyBand'; -import type { SkyBand } from './skyBand'; -import { luminance } from '../../../sky/skyTokens.js'; -import { CAMERA } from './terrain/terrainWorld'; +import { currentWeather, feedFor, fetchWeatherFile } from './ridge/weatherFeed'; +import { getConstellationLines, skyNow } from './skyState'; -/** Sun elevation in degrees for the terrain's dusk: just above the horizon, between the two bakes (as `?sun=` puts it). */ -export const DUSK_SUN_ELEVATION = 2; +/** 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 and the weather. The sun moves with the clock inside a state and - * is not part of the key (the scene is baked at its start), as the sky was one gradient per state before. + * 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. + * 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 = ( - state: SkyState, - weather: number = ridgeWeather(), + choice: SkyChoice, + view: View, + weather: number = weatherFor(choice), now: Date = skyNow() -): string => `ridge:${resolveSkyState(state, now)}:${weather}`; +): string => { + const band = skyBand(sunAt(view.place, momentFor(choice, view.place, now)).elevation); + return `ridge:${band}:${weather}:${view.place.id}:${momentKey(choice, view.place, now)}${band === 'night' && getConstellationLines() ? ':lines' : ''}`; +}; const WEATHER_REFRESH_MS = 10 * 60_000; let weatherAt = -Infinity; +let weatherPlace = ''; /** - * Read `weather.json` (the page's own, next to config.json) into the weather the ridge sky is drawn for; at most once in ten minutes. - * Never throws: a missing, stale or broken file is a clear sky (`currentWeather`). + * Read `weather.json` (the page's own, next to config.json) into the weather the ridge sky is drawn for; at most once in ten minutes. A file that arrives after + * the place moved on is not written. + * Never throws: a missing, stale or broken file is a clear sky (`currentWeather`). A place with no feed (`feedFor`) is a clear sky and the file is not + * fetched; the place is remembered all the same, so going back to a place with a feed reads the file at once. */ -export async function loadWeather(url: string, now: Date = skyNow()): Promise { - if (now.getTime() - weatherAt < WEATHER_REFRESH_MS) return; +export async function loadWeather(url: string, place: Place, now: Date = skyNow()): Promise { + if (place.id === weatherPlace && now.getTime() - weatherAt < WEATHER_REFRESH_MS) return; weatherAt = now.getTime(); - setFedWeather(currentWeather(await fetchWeatherFile(url), now)); + weatherPlace = place.id; + const feed = feedFor(place.id); + if (!feed) { + setFedWeather(CLEAR_SKY); + return; + } + const weather = currentWeather(await fetchWeatherFile(url, feed), place, now); + // The place the weather is for may have changed while the file was on the wire: `weatherPlace` is the one owner of it, and an answer for another place is dropped. + if (weatherPlace === place.id) setFedWeather(weather); } /** - * The ridge scene's `sky` option: the physical sky over Vienna for the state ('auto': the real sun now; a forced state: the - * sun of today at a moment inside it, `sunForState`), as a palette for the layers and stars plus the `physical` sky the host canvas + * 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, + * 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). */ export function ridgeSkyFor( - state: SkyState, - weather: number = ridgeWeather(), + choice: SkyChoice, + view: View, + weather: number = weatherFor(choice), now: Date = skyNow() ): SkyColours { - const { ground } = skyColours(); - const fixed = resolveSkyState(state, now); - const physical = makePhysicalSky(fixed, now, weather); + const physical = makePhysicalSky(sunAt(view.place, momentFor(choice, view.place, now)), weather, view); return { ...physical.stops, - ground, - band: SKY_BAND[fixed], physical, }; } -/** - * The terrain scene's `sky`, `sun` and `band` options. An explicit state draws its own sky and ignores the URL. 'auto' - * draws the sky it resolves to, unless the page URL steers (`?sun=` `?az=` `?sky=`, see `urlSky`): then the URL's sky, - * shaped into the band of the state the clock resolves to, which keeps any sun the URL picks inside that band. - */ -export function terrainSkyFor(state: SkyState): { - sky?: SkyName; - sun?: { elevation: number; azimuth?: number }; - band: SkyBand; -} { - const fixed = resolveSkyState(state); - const band = SKY_BAND[fixed]; - if (state === 'auto') { - const url = urlSky(); - if (url) return { ...url, band }; - } - switch (fixed) { - case 'day': - return { sky: 'noonday', band }; - case 'night': - return { sky: 'midnight', band }; - default: - return { sun: { elevation: DUSK_SUN_ELEVATION }, band }; - } -} - /** Relative luminance (WCAG) of the darkest and lightest colour a scene can draw. */ export interface Range { readonly darkest: number; @@ -101,86 +84,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 * sun's whole year over Vienna. Dark ink needs the floor; light ink the ceiling. */ -export function ridgeDrawn(state: SkyState): Range { - const b = BUDGET[resolveSkyState(state)]; +export function ridgeDrawn(band: FixedSkyState): Range { + const b = BUDGET[band]; return { darkest: b.floor, lightest: b.ceiling }; } - -/** - * How high the terrain camera can see, in degrees of elevation: it is frozen at a downward pitch and only turns - * (no pull-back), so the top edge of its view, at the centre column, is the pitch down subtracted from half the - * field of view (14.5 degrees; off-centre columns look lower). Plus a 1.5 degree margin. The terrain's range is - * over 0 to this, all azimuths, not the whole upper sphere; below the horizon the sky is the horizon's colour. - */ -export const TERRAIN_REACH_DEG = Math.ceil((CAMERA.fov / 2 - CAMERA.pitch) * (180 / Math.PI) + 1.5); - -const SAMPLE_DEG = 3; -const SUN_DEG = 0.1; -const SUN_SPAN_DEG = 8; -const HORIZON_DEG = 0.5; -const REFINE_FROM = 6; - -/** - * The terrain sky's range as the 8-bit screen shows it (`displayedLuminance`, read 'low' for the darkest and 'high' for the - * lightest: one 8-bit step each way, rounding and dither at their worst): `skyColour` (the CPU twin of its sky shader) over the part of the sky the camera reaches - * (0 to TERRAIN_REACH_DEG, every azimuth: it turns), for the sky the scene picks for this state. A 3 degree grid, a 0.5 degree - * ring of the horizon, the top of the reach and a 0.25 degree patch around the sun find where the extremes are; each of the - * best few is then refined by a compass search whose step halves from 1 degree to under 5e-7, because the sun's glow peaks - * (and the sky's darkest patch sits) between any fixed grid's samples. - */ -export function terrainDrawn(state: SkyState): Range { - const sky = chooseSky(terrainSkyFor(state)); - const rad = Math.PI / 180; - type Point = { el: number; az: number; read: number; score: number }; - const extreme = (reading: 'low' | 'high', sign: 1 | -1): number => { - const point = (el: number, az: number): Point => { - const e = Math.min(TERRAIN_REACH_DEG, Math.max(0, el)) * rad; - const a = az * rad; - const c = skyColour(sky, [ - Math.cos(e) * Math.sin(a), - Math.sin(e), - -Math.cos(e) * Math.cos(a), - ]); - const read = displayedLuminance(c, reading); - return { el, az, read, score: read }; - }; - const seen: Point[] = []; - const at = (el: number, az: number) => seen.push(point(el, az)); - for (let el = 0; el <= TERRAIN_REACH_DEG; el += SAMPLE_DEG) { - for (let az = 0; az < 360; az += SAMPLE_DEG) at(el, az); - } - for (let az = 0; az < 360; az += HORIZON_DEG) at(0, az); - at(TERRAIN_REACH_DEG, 0); - for (let dEl = -SUN_SPAN_DEG; dEl <= SUN_SPAN_DEG; dEl += SUN_DEG) { - for (let dAz = -SUN_SPAN_DEG; dAz <= SUN_SPAN_DEG; dAz += SUN_DEG) { - at(sky.elevation + dEl, sky.azimuth + dAz); - } - } - const around = (p: Point, step: number): Point[] => - [ - [step, 0], - [-step, 0], - [0, step], - [0, -step], - ].map(([dEl, dAz]) => - point(Math.min(TERRAIN_REACH_DEG, Math.max(0, p.el + dEl)), p.az + dAz) - ); - const refine = (from: Point) => { - let best = from; - for (let step = 1; step > 5e-7; step /= 2) { - let improved = true; - while (improved) { - const cur = best; - best = around(cur, step).reduce((b, c) => (sign * c.score > sign * b.score ? c : b), cur); - improved = best !== cur; - } - } - return best.read; - }; - const ranked = [...seen].sort((p, q) => sign * (q.score - p.score)); - return sign === 1 - ? Math.max(ranked[0].read, ...ranked.slice(0, REFINE_FROM).map(refine)) - : Math.min(ranked[0].read, ...ranked.slice(0, REFINE_FROM).map(refine)); - }; - return { darkest: extreme('low', -1), lightest: extreme('high', 1) }; -} diff --git a/src/app/features/scene/skyInk.test.ts b/src/app/features/scene/skyInk.test.ts index c92892f6..edb44929 100644 --- a/src/app/features/scene/skyInk.test.ts +++ b/src/app/features/scene/skyInk.test.ts @@ -1,9 +1,9 @@ import chroma from 'chroma-js'; import { describe, expect, it } from 'vitest'; import { baked } from '../../../sky/baked'; -import { AA, NIGHT_SKY_LIGHTEST, luminance } from '../../../sky/skyTokens.js'; +import { AA, luminance } from '../../../sky/skyTokens.js'; import { indexColorMXID } from '../../../util/colorMXID'; -import type { FixedSkyState } from './skyBand'; +import type { FixedSkyState } from './ridge/skyMoment'; import { LIGHTEST_PATCH, NIGHT_INK_MAX_L, @@ -115,8 +115,6 @@ describe('inkForState', () => { expect(chroma(aqua).oklch()[0]).toBeLessThanOrEqual(NIGHT_INK_MAX_L); expect(chroma(aqua).oklch()[1]).toBeGreaterThan(0.08); expect(patchRatio(aqua, 'night', true)).toBeGreaterThan(3.9); - // The one-patch figure is what the cap gives up; against the sky's own lightest (skyBackdrop) it clears AA. - expect((luminance(aqua) + 0.05) / (NIGHT_SKY_LIGHTEST + 0.05)).toBeGreaterThanOrEqual(AA); }); it('leaves a colour that already clears its patch untouched, and a non-colour alone', () => { @@ -138,29 +136,18 @@ describe('userColorInk', () => { }); }); -describe('sceneInk: an explicit theme wins over the auto ink', () => { - it('is the sky state and viewport only while the sky theme is worn and a scene runs', () => { - // auto, scene on, no theme of the person's own: the sky theme is worn. - expect(sceneInk(sceneThemeId('auto', 'dusk', true, false), true, 'dusk', true)).toEqual({ +describe('sceneInk: the drawn sky decides the ink', () => { + it('is the sky state and viewport while a scene runs, and nothing without one', () => { + expect(sceneInk(sceneThemeId('dusk', true), true, 'dusk', true)).toEqual({ state: 'dusk', phone: true, }); - // auto, but the person chose a theme: it wins, the theme's own ink stands. - expect(sceneInk(sceneThemeId('auto', 'dusk', true, true), true, 'dusk', true)).toBeUndefined(); - // a fixed sky state does not override the person's theme either: the theme's own ink stands. - expect( - sceneInk(sceneThemeId('night', 'night', true, true), true, 'night', false) - ).toBeUndefined(); - // a fixed sky state with no theme of the person's own: the sky theme's ink applies. - expect(sceneInk(sceneThemeId('night', 'night', true, false), true, 'night', false)).toEqual({ + expect(sceneInk(sceneThemeId('night', true), true, 'night', false)).toEqual({ state: 'night', phone: false, }); - // no scene behind the page: nothing for the ink to be measured against. - expect( - sceneInk(sceneThemeId('auto', 'day', false, false), false, 'day', false) - ).toBeUndefined(); - expect(sceneInk(sceneThemeId('day', 'day', true, false), false, 'day', false)).toBeUndefined(); + // no scene behind the page: the person's theme and its ink stand. + expect(sceneInk(sceneThemeId('day', false), false, 'day', false)).toBeUndefined(); }); }); diff --git a/src/app/features/scene/skyInk.ts b/src/app/features/scene/skyInk.ts index b8e38f31..d3aa2028 100644 --- a/src/app/features/scene/skyInk.ts +++ b/src/app/features/scene/skyInk.ts @@ -8,14 +8,14 @@ // until it clears 4.5:1 (WCAG) against the LIGHTEST 24x12 patch of terrain under the timeline in that state // and viewport. Measured 2026-11-10 on the demo's terrain scene at 1920x1080 and 390x844 (Chrome, SwiftShader, // not a GPU; ratatoskr-sidebar-contrast-20261110/results.md, T3). These are the scene's own patches, not -// `skyBackdrop` (skyState.ts): that is the bare sky's extreme (day 0.90, dusk 0.97), which the terrain under the -// timeline never shows, and at night the terrain's snow (0.103, phone 0.149) is lighter than the sky (0.0816). -// Only a person whose theme is the sky's (no explicit theme of their own, sceneThemeId) wears this ink. +// the bare sky: the terrain under the timeline is what the ink sits on, and at night its snow (0.103, phone 0.149) is +// lighter than the sky was when these were measured (0.0816). +// The page wears this ink whenever the drawn sky decides its theme (a scene is on, sceneThemeId). import chroma from 'chroma-js'; import { AA, luminance } from '../../../sky/skyTokens.js'; import { baked } from '../../../sky/baked'; import { indexColorMXID } from '../../../util/colorMXID'; -import type { FixedSkyState } from './skyBand'; +import type { FixedSkyState } from './ridge/skyMoment'; import type { SkyThemeId } from './skyTheme'; export interface SkyInk { @@ -25,15 +25,15 @@ export interface SkyInk { } /** - * The ink in force: only while the page wears the sky's theme (`themeId`, from sceneThemeId, so a person's explicit - * theme, which that function lets win over 'auto', keeps its own ink) and a scene runs behind it. Otherwise undefined. + * The ink in force: only while the page wears the sky's theme (`themeId`, from sceneThemeId, defined only while a + * scene is on) and a scene runs behind it. With no scene the person's theme and its own ink stand: undefined. */ export const sceneInk = ( themeId: SkyThemeId | undefined, sceneOn: boolean, - state: FixedSkyState, + state: FixedSkyState | undefined, 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. */ export const LIGHTEST_PATCH: Record = { diff --git a/src/app/features/scene/skyPlace.test.ts b/src/app/features/scene/skyPlace.test.ts new file mode 100644 index 00000000..94cc3284 --- /dev/null +++ b/src/app/features/scene/skyPlace.test.ts @@ -0,0 +1,98 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { forgetManifests } from './ridge/manifest'; +import { wireIndex, wireManifest } from './ridge/manifest.fixture'; +import { momentFor } from './ridge/skyMoment'; +import type { SkyChoice } from './ridge/skyMoment'; +import { sunAt } from './ridge/sunAt'; +import { drawnView, ensureSkyPlace, loadPlaceManifest, resolvePlaceId } from './skyPlace'; +import { forgetPlaceChoice, setPlaceChoice } from './placeState'; +import { getSkyPlace, setSkyPlace, subscribe } from './skyState'; + +const index = { + default: 'vienna', + places: { vienna: 'v', fuji: 'f', matterhorn: 'm', amadablam: 'a', grandcanyon: 'g' }, +}; + +describe('which place is drawn', () => { + it('is the listed viewer choice before the config place, the config place before the default', () => { + expect(resolvePlaceId(index, 'matterhorn', 'fuji')).toBe('fuji'); + expect(resolvePlaceId(index, 'matterhorn', undefined)).toBe('matterhorn'); + expect(resolvePlaceId(index, undefined, undefined)).toBe('vienna'); + }); + it('ignores an unlisted viewer choice, and falls to the default for an unlisted config place', () => { + expect(resolvePlaceId(index, 'matterhorn', 'atlantis')).toBe('matterhorn'); + expect(resolvePlaceId(index, 'atlantis', 'atlantis')).toBe('vienna'); + expect(resolvePlaceId(index, undefined, 'constructor')).toBe('vienna'); + }); +}); + +describe('the place drawn follows the choice through the one resolution', () => { + const noon: SkyChoice = { kind: 'named', id: 'noon' }; + const at = new Date('2030-06-21T09:00:00Z'); + const names: Record = { + 'v/manifest.json': 'vienna', + 'f/manifest.json': 'fuji', + }; + beforeEach(() => { + vi.stubGlobal('localStorage', { getItem: () => null, setItem: () => undefined }); + forgetPlaceChoice(); + forgetManifests(); + vi.stubGlobal( + 'fetch', + vi.fn(async (url: string) => { + const id = Object.entries(names).find(([k]) => url.endsWith(`/${k}`))?.[1]; + const w = wireManifest() as { place: Record }; + const body = url.endsWith('index.json') + ? { ...wireIndex, places: { vienna: 'v', fuji: 'f' } } + : { + ...w, + place: { + ...w.place, + id, + name: id, + ...(id === 'fuji' ? { lat: 35.2, lon: 138.6, tz: 'Asia/Tokyo' } : {}), + }, + }; + return { ok: true, status: 200, json: async () => body }; + }) + ); + }); + afterEach(() => { + vi.unstubAllGlobals(); + forgetPlaceChoice(); + }); + + it("a pick resolves to that place's own sun (Fuji at Noon is another instant than Vienna at Noon), and only a made scene moves the store's place", async () => { + setSkyPlace(undefined); + const heard = vi.fn(); + const off = subscribe(heard); + const a = await ensureSkyPlace(undefined); + expect(a.view.place.id).toBe('vienna'); + expect(getSkyPlace()).toBeUndefined(); // asked for, not drawn + expect(heard).not.toHaveBeenCalled(); + setPlaceChoice('fuji'); + const b = await ensureSkyPlace(undefined); + expect(b.view.place.id).toBe('fuji'); + expect(getSkyPlace()).toBeUndefined(); // a build that has not been made names nothing + expect(heard).not.toHaveBeenCalled(); + drawnView(a.manifest); + drawnView(a.manifest); // the same place again: no further change + expect(getSkyPlace()?.id).toBe('vienna'); + expect(heard).toHaveBeenCalledTimes(1); + drawnView(b.manifest); + expect(getSkyPlace()?.id).toBe('fuji'); + expect(heard).toHaveBeenCalledTimes(2); + const noonAt = (p: typeof a.view.place) => momentFor(noon, p, at).getTime(); + expect(noonAt(b.view.place)).not.toBe(noonAt(a.view.place)); + expect(sunAt(b.view.place, momentFor(noon, b.view.place, at)).elevation).toBeGreaterThan(60); + off(); + }); + + it('loads the manifest of the resolved place for any reader', async () => { + setPlaceChoice('fuji'); + expect((await loadPlaceManifest({ place: 'vienna' })).name).toBe('fuji'); + setPlaceChoice('atlantis'); + expect((await loadPlaceManifest({ place: 'fuji' })).name).toBe('fuji'); + expect((await loadPlaceManifest(undefined)).name).toBe('vienna'); + }); +}); diff --git a/src/app/features/scene/skyPlace.ts b/src/app/features/scene/skyPlace.ts new file mode 100644 index 00000000..7d2096ba --- /dev/null +++ b/src/app/features/scene/skyPlace.ts @@ -0,0 +1,64 @@ +// The place the sky is over, and the one decision of which place is drawn: the viewer's choice (placeState.ts) if the index lists it, else the config's place if +// listed, else the index's default. The store (skyState.ts) holds the DRAWN place, and `drawnView` is the only writer of it, called when a scene is made: the +// baked place's manifest when the ridge planes are drawn, 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. The pick is a wish and `ensureSkyPlace` only resolves it; a place whose build is still loading, or failed, +// is never the store's. So the carousel, the credits, the ink and the Auto timer all read the place the canvas 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 { loadIndex, loadManifest } from './ridge/manifest'; +import type { RidgeIndex, RidgeManifest } from './ridge/manifest'; +import { getPlaceChoice } from './placeState'; +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; + +/** The id of the place to draw: the viewer's choice if the index lists it, else the config's if listed, else the index's default. An id the index does not list decides nothing. */ +export const resolvePlaceId = ( + index: Pick, + configPlace: string | undefined, + choice: string | undefined = getPlaceChoice() +): string => + [choice, configPlace].find( + (id): id is string => id !== undefined && Object.prototype.hasOwnProperty.call(index.places, id) + ) ?? index.default; + +/** The manifest of the place to draw (`resolvePlaceId`); memoised, rejects on any failure. */ +export async function loadPlaceManifest( + config: Pick | undefined +): Promise { + const base = import.meta.env.BASE_URL; + return loadManifest(base, resolvePlaceId(await loadIndex(base), config?.place)); +} + +/** A scene start is a fresh attempt at the planes. */ +export function resetSkyPlanes(): void { + skyOnly = false; +} + +/** + * Load the manifest of the place to draw (`resolvePlaceId`) and return the view a build for it draws. Safe to call whenever a reader wants the view: the load is memoised. + * Writes nothing: the store's place is the one drawn (`drawnView`), not the one asked for. 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 | undefined +): Promise<{ manifest: RidgeManifest | null; view: View; fail: Error | null }> { + let manifest: RidgeManifest | null = null; + let fail: Error | null = null; + try { + manifest = await loadPlaceManifest(config); + } catch (e) { + fail = e instanceof Error ? e : new Error(String(e)); + } + const view = manifest && !skyOnly ? manifest.view : FALLBACK_VIEW; + return { manifest, view, fail }; +} + +/** A scene has been made and is now what is drawn: its manifest's planes (the manifest), or the sky alone (null). Makes that view's place the sky's. The one writer of the store's place. */ +export function drawnView(manifest: RidgeManifest | null): void { + skyOnly = manifest === null; + setSkyPlace((manifest?.view ?? FALLBACK_VIEW).place); +} diff --git a/src/app/features/scene/skyPlate.ts b/src/app/features/scene/skyPlate.ts index b82a3026..f7bb02c9 100644 --- a/src/app/features/scene/skyPlate.ts +++ b/src/app/features/scene/skyPlate.ts @@ -13,7 +13,7 @@ export const SKY_PLATE_FALLBACK = { * footer line. The footer is a blurred, tinted band with soft edges, not a plate: the scene shows through it. The * footer ink is the plate's, so the tint has to bring the scene behind it to where that ink clears 4.5:1. The browser * mixes in sRGB, so the test does too (skyTheme.test.ts): over pure black 0.80 gives 4.36 and 0.82 gives 4.55. The - * terrain is not black: in the shots at 390x844 (terrain scene, tier low) the darkest pixel in the footer's region is + * background is not black: in the shots at 390x844 (taken on the earlier terrain scene, tier low; not re-measured on the ridges) the darkest pixel in the footer's region is * 0.0203 at Dusk, 0.0936 at Day (dark ink) and 0.0052 at Night (light ink). Measured on the drawn pixels with the band * on, the worst link contrast is 5.0 at Dusk, 5.7 at Day and 11.2 at Night. */ diff --git a/src/app/features/scene/skyState.test.ts b/src/app/features/scene/skyState.test.ts index d0a902a2..ffd25717 100644 --- a/src/app/features/scene/skyState.test.ts +++ b/src/app/features/scene/skyState.test.ts @@ -1,17 +1,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { atStandardTime } from './standardTime.testkit'; -import { baked } from '../../../sky/baked'; -import { luminance } from '../../../sky/skyTokens.js'; -import { - SKY_STATES, - SKY_STATE_KEY, - resolveSkyState, - setSkyClock, - skyBackdrop, - type SkyState, -} from './skyState'; +import { atSolarTime } from './ridge/skyTestkit'; +import { FALLBACK_VIEW } from './ridge/view'; +import { sceneThemeId } from './skyTheme'; +import { SKY_CHOICE_KEY } from './skyState'; +import type { SkyChoice } from './ridge/skyMoment'; 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 = {}) { const data = new Map(Object.entries(initial)); @@ -21,6 +21,9 @@ function fakeStorage(initial: Record = {}) { setItem: (k: string, v: string) => { data.set(k, v); }, + removeItem: (k: string) => { + data.delete(k); + }, }; } const fresh = (): Promise => { @@ -32,31 +35,74 @@ afterEach(() => { vi.unstubAllGlobals(); }); -describe('sky state', () => { +describe('persistence', () => { let storage: ReturnType; beforeEach(() => { storage = fakeStorage(); vi.stubGlobal('localStorage', storage); }); - it('defaults to auto when nothing is stored', async () => { - expect((await fresh()).getSkyState()).toBe('auto'); + it('defaults to Auto when nothing is stored', async () => { + expect((await fresh()).getSkyChoice()).toEqual(auto); }); - it.each(['night', 'day', 'dusk', 'auto'] as const)('restores a stored %s', async (s) => { - storage.data.set(SKY_STATE_KEY, s); - expect((await fresh()).getSkyState()).toBe(s); - }); - - 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.each([auto, noon, night, { kind: 'free', date: '2026-12-21', minutes: 400 }] as SkyChoice[])( + 'restores a stored %j', + async (c) => { + storage.data.set(SKY_CHOICE_KEY, JSON.stringify(c)); + expect((await fresh()).getSkyChoice()).toEqual(c); } ); - 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', { getItem: () => { throw new Error('denied'); @@ -64,103 +110,154 @@ describe('sky state', () => { setItem: () => { throw new Error('denied'); }, + removeItem: () => { + throw new Error('denied'); + }, }); const m = await fresh(); - expect(m.getSkyState()).toBe('auto'); - m.setSkyState('night'); - expect(m.getSkyState()).toBe('night'); + expect(m.getSkyChoice()).toEqual(auto); + m.setSkyChoice(night); + expect(m.getSkyChoice()).toEqual(night); }); - it('persists a set state under one key and reads it back after a reload', async () => { - (await fresh()).setSkyState('dusk'); - expect([...storage.data.entries()]).toEqual([[SKY_STATE_KEY, 'dusk']]); - expect((await fresh()).getSkyState()).toBe('dusk'); + 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 () => { + storage.data.set(OLD_KEY, 'day'); + vi.stubGlobal('localStorage', { + ...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(); - m.setSkyState('night'); - m.setSkyState('noon' as SkyState); - expect(m.getSkyState()).toBe('night'); - expect(storage.data.get(SKY_STATE_KEY)).toBe('night'); + m.setSkyChoice(night); + m.setSkyChoice({ kind: 'named', id: 'midday' } as unknown as SkyChoice); + expect(m.getSkyChoice()).toEqual(night); }); it('notifies subscribers on change only, and stops after unsubscribe', async () => { const m = await fresh(); + m.setSkyPlace(VIENNA); const cb = vi.fn(); const off = m.subscribe(cb); - m.setSkyState('day'); - m.setSkyState('day'); - expect(cb.mock.calls).toEqual([['day']]); + m.setSkyChoice(noon); + m.setSkyChoice(noon); + expect(cb).toHaveBeenCalledTimes(1); off(); - m.setSkyState('night'); + m.setSkyChoice(night); expect(cb).toHaveBeenCalledTimes(1); }); it('tells a late subscriber nothing until the next change', async () => { const m = await fresh(); - m.setSkyState('day'); + m.setSkyChoice(noon); const cb = vi.fn(); m.subscribe(cb); expect(cb).not.toHaveBeenCalled(); }); }); -describe('skyBackdrop', () => { - 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).toBeGreaterThanOrEqual(skyBackdrop('day').lightest); +describe('one authority: the choice at the place decides the sky and the ink', () => { + let m: Mod; + beforeEach(async () => { + vi.stubGlobal('localStorage', fakeStorage()); + m = await fresh(); + m.setSkyClock(() => atSolarTime(0, 0)); }); - it('holds the baked gradients for day and night', () => { - const lum = (g: readonly string[]) => g.map(luminance); - expect(skyBackdrop('day').lightest).toBeGreaterThanOrEqual( - Math.max(...lum(baked.noonday.gradient)) - 1e-9 - ); - expect(skyBackdrop('night').darkest).toBeLessThanOrEqual( - Math.min(...lum(baked.midnight.gradient)) + 1e-9 - ); + 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('is the band of the sky auto resolves to, not the union of all three', () => { - const at = (h: number) => setSkyClock(() => atStandardTime(h, 0)); - at(12); - expect(skyBackdrop('auto')).toEqual(skyBackdrop('day')); - at(0); - expect(skyBackdrop('auto')).toEqual(skyBackdrop('night')); - setSkyClock(); + 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('never has darkest above lightest', () => { - SKY_STATES.forEach((s) => - expect(skyBackdrop(s).darkest).toBeLessThanOrEqual(skyBackdrop(s).lightest) - ); + 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) => atStandardTime(h, m); // local solar time ~ local clock - let storage: ReturnType; +describe('Auto follows the clock', () => { + const local = (h: number, m = 0) => atSolarTime(h, m); beforeEach(() => { vi.useFakeTimers(); - storage = fakeStorage(); - vi.stubGlobal('localStorage', storage); + vi.stubGlobal('localStorage', fakeStorage()); }); afterEach(() => { vi.useRealTimers(); }); - it('resolves noon to day, midnight to night and the twilight after sunset to dusk', () => { - expect(resolveSkyState('auto', local(12))).toBe('day'); - expect(resolveSkyState('auto', local(0))).toBe('night'); - expect(resolveSkyState('auto', local(18, 10))).toBe('dusk'); - expect(resolveSkyState('auto', local(5, 50))).toBe('dusk'); - expect(resolveSkyState('day', local(0))).toBe('day'); + it('is the real sun over the place: noon is day, midnight night and the twilight after sunset dusk', async () => { + const m = await fresh(); + m.setSkyPlace(VIENNA); + const at = (t: Date) => { + m.setSkyClock(() => t); + 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 () => { const m = await fresh(); + m.setSkyPlace(VIENNA); let now = local(17, 0); m.setSkyClock(() => now); const cb = vi.fn(); @@ -177,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 () => { const m = await fresh(); + m.setSkyPlace(VIENNA); let now = local(17, 0); m.setSkyClock(() => now); const [a, b, late] = [vi.fn(), vi.fn(), vi.fn()]; @@ -193,25 +291,119 @@ describe('auto follows the clock', () => { 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 off = m.subscribe(() => undefined); expect(vi.getTimerCount()).toBe(1); - m.setSkyState('night'); + m.setSkyChoice({ kind: 'free', date: '2026-07-01', minutes: 600 }); expect(vi.getTimerCount()).toBe(0); - m.setSkyState('auto'); + m.setSkyChoice(night); + expect(vi.getTimerCount()).toBe(1); + m.setSkyChoice(auto); expect(vi.getTimerCount()).toBe(1); off(); 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 () => { const m = await fresh(); + m.setSkyPlace(VIENNA); m.setSkyClock(() => local(12)); const cb = vi.fn(); m.subscribe(cb); - m.setSkyState('night'); - m.setSkyState('auto'); + m.setSkyChoice(night); + m.setSkyChoice(auto); expect(cb.mock.calls).toEqual([['night'], ['day']]); }); }); + +describe('the constellation lines', () => { + let storage: ReturnType; + beforeEach(() => { + storage = fakeStorage(); + vi.stubGlobal('localStorage', storage); + }); + + it('are off by default, and picking Night is a plain choice that leaves them off', async () => { + const m = await fresh(); + expect(m.getConstellationLines()).toBe(false); + m.setSkyChoice(night); + expect(m.getSkyChoice()).toEqual(night); + expect(m.getConstellationLines()).toBe(false); + }); + + it('picking Night while the choice is Night does nothing: no toggle, no notice', async () => { + const m = await fresh(); + m.setSkyPlace(VIENNA); + m.setSkyChoice(night); + const cb = vi.fn(); + m.subscribe(cb); + m.setSkyChoice(night); + m.setSkyChoice(night); + expect(m.getConstellationLines()).toBe(false); + expect(cb).not.toHaveBeenCalled(); + expect(m.getSkyChoice()).toEqual(night); + }); + + it('setConstellationLines sets them, tells the listeners once per change, and keeps the choice', async () => { + const m = await fresh(); + m.setSkyPlace(VIENNA); + m.setSkyChoice(night); + const cb = vi.fn(); + m.subscribe(cb); + m.setConstellationLines(true); + m.setConstellationLines(true); + expect(m.getConstellationLines()).toBe(true); + expect(cb.mock.calls).toEqual([['night']]); + expect(m.getSkyChoice()).toEqual(night); + m.setConstellationLines(false); + expect(m.getConstellationLines()).toBe(false); + expect(cb).toHaveBeenCalledTimes(2); + }); + + it('persist per viewer, and come back from storage', async () => { + const m = await fresh(); + m.setConstellationLines(true); + expect(storage.data.get(m.SKY_LINES_KEY)).toBe('on'); + const again = await fresh(); + expect(again.getConstellationLines()).toBe(true); + again.setConstellationLines(false); + expect(storage.data.get(again.SKY_LINES_KEY)).toBe('off'); + }); + + it('survive a refused storage: they hold for the page and read as off from a broken store', async () => { + vi.stubGlobal('localStorage', { + getItem: () => { + throw new Error('denied'); + }, + setItem: () => { + throw new Error('denied'); + }, + removeItem: () => { + throw new Error('denied'); + }, + }); + const m = await fresh(); + expect(m.getConstellationLines()).toBe(false); + m.setConstellationLines(true); + expect(m.getConstellationLines()).toBe(true); + }); +}); diff --git a/src/app/features/scene/skyState.ts b/src/app/features/scene/skyState.ts index 52b0cdc8..3267468c 100644 --- a/src/app/features/scene/skyState.ts +++ b/src/app/features/scene/skyState.ts @@ -1,100 +1,154 @@ -// Which sky the signed-out page is drawn against. The choice is one value, kept in one -// localStorage key; whoever draws the sky (the scene, the title bar's control) reads it here, and -// `skyBackdrop` says how light or dark the sky behind the login text can be in each state, so the -// text colours can be checked against it. 'auto' is a choice, not a sky: it resolves from the -// clock to day, dusk or night (`resolveSkyState`), and every sky drawn is one of those three. -import { sunElevation } from '../../../sky/sun.js'; -import type { FixedSkyState } from './skyBand'; +// 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 +// named moment, a free moment), the place the sky is over, and the constellation lines. They decide nothing: which instant is drawn is +// `momentFor` and which band it is, `skyBand` (ridge/skyMoment.ts); the resolved sky here is those two applied to the stores. +import { MOMENT_IDS, FREE_DATE_MAX, FREE_DATE_MIN, isDate, momentFor, momentKey, skyBand } from './ridge/skyMoment'; +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']; -export const SKY_STATE_KEY = 'ratatoskr.skyState'; +const AUTO: SkyChoice = { kind: 'auto' }; -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; + 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 old 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([ + ['auto', AUTO], + ['day', { kind: 'named', id: 'noon' }], + ['dusk', { kind: 'named', id: 'dusk' }], + ['night', { kind: 'named', id: 'night' }], +]); + +function load(): SkyChoice { try { - const stored = localStorage.getItem(SKY_STATE_KEY); - return isSkyState(stored) ? stored : 'auto'; + const old = localStorage.getItem(OLD_KEY); + 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 { + 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'; + return AUTO; } } -export type { FixedSkyState }; - -/** 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(); -/** 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: on or off, per viewer, off by default; set by `setConstellationLines`. */ +export const SKY_LINES_KEY = 'ratatoskr.skyLines'; +let lines: boolean | undefined; -let current: SkyState | undefined; -const listeners = new Set<(s: FixedSkyState) => void>(); +/** Whether the constellation lines are on: the stored choice of this viewer. They are drawn over the real stars of a night sky only. */ +export const getConstellationLines = (): boolean => { + if (lines === undefined) { + try { + lines = localStorage.getItem(SKY_LINES_KEY) === 'on'; + } catch { + lines = false; + } + } + return lines; +}; + +let current: SkyChoice | undefined; +let place: Place | undefined; +const listeners = new Set<(s: FixedSkyState | undefined) => void>(); let timer: ReturnType | undefined; let shown: FixedSkyState | undefined; +let shownKey: string | undefined; const TICK_MS = 60_000; /** The choice (what the control shows). */ -export const getSkyState = (): SkyState => { +export const getSkyChoice = (): SkyChoice => { current ??= load(); return current; }; -/** The sky being drawn: the choice, resolved. */ -export const getResolvedSkyState = (): FixedSkyState => resolveSkyState(getSkyState()); +/** The place the sky is over: the place of the scene that is up, set by skyPlace.ts when a scene is made; undefined until one is. */ +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 && skyBandAt(getSkyChoice(), place); + +/** The band of `choice` at `at`, for any place: what a build for a place not yet drawn is told, since the store holds only the drawn one. */ +export const skyBandAt = (choice: SkyChoice, at: Place, now: Date = skyNow()): FixedSkyState => + skyBand(sunAt(at, momentFor(choice, at, now)).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 = () => { 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 -// listeners when the resolved sky changes from the one last told (`shown`, set when telling and when the -// first listener arrives, never by a later arrival or departure). Otherwise there is no timer. +// 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 band, or the moment drawn (an Auto band, a named moment's place-local day), changes from the one +// 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 { clearTimeout(timer); timer = undefined; - if (listeners.size === 0 || getSkyState() !== 'auto') return; + if (listeners.size === 0 || getSkyChoice().kind === 'free') return; const tick = () => { - if (getResolvedSkyState() !== shown) emit(); + if (getResolvedSkyState() !== shown || drawnKey() !== shownKey) emit(); 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. */ export function setSkyClock(now?: () => Date): void { clock = now ?? (() => new Date()); sync(); } -export function setSkyState(s: SkyState): void { - if (!isSkyState(s)) return; - const changed = s !== getSkyState(); - current = s; +export function setSkyChoice(c: SkyChoice): void { + const next = parseSkyChoice(c); + if (!next) return; + const changed = !same(next, getSkyChoice()); + current = next; try { - localStorage.setItem(SKY_STATE_KEY, s); + localStorage.setItem(SKY_CHOICE_KEY, JSON.stringify(next)); } catch { // Storage is refused (private mode, quota): the choice holds for this page load only. } @@ -104,9 +158,36 @@ export function setSkyState(s: SkyState): void { } } -/** Listeners hear the resolved sky: on a change of choice, and while 'auto', when the clock crosses a boundary. */ -export function subscribe(cb: (s: FixedSkyState) => void): () => void { - if (listeners.size === 0) shown = getResolvedSkyState(); +/** The place the sky is over (skyPlace.ts `drawnView`, when a scene is made). 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(); +} + +/** + * The constellation lines on or off (the Sky submenu of the scene view, ruling ridge-scene-view-submenus): per viewer, stored. Listeners hear it as a sky change + * (the scene is rebuilt for it: `ridgeSkyKey` carries the flag), once, and only when the flag moved. This is the one setter; picking Night again sets nothing. + */ +export function setConstellationLines(on: boolean): void { + if (getConstellationLines() === on) return; + lines = on; + try { + localStorage.setItem(SKY_LINES_KEY, on ? 'on' : 'off'); + } catch { + // Storage is refused: the lines hold for this page load only. + } + emit(); +} + +/** 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 | undefined) => void): () => void { + if (listeners.size === 0) { + shown = getResolvedSkyState(); + shownKey = drawnKey(); + } listeners.add(cb); sync(); return () => { @@ -114,29 +195,3 @@ export function subscribe(cb: (s: FixedSkyState) => void): () => void { sync(); }; } - -/** - * Relative luminance (WCAG, 0..1) of the lightest and darkest sky the state can show behind the - * page. Light ink is worst against `lightest`, dark ink against `darkest`. 'auto' is the band of - * the sky it resolves to now. - */ -export interface SkyBackdrop { - readonly darkest: number; - readonly lightest: number; -} - -// The union of every sky a scene draws for the state: the ridge sky and the terrain sky, each from -// the function its scene uses (`ridgeDrawn`, `terrainDrawn` in skyForState.ts). The ridge sky is the physical sky over Vienna, its -// display fitted to the state's budget (ridge/toneMap.ts `BUDGET`): the budget is its extreme, whatever the sun's elevation. Held as constants so -// this module, which the main chunk loads, does not pull in the terrain sky and the baked scattering -// tables with it; skyForState.test.ts fails when they drift from the computed union. The ridge sky counts -// over its whole range, the terrain sky over what its frozen camera reaches (TERRAIN_REACH_DEG, skyForState.ts). -// 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 = { - day: { darkest: 0.461063, lightest: 1 }, - dusk: { darkest: 0.460352, lightest: 1 }, - night: { darkest: 0, lightest: 0.081642 }, -}; - -export const skyBackdrop = (state: SkyState): SkyBackdrop => BACKDROPS[resolveSkyState(state)]; diff --git a/src/app/features/scene/skyTheme.test.ts b/src/app/features/scene/skyTheme.test.ts index aab972fb..cce8a657 100644 --- a/src/app/features/scene/skyTheme.test.ts +++ b/src/app/features/scene/skyTheme.test.ts @@ -1,7 +1,7 @@ -import { describe, expect, it, vi } from 'vitest'; -import { atStandardTime } from './standardTime.testkit'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import { atSolarTime } from './ridge/skyTestkit'; import { baked } from '../../../sky/baked'; -import { AA, NIGHT_SKY_LIGHTEST, contrast, luminance } from '../../../sky/skyTokens.js'; +import { AA, contrast } from '../../../sky/skyTokens.js'; import { Editor } from '../../components/editor/Editor.css'; import { PageContent, PageNavContent } from '../../components/page/style.css'; import { CallStatus } from '../call-status/styles.css'; @@ -12,80 +12,61 @@ import { SkyPlate, plateRegions } from './skyPlate.css'; import { getResolvedSkyState, setSkyClock, - skyBackdrop, + setSkyPlace, subscribe as subscribeSky, } from './skyState'; -import type { SkyBackdrop } from './skyState'; -import type { FixedSkyState } from './skyBand'; -import { sceneThemeId, skyThemeId } 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 fixed = (['day', 'dusk', 'night'] as const).flatMap((s) => { - const id = skyThemeId(s); - return id ? [[s, id] as const] : []; +const r2 = (n: number) => n.toFixed(2); +const fixed = (['day', 'dusk', 'night'] as const).flatMap((st) => { + const id = sceneThemeId(st, true); + return id ? [[st, id] as const] : []; }); -// WCAG contrast of an ink against the sky it is worst on, measured as skyState.test.ts does: the -// sky can show any luminance between its darkest and lightest, and contrast is lowest where the -// backdrop is closest to the ink, which is the ink's own luminance clamped into that range. -const against = (ink: string, bg: number) => { - const li = luminance(ink); - const [hi, lo] = li > bg ? [li, bg] : [bg, li]; - return (hi + 0.05) / (lo + 0.05); -}; -const ratio = (ink: string, b: SkyBackdrop) => - against(ink, Math.min(b.lightest, Math.max(b.darkest, luminance(ink)))); -const r2 = (n: number) => n.toFixed(2); - -describe('skyThemeId', () => { - it('picks a theme for each explicit state', () => { - expect(skyThemeId('day')).toBe('noonday-sky'); - expect(skyThemeId('dusk')).toBe('noonday-sky'); - expect(skyThemeId('night')).toBe('midnight-sky'); +describe('sceneThemeId, the theme the page wears', () => { + it('with a scene on, the drawn sky gives its theme, whatever theme a person stored', () => { + expect(sceneThemeId('day', true)).toBe('noonday-sky'); + expect(sceneThemeId('dusk', true)).toBe('noonday-sky'); + expect(sceneThemeId('night', true)).toBe('midnight-sky'); }); - it('picks none for auto, at any hour: auto never overrides a signed-in theme', () => { - [0, 6, 12, 18, 23].forEach((h) => { - setSkyClock(() => atStandardTime(h, 10)); - expect(skyThemeId('auto')).toBeUndefined(); + it('auto draws the clock sky and that sky decides', () => { + [0, 12, 23].forEach((h) => { + setSkyClock(() => atSolarTime(h, 10)); + expect(sceneThemeId(getResolvedSkyState(), true)).toBe( + h === 12 ? 'noonday-sky' : 'midnight-sky' + ); }); setSkyClock(); }); - describe('sceneThemeId, the theme the page wears', () => { - it('a fixed state picks its theme, whatever the scene, while the person chose no theme', () => { - [true, false].forEach((scene) => { - expect(sceneThemeId('day', 'night', scene, false)).toBe('noonday-sky'); - expect(sceneThemeId('night', 'day', scene, false)).toBe('midnight-sky'); - }); - }); + 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('a theme the person chose wins over every sky state, fixed or auto', () => { - (['auto', 'day', 'dusk', 'night'] as const).forEach((state) => - [true, false].forEach((scene) => - expect(sceneThemeId(state, 'night', scene, true)).toBeUndefined() - ) - ); - }); - - it('auto follows the resolved sky only while a scene is on and the person chose no theme', () => { - expect(sceneThemeId('auto', 'day', true, false)).toBe('noonday-sky'); - expect(sceneThemeId('auto', 'dusk', true, false)).toBe('noonday-sky'); - expect(sceneThemeId('auto', 'night', true, false)).toBe('midnight-sky'); - expect(sceneThemeId('auto', 'day', false, false)).toBeUndefined(); - expect(sceneThemeId('auto', 'day', true, true)).toBeUndefined(); - }); + it('with the scene off no sky is drawn, so the person theme stands', () => { + (['day', 'dusk', 'night'] as const).forEach((st) => + expect(sceneThemeId(st, false)).toBeUndefined() + ); }); it('the resolved sky a hook subscribes to changes as the clock crosses, so theme classes follow', () => { vi.useFakeTimers(); let hour = 12; - setSkyClock(() => atStandardTime(hour, 10)); - const seen: string[] = []; + setSkyClock(() => atSolarTime(hour, 10)); + const seen: Array = []; const off = subscribeSky((s) => seen.push(s)); expect(getResolvedSkyState()).toBe('day'); hour = 0; - setSkyClock(() => atStandardTime(hour, 10)); + setSkyClock(() => atSolarTime(hour, 10)); vi.advanceTimersByTime(61_000); expect(seen).toEqual(['night']); expect(getResolvedSkyState()).toBe('night'); @@ -93,69 +74,6 @@ describe('skyThemeId', () => { vi.useRealTimers(); setSkyClock(); }); - - it('is what a wiring that follows the sky reads: the resolved state names a theme', () => { - setSkyClock(() => atStandardTime(12)); - expect(skyThemeId(getResolvedSkyState())).toBe('noonday-sky'); - setSkyClock(() => atStandardTime(0)); - expect(skyThemeId(getResolvedSkyState())).toBe('midnight-sky'); - setSkyClock(); - }); -}); - -describe('ink of the theme a state picks, on bare sky', () => { - // Per state: the picked theme, its text ink and link, and their WCAG ratios on the sky the scenes - // draw (skyBackdrop, the worst case over its band). Text clears 4.5 in every state. Link clears - // in every state: the links are derived in src/sky/skyTokens.js, outside the band, and these numbers are recorded as - // they are measured. Midnight's link is brightened in its own hue until it clears the lightest Night sky - // (NIGHT_SKY_LIGHTEST); Dusk's dark link needs a backdrop of about 0.4554, which the dusk floor is set above. - // 'auto' resolves from the clock to one of these three and has the same numbers. - const cells: [FixedSkyState, string, string, string, string, string][] = [ - ['day', 'noonday-sky', '#342d25', '6.60', '#2a4f27', '4.55'], - ['dusk', 'noonday-sky', '#342d25', '6.59', '#2a4f27', '4.54'], - ['night', 'midnight-sky', '#aeccff', '4.89', '#8ad1bd', '4.53'], - ]; - - it.each(cells)( - '%s with %s: text %s is %s, link %s is %s', - (state, id, ink, want, link, wantLink) => { - const sky = SKY[id as keyof typeof SKY]; - expect(sky.tokens.Background.OnContainer).toBe(ink); - expect(sky.link).toBe(link); - expect(r2(ratio(ink, skyBackdrop(state)))).toBe(want); - expect(r2(ratio(link, skyBackdrop(state)))).toBe(wantLink); - } - ); - - it.each(cells)('%s: text clears AA', (state, _id, ink) => { - expect(ratio(ink, skyBackdrop(state))).toBeGreaterThanOrEqual(AA); - }); - - it('link clears AA in every state', () => { - const link = (s: FixedSkyState, id: keyof typeof SKY) => ratio(SKY[id].link, skyBackdrop(s)); - expect(link('day', 'noonday-sky')).toBeGreaterThanOrEqual(AA); - expect(link('dusk', 'noonday-sky')).toBeGreaterThanOrEqual(AA); - expect(link('night', 'midnight-sky')).toBeGreaterThanOrEqual(AA); - }); - - it('keeps the lightest Night sky the link was fitted to equal to the Night backdrop (no drift)', () => { - expect(NIGHT_SKY_LIGHTEST).toBe(skyBackdrop('night').lightest); - }); - - it.each([ - [12, 'day'], - [18, 'dusk'], - [0, 'night'], - ] as const)('auto at %s:00 has the numbers of %s', (hour, state) => { - setSkyClock(() => atStandardTime(hour, hour === 18 ? 10 : 0)); - const id = skyThemeId(getResolvedSkyState()) as keyof typeof SKY; - expect(id).toBe(skyThemeId(state)); - const { tokens, link } = SKY[id]; - const text = tokens.Background.OnContainer; - expect(r2(ratio(text, skyBackdrop('auto')))).toBe(r2(ratio(text, skyBackdrop(state)))); - expect(r2(ratio(link, skyBackdrop('auto')))).toBe(r2(ratio(link, skyBackdrop(state)))); - setSkyClock(); - }); }); describe('the plate, where text cannot rest on bare sky', () => { @@ -218,7 +136,7 @@ describe('regions that sit on the plate', () => { describe('the sign-in footer band', () => { // The footer line is the plate's ink on a band that mixes FOOTER_TINT of the plate's fill over the blurred scene, // as the browser does: per channel, in encoded sRGB (not in linear light, which flatters dark scenes). The scene - // behind it is the terrain, taken as grey: as dark as 0, as light as the sky state's lightest backdrop. Ink + // behind it is the scene, taken as grey: as dark as 0 or as light as 1 (a sky's range is whatever the look draws). Ink // contrast is lowest at one of those two ends, so both are checked. const encode = (l: number) => (l <= 0.0031308 ? 12.92 * l : 1.055 * l ** (1 / 2.4) - 0.055); const channels = (hex: string) => [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255); @@ -236,7 +154,7 @@ describe('the sign-in footer band', () => { '%s: the ink clears AA over the darkest and the lightest scene behind it', (state, id) => { const { Other, OtherText } = SKY[id].bubbles; - [0, skyBackdrop(state).lightest].forEach((behind) => { + [0, 1].forEach((behind) => { expect(contrast(OtherText, bandOver(Other, behind))).toBeGreaterThanOrEqual(AA); }); } diff --git a/src/app/features/scene/skyTheme.ts b/src/app/features/scene/skyTheme.ts index e1934d81..8993b127 100644 --- a/src/app/features/scene/skyTheme.ts +++ b/src/app/features/scene/skyTheme.ts @@ -1,16 +1,8 @@ -// Which theme a sky state lights the page with. 'auto' picks none: it never overrides a person's theme -// (the stored one when signed in, Midnight Sky when signed out). A wiring that follows the sky when no theme -// is stored reads `getResolvedSkyState` (skyState.ts) and passes that fixed state here. -// -// Day and Dusk take the dark ink of Noonday Sky, Night the light ink of Midnight Sky. Each state's -// drawn sky is shaped into a luminance band (skyBand.ts) in which that ink's TEXT clears 4.5:1 on -// bare sky: Day at least 0.2983 (dark ink), Night at most 0.0931 (light ink). Dusk's floor is higher, the bound of -// the dark link (0.4554), so its link clears as well. skyTheme.test.ts pins the measured text and link ratios. Night's -// link ink is not in the band, and the themes' link colours are derived outside this code (src/sky/skyTokens.js). -// Midnight Sky's link is derived there against the lightest Night sky -// (4.53 on it, 5.43 on the darkest). The plate (skyPlate.css.ts) is still in the shell, pending -// its removal. -import type { FixedSkyState, SkyState } from './skyState'; +// Which theme the drawn sky lights the page with. While a scene is on, the sky being drawn (the +// scene that is up draws; `useDrawnSky`) 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 +// drawn, that is with the scene off. +import type { FixedSkyState } from './ridge/skyMoment'; export type SkyThemeId = 'midnight-sky' | 'noonday-sky'; @@ -20,21 +12,8 @@ const BY_STATE: Record = { night: 'midnight-sky', }; -export const skyThemeId = (state: SkyState): SkyThemeId | undefined => - state === 'auto' ? undefined : BY_STATE[state]; - -/** - * The theme the page wears: a theme the person chose always wins, and picks none here. Otherwise a fixed sky state - * picks its theme, and 'auto' follows the resolved sky (`resolved`, the clock's state) only while a scene is on. - * Signed-out pages choose no theme, so they pass `userChoseTheme: false`. - */ +/** The theme the page wears: the drawn sky's while a scene is on, otherwise none (the person's theme stands). */ export const sceneThemeId = ( - state: SkyState, - resolved: FixedSkyState, - sceneOn: boolean, - userChoseTheme: boolean -): SkyThemeId | undefined => { - if (userChoseTheme) return undefined; - if (state !== 'auto') return BY_STATE[state]; - return sceneOn ? BY_STATE[resolved] : undefined; -}; + resolved: FixedSkyState | undefined, + sceneOn: boolean +): SkyThemeId | undefined => (sceneOn && resolved ? BY_STATE[resolved] : undefined); diff --git a/src/app/features/scene/standardTime.testkit.ts b/src/app/features/scene/standardTime.testkit.ts deleted file mode 100644 index a6966238..00000000 --- a/src/app/features/scene/standardTime.testkit.ts +++ /dev/null @@ -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); -}; diff --git a/src/app/features/scene/terrain/Terrain.test.ts b/src/app/features/scene/terrain/Terrain.test.ts deleted file mode 100644 index ef1623c4..00000000 --- a/src/app/features/scene/terrain/Terrain.test.ts +++ /dev/null @@ -1,385 +0,0 @@ -/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion, @typescript-eslint/no-empty-function -- fake GL and DOM stubs, as the other scene tests */ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { createTerrainScene } from './Terrain'; -import { GRID, triangleCount } from './terrainWorld'; -import { groundLight, SKY, skyAtSun } from './terrainSky'; -import { AP_VOLUME, apVolumeWords, SKY_VIEW, skyViewWords } from './terrainScatter'; -import { SKY_FRAG } from './terrainShaders'; -import { SKY_BAND } from '../skyBand'; -import { terrainSkyFor } from '../skyForState'; -import { startBackgroundScene } from '../index'; - -/** A GL context that accepts every call, remembers them, reports success for compile, link and framebuffer. */ -function fakeGl(over: Record = {}) { - const calls: Record = {}; - const gl: any = new Proxy( - {}, - { - get(_t, name: string) { - if (name in over) return over[name]; - if (name === 'getShaderParameter' || name === 'getProgramParameter') return () => true; - if (name === 'getAttribLocation' || name === 'getUniformLocation') return () => 1; - if (name === 'checkFramebufferStatus') return () => 1; - if (name === 'getParameter') return () => 16; - if (/^[A-Z_0-9]+$/.test(name)) return 1; - return (...args: unknown[]) => { - (calls[name] ??= []).push(args); - return {}; - }; - }, - } - ); - return { gl, calls }; -} - -let rafQueue: Array<(t: number) => void>; -let visibility: string; -let search: string; -beforeEach(() => { - rafQueue = []; - visibility = 'visible'; - search = ''; - vi.stubGlobal('document', { - addEventListener: vi.fn(), - removeEventListener: vi.fn(), - get visibilityState() { - return visibility; - }, - createElement: () => ({ style: {}, remove() {} }), - }); - vi.stubGlobal('window', { - devicePixelRatio: 1, - innerWidth: 400, - innerHeight: 800, - matchMedia: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }), - addEventListener: vi.fn(), - removeEventListener: vi.fn(), - get location() { - return { search }; - }, - setTimeout, - }); - vi.stubGlobal('performance', { now: () => 0 }); - vi.stubGlobal('requestAnimationFrame', (cb: (t: number) => void) => rafQueue.push(cb)); - vi.stubGlobal('cancelAnimationFrame', () => { - rafQueue = []; - }); -}); -afterEach(() => { - vi.unstubAllGlobals(); -}); - -function canvasWith(gl: unknown) { - return { - width: 0, - height: 0, - clientWidth: 400, - clientHeight: 800, - parentElement: { appendChild: vi.fn() }, - getContext: vi.fn(() => gl), - addEventListener: vi.fn(), - removeEventListener: vi.fn(), - } as any; -} - -describe('createTerrainScene', () => { - it("returns null at tier 'off' and touches nothing", () => { - const canvas = canvasWith(null); - expect(createTerrainScene({ canvas, tier: 'off' })).toBeNull(); - expect(canvas.getContext).not.toHaveBeenCalled(); - }); - - it('returns null without WebGL2, so the host keeps its CSS ground', () => { - const canvas = canvasWith(null); - expect(createTerrainScene({ canvas, tier: 'full' })).toBeNull(); - expect(canvas.getContext).toHaveBeenCalledWith('webgl2', expect.anything()); - }); - - it('returns null with no vertex texture units, or an incomplete bake target', () => { - expect( - createTerrainScene({ canvas: canvasWith(fakeGl({ getParameter: () => 0 }).gl), tier: 'full' }) - ).toBeNull(); - const { gl, calls } = fakeGl({ checkFramebufferStatus: () => 0 }); - expect(createTerrainScene({ canvas: canvasWith(gl), tier: 'full' })).toBeNull(); - expect(calls.deleteProgram).toHaveLength(3); - }); - - it('reports a shader that does not compile to onCompileFail and returns null', () => { - const { gl } = fakeGl({ getShaderParameter: () => false, getShaderInfoLog: () => 'bad' }); - const onCompileFail = vi.fn(); - expect(createTerrainScene({ canvas: canvasWith(gl), tier: 'full', onCompileFail })).toBeNull(); - expect(onCompileFail).toHaveBeenCalledOnce(); - expect(onCompileFail.mock.calls[0][0].log).toContain('terrain height'); - }); - - it('bakes the height map once, then draws sky and grid each frame and keeps turning', () => { - const { gl, calls } = fakeGl(); - const scene = createTerrainScene({ canvas: canvasWith(gl), tier: 'low' })!; - expect(scene).not.toBeNull(); - const bakes = calls.drawArrays.length; - expect(bakes).toBe(1); - rafQueue.shift()!(16); - rafQueue.shift()!(32); - expect(calls.drawArrays).toHaveLength(bakes + 2); // one sky draw per frame - expect(calls.drawElements).toHaveLength(2); - expect(calls.drawElements[0][1]).toBe(triangleCount(GRID.low.grid) * 3); - expect(calls.texImage2D).toHaveLength(1); // the baked map is never re-uploaded - expect(rafQueue).toHaveLength(1); - scene.dispose(); - }); - - it("'still' draws one frame and queues nothing", () => { - const { gl, calls } = fakeGl(); - const scene = createTerrainScene({ canvas: canvasWith(gl), tier: 'still' })!; - expect(calls.drawElements).toHaveLength(1); - expect(rafQueue).toHaveLength(0); - scene.dispose(); - }); - - it('lights with the sky chosen: option, then ?sky=, then the night default', () => { - const uploaded = (opts: { sky?: 'midnight' | 'noonday' }) => { - const { gl, calls } = fakeGl(); - createTerrainScene({ canvas: canvasWith(gl), tier: 'still', ...opts })!.dispose(); - // every vec3 uniform draw() sets: right, up, forward, sun, sunColour, glow, ambient, camera, soil... - return calls.uniform3fv - .filter((a) => (a[1] as ArrayLike).length === 3) - .map((a) => Array.from(a[1] as ArrayLike)); - }; - const night = uploaded({}); - const day = uploaded({ sky: 'noonday' }); - const nightA = Array.from(groundLight(SKY.midnight).ambient); - const dayA = Array.from(groundLight(SKY.noonday).ambient); - const has = (all: number[][], v: number[]) => - all.some((a) => a.every((x, i) => Math.abs(x - v[i]) < 1e-6)); - expect(has(night, nightA)).toBe(true); - expect(has(night, dayA)).toBe(false); - expect(has(day, dayA)).toBe(true); - search = '?sky=noonday'; - expect(has(uploaded({}), dayA)).toBe(true); - search = '?sky=garbage'; - expect(has(uploaded({}), nightA)).toBe(true); - }); - - it.each(['day', 'dusk', 'night'] as const)( - 'uploads the %s band as uBand (floor, ceiling) and uLift, in the sky pass and the grid pass', - (state) => { - const { gl, calls } = fakeGl(); - const opts = terrainSkyFor(state); - createTerrainScene({ canvas: canvasWith(gl), tier: 'still', ...opts })!.dispose(); - const { floor, ceiling, lift } = SKY_BAND[state]; - const pairs = calls.uniform2fv.filter( - (a) => - Math.abs((a[1] as number[])[0] - floor) < 1e-6 && - Math.abs((a[1] as number[])[1] - ceiling) < 1e-6 - ); - expect(pairs).toHaveLength(2); - const lifts = calls.uniform3fv.filter((a) => - Array.from(a[1] as ArrayLike).every((x, i) => Math.abs(x - lift[i]) < 1e-6) - ); - expect(lifts).toHaveLength(2); - } - ); - - it('uploads no band (0, 1) and a zero lift without one', () => { - const { gl, calls } = fakeGl(); - createTerrainScene({ canvas: canvasWith(gl), tier: 'still' })!.dispose(); - expect(calls.uniform2fv.filter((a) => (a[1] as number[])[1] === 1)).toHaveLength(2); - }); - - it('a sun elevation (option or ?sun=&az=) lights between the bakes, and wins over ?sky=', () => { - const ambients = (opts: Record) => { - const { gl, calls } = fakeGl(); - createTerrainScene({ canvas: canvasWith(gl), tier: 'still', ...opts })!.dispose(); - return calls.uniform3fv.map((a) => Array.from(a[1] as ArrayLike)); - }; - const dusk = skyAtSun(-1, 300); - const has = (all: number[][], v: readonly number[]) => - all.some((a) => a.length === 3 && a.every((x, i) => Math.abs(x - v[i]) < 1e-6)); - expect(has(ambients({ sun: { elevation: -1, azimuth: 300 } }), groundLight(dusk).ambient)).toBe( - true - ); - search = '?sky=noonday&sun=-1&az=300'; - expect(has(ambients({}), groundLight(dusk).ambient)).toBe(true); - search = '?sun=garbage'; - expect(has(ambients({}), groundLight(SKY.midnight).ambient)).toBe(true); - }); - - it('uploads the baked sky table and the aerial perspective volume once each, as half floats, to 3D textures', () => { - const { gl, calls } = fakeGl(); - createTerrainScene({ canvas: canvasWith(gl), tier: 'full' })!.dispose(); - expect(calls.texImage3D).toHaveLength(2); - const a = calls.texImage3D[0]; - expect([a[3], a[4], a[5]]).toEqual([SKY_VIEW.width, SKY_VIEW.height, SKY_VIEW.depth]); - expect(a[9]).toEqual(skyViewWords()); - const ap = calls.texImage3D[1]; - expect([ap[3], ap[4], ap[5]]).toEqual([AP_VOLUME.width, AP_VOLUME.height, AP_VOLUME.depth]); - expect(ap[9]).toEqual(apVolumeWords()); - expect(calls.deleteTexture).toHaveLength(3); - }); - - it('dithers the sky output by half an 8-bit step either way, and the terrain not at all', () => { - expect(SKY_FRAG).toContain('- 0.5'); - expect(SKY_FRAG).toContain('dither / 255.0'); - }); - - it('falls back to a still frame when the measured p95 is over 33 ms', () => { - const { gl, calls } = fakeGl(); - const onProbe = vi.fn(); - const scene = createTerrainScene({ canvas: canvasWith(gl), tier: 'full', onProbe })!; - let t = 0; - for (let i = 0; i < 400 && rafQueue.length; i += 1) rafQueue.shift()!((t += 50)); - expect(rafQueue).toHaveLength(0); - expect(onProbe).toHaveBeenLastCalledWith(expect.objectContaining({ still: true })); - expect(calls.drawElements.length).toBeLessThan(400); - scene.dispose(); - }); - - it('does not draw while the tab is hidden, or under reduced motion', () => { - const { gl, calls } = fakeGl(); - const scene = createTerrainScene({ canvas: canvasWith(gl), tier: 'full' })!; - const before = (calls.drawElements ?? []).length; - visibility = 'hidden'; - rafQueue.shift()!(16); - expect((calls.drawElements ?? []).length).toBe(before); - scene.dispose(); - vi.stubGlobal('window', { - ...(window as object), - matchMedia: () => ({ matches: true, addEventListener() {}, removeEventListener() {} }), - }); - visibility = 'visible'; - const g2 = fakeGl(); - const still = createTerrainScene({ canvas: canvasWith(g2.gl), tier: 'full' })!; - expect(rafQueue).toHaveLength(0); - expect(g2.calls.drawElements).toHaveLength(1); // one frame, then still - still.dispose(); - }); - - it('a lost context stops the scene and tells the host', () => { - const { gl, calls } = fakeGl(); - const canvas = canvasWith(gl); - const onContextLost = vi.fn(); - createTerrainScene({ canvas, tier: 'full', onContextLost })!; - const handler = canvas.addEventListener.mock.calls.find( - (c: unknown[]) => c[0] === 'webglcontextlost' - )[1]; - handler({ preventDefault() {} }); - expect(onContextLost).toHaveBeenCalledOnce(); - const n = (calls.drawElements ?? []).length; - rafQueue.splice(0).forEach((f) => f(16)); - expect((calls.drawElements ?? []).length).toBe(n); - }); - - it('dispose frees its programs, buffers and texture and queues nothing more', () => { - const { gl, calls } = fakeGl(); - createTerrainScene({ canvas: canvasWith(gl), tier: 'full' })!.dispose(); - expect(calls.deleteProgram).toHaveLength(3); - expect(calls.deleteBuffer).toHaveLength(2); - expect(calls.deleteTexture).toHaveLength(3); - expect(rafQueue).toHaveLength(0); - }); -}); - -describe("startBackgroundScene style 'terrain'", () => { - it('requests webgl2 and returns a scene once the tier is on', async () => { - const { gl } = fakeGl(); - const canvas = canvasWith(gl); - const scene = await startBackgroundScene({ tier: 'still', style: 'terrain' }, {}, { canvas }); - expect(scene).not.toBeNull(); - expect(canvas.getContext).toHaveBeenCalledWith('webgl2', expect.anything()); - scene!.dispose(); - }); - - it('stays off by default, and the default style is still the ridge (no WebGL2)', async () => { - const canvas = canvasWith(null); - expect(await startBackgroundScene({ style: 'terrain' }, {}, { canvas })).toBeNull(); - expect(canvas.getContext).not.toHaveBeenCalled(); - const { gl } = fakeGl(); - const c2 = { ...canvasWith(gl), getContext: vi.fn(() => null) }; - await startBackgroundScene({ tier: 'still' }, {}, { canvas: c2 }); - expect(c2.getContext).not.toHaveBeenCalledWith('webgl2', expect.anything()); - }); -}); - -describe('stars in the terrain scene', () => { - let overlays: any[]; - let arcs: number; - const withOverlays = () => { - overlays = []; - arcs = 0; - (document as any).createElement = () => { - const el: any = { - style: {}, - remove: vi.fn(), - setAttribute() {}, - getContext: () => ({ - clearRect() {}, - beginPath() {}, - fill() {}, - arc: () => (arcs += 1), - }), - }; - overlays.push(el); - return el; - }; - }; - const scene = (sky: 'midnight' | 'noonday', tier: 'still' | 'low' = 'low') => { - withOverlays(); - const canvas = canvasWith(fakeGl().gl); - const s = createTerrainScene({ canvas, tier, sky })!; - return { s, canvas }; - }; - - it('a midnight sky gets one star overlay beside the canvas, painted with the terrain', () => { - const { s, canvas } = scene('midnight'); - expect(overlays).toHaveLength(1); - expect(canvas.parentElement.appendChild).toHaveBeenCalledWith(overlays[0]); - rafQueue.shift()!(16); - expect(arcs).toBeGreaterThan(0); - s.dispose(); - expect(overlays[0].remove).toHaveBeenCalledOnce(); - }); - - it('a noonday sky gets no overlay and paints no stars', () => { - const { s } = scene('noonday'); - expect(overlays).toHaveLength(0); - expect(arcs).toBe(0); - s.dispose(); - }); - - it("'still' paints the stars once at base and queues nothing", () => { - const { s } = scene('midnight', 'still'); - expect(arcs).toBeGreaterThan(0); - expect(rafQueue).toHaveLength(0); - s.dispose(); - }); - - it('a hidden tab or reduced motion paints no more stars than the first frame', () => { - visibility = 'hidden'; - const { s } = scene('midnight'); - const n = arcs; - expect(n).toBeGreaterThan(0); - expect(rafQueue).toHaveLength(0); // the terrain loop never starts, so nothing repaints the stars - s.dispose(); - visibility = 'visible'; - (window as any).matchMedia = () => ({ - matches: true, - addEventListener() {}, - removeEventListener() {}, - }); - const r = scene('midnight'); - expect(rafQueue).toHaveLength(0); - expect(arcs).toBe(n); - r.s.dispose(); - }); - - it('stars turn with the terrain: a later frame is painted at a later heading', () => { - let clock = 0; - vi.stubGlobal('performance', { now: () => (clock += 1000) }); - const { s } = scene('midnight'); - rafQueue.shift()!(16); - const first = arcs; - rafQueue.shift()!(1000); - expect(arcs).toBeGreaterThan(first); - s.dispose(); - }); -}); diff --git a/src/app/features/scene/terrain/Terrain.ts b/src/app/features/scene/terrain/Terrain.ts deleted file mode 100644 index a1807305..00000000 --- a/src/app/features/scene/terrain/Terrain.ts +++ /dev/null @@ -1,443 +0,0 @@ -import type { Scene, SceneOptions } from '../Scene'; -import type { SkyBand } from '../skyBand'; -import { FrameSampler, FrameStats } from '../ridge/probe'; -import { albedoPalette } from './terrainAlbedo'; -import { sunIndex } from '../../../../sky/scatter.js'; -import { AP_VOLUME, apVolumeWords, SKY_VIEW, skyViewWords } from './terrainScatter'; -import { - nightness, - glowColour, - groundLight, - chooseSky, - SkyName, - START_TURNS, - sunDirection, -} from './terrainSky'; -import { buildGrid, CAMERA, GRID, seedOffset, TERRAIN, triangleCount, view } from './terrainWorld'; -import { - FULLSCREEN_VERT, - GRID_FRAG, - GRID_VERT, - heightFragmentSource, - SKY_FRAG, -} from './terrainShaders'; -import { createTerrainStars } from './terrainStars'; -import { overlayRequested } from '../debugOverlays'; -import { showTierLabel } from './tierLabel'; - -export type TerrainOptions = Pick< - SceneOptions, - 'canvas' | 'tier' | 'onCompileFail' | 'onContextLost' -> & { - /** Which baked sky lights and hazes the terrain. Default: `?sky=` in the page URL, else midnight. */ - sky?: SkyName; - /** Put the sun at this elevation (degrees) and azimuth (clockwise from north; default: noonday's) instead of at the baked sky's: `?sun=` and `?az=` in the page URL. Lights between the two bakes, for dusk. */ - sun?: { elevation: number; azimuth?: number }; - /** The luminance band the sky is shaped into (skyBand.ts), in the sky pass and in the haze that fades into it. Default: none. */ - band?: SkyBand; - /** Terrain seed: the height map is sampled at an offset taken from it. Default 0. */ - seed?: number; - /** Show the rAF median/p95 readout (plus triangle count). Default: the page URL has `?probe=1`, where `debug` allows it. */ - probe?: boolean; - /** The diagnostic overlays (readout, tier label) may be asked for by URL (debugOverlays.ts). Default: no. */ - debug?: boolean; - onProbe?: (s: FrameStats & { still: boolean; triangles: number }) => void; -}; - -/** Same shape as Scene.ts's ShaderCompileError, redeclared so this chunk does not import the ray-march scene. */ -class ShaderCompileError extends Error { - constructor(readonly stage: 'vertex', readonly log: string) { - super(`${stage} shader failed to compile:\n${log}`); - } -} - -function program(gl: WebGL2RenderingContext, name: string, vs: string, fs: string): WebGLProgram { - const make = (type: number, src: string, which: string) => { - const s = gl.createShader(type); - if (!s) throw new Error('createShader failed'); - gl.shaderSource(s, src); - gl.compileShader(s); - if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) { - const log = gl.getShaderInfoLog(s) ?? ''; - gl.deleteShader(s); - throw new ShaderCompileError('vertex', `terrain ${name} ${which} shader: ${log}`); - } - return s; - }; - const v = make(gl.VERTEX_SHADER, vs, 'vertex'); - const f = make(gl.FRAGMENT_SHADER, fs, 'fragment'); - const p = gl.createProgram(); - if (!p) throw new Error('createProgram failed'); - gl.attachShader(p, v); - gl.attachShader(p, f); - gl.linkProgram(p); - gl.deleteShader(v); - gl.deleteShader(f); - if (!gl.getProgramParameter(p, gl.LINK_STATUS)) { - const log = gl.getProgramInfoLog(p) ?? ''; - gl.deleteProgram(p); - throw new ShaderCompileError('vertex', `terrain ${name} link: ${log}`); - } - return p; -} - -/** - * The terrain scene: same contract as `createRidgeScene`/`createScene` ({ login, dispose }, null for "keep the - * CSS ground"). WebGL2 only. The height map is baked once on the GPU (Phacelle, see terrainShaders.ts) into an - * RGBA8 texture; each frame is two draws: the sky from the baked scattering table, then a displaced grid lit by the - * baked sun and ambient and hazed toward that sky at the horizon. Cadence guard, pauses and the `?probe=1` readout match the - * ridge scene. - */ -export function createTerrainScene(opts: TerrainOptions): Scene | null { - const tier = opts.tier ?? 'full'; - if (tier === 'off') return null; - const { canvas } = opts; - const probe = opts.probe ?? overlayRequested('probe', opts.debug === true); - const gl = canvas.getContext('webgl2', { - antialias: false, - alpha: false, - }) as WebGL2RenderingContext | null; - if (!gl) return null; - const units = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS); - if (typeof units === 'number' && units < 1) return null; - - const sky = chooseSky(opts); - const spec = GRID[tier]; - - let skyProg: WebGLProgram; - let gridProg: WebGLProgram; - let bakeProg: WebGLProgram; - try { - bakeProg = program(gl, 'height', FULLSCREEN_VERT, heightFragmentSource()); - skyProg = program(gl, 'sky', FULLSCREEN_VERT, SKY_FRAG); - gridProg = program(gl, 'grid', GRID_VERT, GRID_FRAG); - } catch (e) { - opts.onCompileFail?.(e as ShaderCompileError); - return null; - } - - // The height map, baked once. - const heightTex = gl.createTexture(); - const fbo = gl.createFramebuffer(); - gl.bindTexture(gl.TEXTURE_2D, heightTex); - gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, spec.tex, spec.tex, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); - // The baked scattering table, RGB16F, uploaded as it is stored (half floats); the shader divides by the store scale. - const skyTex = gl.createTexture(); - gl.bindTexture(gl.TEXTURE_3D, skyTex); - gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1); - gl.texImage3D( - gl.TEXTURE_3D, - 0, - gl.RGB16F, - SKY_VIEW.width, - SKY_VIEW.height, - SKY_VIEW.depth, - 0, - gl.RGB, - gl.HALF_FLOAT, - skyViewWords() - ); - gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); - [gl.TEXTURE_WRAP_S, gl.TEXTURE_WRAP_T, gl.TEXTURE_WRAP_R].forEach((w) => - gl.texParameteri(gl.TEXTURE_3D, w, gl.CLAMP_TO_EDGE) - ); - // The aerial perspective volume, RGBA16F, half floats as stored (src/sky/scatter.js). - const apTex = gl.createTexture(); - gl.bindTexture(gl.TEXTURE_3D, apTex); - gl.texImage3D( - gl.TEXTURE_3D, - 0, - gl.RGBA16F, - AP_VOLUME.width, - AP_VOLUME.height, - AP_VOLUME.depth, - 0, - gl.RGBA, - gl.HALF_FLOAT, - apVolumeWords() - ); - gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); - [gl.TEXTURE_WRAP_S, gl.TEXTURE_WRAP_T, gl.TEXTURE_WRAP_R].forEach((w) => - gl.texParameteri(gl.TEXTURE_3D, w, gl.CLAMP_TO_EDGE) - ); - gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4); - gl.bindTexture(gl.TEXTURE_2D, heightTex); - gl.bindFramebuffer(gl.FRAMEBUFFER, fbo); - gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, heightTex, 0); - const complete = gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE; - const free: Array<() => void> = []; - const release = () => { - free.forEach((f) => f()); - gl.deleteTexture(heightTex); - gl.deleteTexture(skyTex); - gl.deleteTexture(apTex); - gl.deleteFramebuffer(fbo); - gl.deleteProgram(bakeProg); - gl.deleteProgram(skyProg); - gl.deleteProgram(gridProg); - }; - if (!complete) { - release(); - return null; - } - gl.viewport(0, 0, spec.tex, spec.tex); - gl.disable(gl.DEPTH_TEST); - gl.useProgram(bakeProg); - gl.uniform1f(gl.getUniformLocation(bakeProg, 'uSpan'), TERRAIN.span); - gl.uniform1f(gl.getUniformLocation(bakeProg, 'uTexels'), spec.tex); - gl.uniform2fv(gl.getUniformLocation(bakeProg, 'uSeed'), seedOffset(opts.seed ?? 0)); - gl.drawArrays(gl.TRIANGLES, 0, 3); - gl.bindFramebuffer(gl.FRAMEBUFFER, null); - - // The displaced grid. - const g = buildGrid(spec.grid); - const vao = gl.createVertexArray(); - const vbuf = gl.createBuffer(); - const ibuf = gl.createBuffer(); - gl.bindVertexArray(vao); - gl.bindBuffer(gl.ARRAY_BUFFER, vbuf); - gl.bufferData(gl.ARRAY_BUFFER, g.uv, gl.STATIC_DRAW); - gl.enableVertexAttribArray(0); - gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0); - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ibuf); - gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, g.indices, gl.STATIC_DRAW); - gl.bindVertexArray(null); - free.push( - () => gl.deleteVertexArray(vao), - () => gl.deleteBuffer(vbuf), - () => gl.deleteBuffer(ibuf) - ); - - const sun = [...sunDirection(sky)]; - const sunLight = [...sky.direct]; - const ground = groundLight(sky); - const ambient = [...ground.ambient]; - const heading = START_TURNS; - const glow = [...glowColour(sky)]; - const band: [number, number] = sky.band ? [sky.band.floor, sky.band.ceiling] : [0, 1]; - const lift = [...(sky.band?.lift ?? [0, 0, 0])]; - const sunTexel = sunIndex(sky.elevation); - const night = nightness(sky.elevation); - const moonTexel = sunIndex(Math.abs(sky.elevation)); - const palette = albedoPalette(sky); - const triangles = triangleCount(spec.grid); - - const stars = createTerrainStars(canvas, sky); - const reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)'); - const sampler = new FrameSampler(); - let still = tier === 'still'; - let disposed = false; - let lost = false; - let raf = 0; - let readout: HTMLElement | undefined; - let resizeTimer = 0; - let turnsAtPause = 0; - let playedFrom: number | undefined; - - /** Size the canvas: low renders at 0.75 of the CSS size; full at device pixel ratio capped to 2. */ - const size = () => { - const dpr = Math.min(window.devicePixelRatio || 1, 2) * (tier === 'low' ? 0.75 : 1); - canvas.width = Math.max(1, Math.round((canvas.clientWidth || window.innerWidth) * dpr)); - canvas.height = Math.max(1, Math.round((canvas.clientHeight || window.innerHeight) * dpr)); - }; - - const draw = (turns: number) => { - if (lost) return; - gl.viewport(0, 0, canvas.width, canvas.height); - const v = view(canvas.width / canvas.height, (turns + heading) % 1); - gl.disable(gl.DEPTH_TEST); - gl.useProgram(skyProg); - const us = (n: string) => gl.getUniformLocation(skyProg, n); - gl.uniform3fv(us('uSun'), sun); - gl.uniform3fv(us('uSunColour'), sunLight); - gl.uniform3fv(us('uGlow'), glow); - gl.uniform2fv(us('uBand'), band); - gl.uniform3fv(us('uLift'), lift); - gl.uniform1f(us('uSunIndex'), sunTexel); - gl.activeTexture(gl.TEXTURE1); - gl.bindTexture(gl.TEXTURE_3D, skyTex); - gl.uniform1i(us('uSky'), 1); - gl.uniform3fv(us('uRight'), v.right); - gl.uniform3fv(us('uUp'), v.up); - gl.uniform3fv(us('uForward'), v.forward); - gl.uniform2f(us('uSize'), canvas.width, canvas.height); - gl.uniform1f(us('uTanHalf'), Math.tan(CAMERA.fov / 2)); - gl.drawArrays(gl.TRIANGLES, 0, 3); - - gl.enable(gl.DEPTH_TEST); - gl.clear(gl.DEPTH_BUFFER_BIT); - gl.useProgram(gridProg); - const u = (n: string) => gl.getUniformLocation(gridProg, n); - gl.uniformMatrix4fv(u('uViewProj'), false, v.viewProj); - gl.uniform3fv(u('uCamera'), v.eye); - gl.uniform1f(u('uSpan'), TERRAIN.span); - gl.uniform1i(u('uTex'), spec.tex); - gl.uniform3fv(u('uSun'), sun); - gl.uniform3fv(u('uLightDir'), ground.dir); - gl.uniform3fv(u('uLight'), ground.colour); - gl.uniform3fv(u('uAmbient'), ambient); - gl.uniform3fv(u('uGlow'), glow); - gl.uniform2fv(u('uBand'), band); - gl.uniform3fv(u('uLift'), lift); - gl.uniform1f(u('uSunIndex'), sunTexel); - gl.activeTexture(gl.TEXTURE1); - gl.bindTexture(gl.TEXTURE_3D, skyTex); - gl.uniform1i(u('uSky'), 1); - gl.uniform1f(u('uNight'), night); - gl.uniform1f(u('uMoonIndex'), moonTexel); - gl.activeTexture(gl.TEXTURE2); - gl.bindTexture(gl.TEXTURE_3D, apTex); - gl.uniform1i(u('uAP'), 2); - gl.uniform3fv(u('uSoil'), palette.soil); - gl.uniform3fv(u('uScree'), palette.scree); - gl.uniform3fv(u('uRock'), palette.rock); - gl.uniform3fv(u('uSnow'), palette.snow); - gl.uniform1f(u('uSnowLine'), palette.snowLine); - gl.activeTexture(gl.TEXTURE0); - gl.bindTexture(gl.TEXTURE_2D, heightTex); - gl.uniform1i(u('uHeight'), 0); - gl.bindVertexArray(vao); - gl.drawElements(gl.TRIANGLES, g.indices.length, gl.UNSIGNED_INT, 0); - gl.bindVertexArray(null); - stars?.draw((turns + heading) % 1, moving() ? performance.now() / 1000 : undefined); - }; - - const moving = () => - !still && - !disposed && - !lost && - !(reducedMotion?.matches ?? false) && - document.visibilityState === 'visible'; - - const turnsNow = (now: number) => - turnsAtPause + (playedFrom === undefined ? 0 : (now - playedFrom) / (CAMERA.seconds * 1000)); - - const report = (stillNow: boolean) => { - const s = { ...sampler.stats(), still: stillNow, triangles }; - opts.onProbe?.(s); - if (readout) { - readout.textContent = `terrain · ${s.triangles} tris · n ${s.n} · median ${s.medianMs.toFixed( - 1 - )} ms · p95 ${s.p95Ms.toFixed(1)} ms${stillNow ? ' · STILL' : ''}`; - } - }; - - const settleToStill = () => { - if (playedFrom !== undefined) turnsAtPause = turnsNow(performance.now()); - playedFrom = undefined; - still = true; - cancelAnimationFrame(raf); - raf = 0; - draw(turnsAtPause); - report(true); - }; - - let sinceReport = 0; - // The first window is measured (guard against a slow device); after it the loop only draws. - let measuring = true; - const frame = (now: number) => { - raf = 0; - if (!moving()) return; - draw(turnsNow(now)); - if (!measuring) { - raf = requestAnimationFrame(frame); - return; - } - const full = sampler.push(now); - if (full) { - measuring = false; - if (sampler.slow()) { - settleToStill(); - return; - } - if (probe) report(false); - } else if (probe && now - sinceReport > 500) { - sinceReport = now; - report(false); - } - raf = requestAnimationFrame(frame); - }; - const wake = () => { - if (!moving()) { - if (playedFrom !== undefined) turnsAtPause = turnsNow(performance.now()); - playedFrom = undefined; - return; - } - if (raf) return; - playedFrom = performance.now(); - if (measuring) sampler.reset(); - raf = requestAnimationFrame(frame); - }; - - const onLost = (e: Event) => { - e.preventDefault(); - lost = true; - cancelAnimationFrame(raf); - raf = 0; - opts.onContextLost?.(); - }; - canvas.addEventListener('webglcontextlost', onLost); - - size(); - if (probe && canvas.parentElement) { - readout = document.createElement('div'); - Object.assign(readout.style, { - position: 'absolute', - left: '8px', - top: '8px', - font: '12px monospace', - color: '#fff', - background: 'rgba(0,0,0,.55)', - padding: '2px 6px', - borderRadius: '3px', - pointerEvents: 'none', - }); - canvas.parentElement.appendChild(readout); - } - const removeLabel = showTierLabel(canvas, tier, opts.debug === true); - if (still) settleToStill(); - else wake(); - if (!still && !moving()) draw(0); - - const onVisibility = () => { - sampler.reset(); - wake(); - }; - const onResize = () => { - clearTimeout(resizeTimer); - resizeTimer = window.setTimeout(() => { - if (disposed || lost) return; - size(); - stars?.resize(); - draw(turnsNow(performance.now())); - sampler.reset(); - }, 250); - }; - document.addEventListener('visibilitychange', onVisibility); - window.addEventListener('resize', onResize); - reducedMotion?.addEventListener?.('change', onVisibility); - - return { - login() { - // The camera is the same before and after. - }, - dispose() { - if (disposed) return; - disposed = true; - cancelAnimationFrame(raf); - clearTimeout(resizeTimer); - document.removeEventListener('visibilitychange', onVisibility); - window.removeEventListener('resize', onResize); - reducedMotion?.removeEventListener?.('change', onVisibility); - canvas.removeEventListener('webglcontextlost', onLost); - readout?.remove(); - removeLabel?.(); - stars?.dispose(); - release(); - }, - }; -} diff --git a/src/app/features/scene/terrain/TerrainSky2D.test.ts b/src/app/features/scene/terrain/TerrainSky2D.test.ts deleted file mode 100644 index d85d8f01..00000000 --- a/src/app/features/scene/terrain/TerrainSky2D.test.ts +++ /dev/null @@ -1,286 +0,0 @@ -/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-empty-function -- DOM stubs, as the other scene tests */ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { createTerrainSkyScene, SKY_WIDTH } from './TerrainSky2D'; -import { startBackgroundScene } from '../index'; -import { terrainSkyFor } from '../skyForState'; - -let search: string; -let arcs: number; -let overlay: { remove: ReturnType }; -let windowListeners: Record void>; -beforeEach(() => { - search = ''; - arcs = 0; - windowListeners = {}; - vi.stubGlobal('document', { - createElement: () => { - overlay = { - remove: vi.fn(), - style: {}, - setAttribute() {}, - getContext: () => ({ - clearRect() {}, - beginPath() {}, - fill() {}, - arc: () => { - arcs += 1; - }, - }), - } as any; - return overlay; - }, - }); - vi.stubGlobal('window', { - devicePixelRatio: 1, - innerWidth: 400, - innerHeight: 800, - addEventListener: (n: string, f: () => void) => { - windowListeners[n] = f; - }, - removeEventListener: (n: string) => { - delete windowListeners[n]; - }, - get location() { - return { search }; - }, - setTimeout, - }); -}); -afterEach(() => { - vi.unstubAllGlobals(); -}); - -/** A canvas with a recording 2D context; `gl` is what 'webgl2' answers. */ -function canvasWith(opts: { twoD?: boolean; gl?: unknown } = {}) { - const painted: { data: Uint8ClampedArray; width: number; height: number }[] = []; - const ctx = { - createImageData: (width: number, height: number) => ({ - width, - height, - data: new Uint8ClampedArray(width * height * 4), - }), - putImageData: (image: any) => painted.push(image), - }; - const parentAppend = vi.fn(); - const canvas: any = { - width: 0, - height: 0, - clientWidth: 400, - clientHeight: 800, - parentElement: { appendChild: parentAppend }, - getContext: vi.fn((kind: string) => { - if (kind !== '2d') return opts.gl ?? null; - return opts.twoD === false ? null : ctx; - }), - addEventListener: vi.fn(), - removeEventListener: vi.fn(), - }; - return { canvas, painted, parentAppend }; -} - -const pixel = (img: { data: Uint8ClampedArray; width: number }, x: number, y: number) => - Array.from(img.data.slice((y * img.width + x) * 4, (y * img.width + x) * 4 + 3)); -const mean = (img: { data: Uint8ClampedArray }) => { - let s = 0; - for (let i = 0; i < img.data.length; i += 4) s += img.data[i] + img.data[i + 1] + img.data[i + 2]; - return s / (img.data.length / 4) / 3; -}; - -describe('createTerrainSkyScene', () => { - it("returns null at tier 'off' and touches nothing", () => { - const { canvas } = canvasWith(); - expect(createTerrainSkyScene({ canvas, tier: 'off' })).toBeNull(); - expect(canvas.getContext).not.toHaveBeenCalled(); - }); - - it('returns null when the canvas gives no 2D context (the CSS ground stays)', () => { - const { canvas } = canvasWith({ twoD: false }); - expect(createTerrainSkyScene({ canvas, tier: 'low' })).toBeNull(); - }); - - it('paints one opaque, graded sky: the horizon end of the image is not the zenith end', () => { - const { canvas, painted } = canvasWith(); - const s = createTerrainSkyScene({ canvas, tier: 'low', sky: 'noonday' })!; - expect(painted).toHaveLength(1); - const img = painted[0]; - expect(img.width).toBe(SKY_WIDTH); - expect(canvas.width).toBe(SKY_WIDTH); - expect(canvas.height).toBe(img.height); - for (let i = 3; i < img.data.length; i += 4) expect(img.data[i]).toBe(255); - const x = Math.floor(SKY_WIDTH / 2); - expect(pixel(img, x, 0)).not.toEqual(pixel(img, x, img.height - 1)); - expect(mean(img)).toBeGreaterThan(20); - s.dispose(); - }); - - it('follows the baked sky: noon is brighter than midnight, and ?sun= / ?az= move it', () => { - const noon = canvasWith(); - createTerrainSkyScene({ canvas: noon.canvas, tier: 'low', sky: 'noonday' })!.dispose(); - const night = canvasWith(); - createTerrainSkyScene({ canvas: night.canvas, tier: 'low', sky: 'midnight' })!.dispose(); - expect(mean(noon.painted[0])).toBeGreaterThan(mean(night.painted[0]) * 1.5); - - const low = canvasWith(); - createTerrainSkyScene({ canvas: low.canvas, tier: 'low', sun: { elevation: 30 } })!.dispose(); - const down = canvasWith(); - createTerrainSkyScene({ canvas: down.canvas, tier: 'low', sun: { elevation: -20 } })!.dispose(); - expect(mean(low.painted[0])).toBeGreaterThan(mean(down.painted[0])); - - search = '?sun=30&az=0'; - const q0 = canvasWith(); - createTerrainSkyScene({ canvas: q0.canvas, tier: 'low' })!.dispose(); - search = '?sun=30&az=180'; - const q1 = canvasWith(); - createTerrainSkyScene({ canvas: q1.canvas, tier: 'low' })!.dispose(); - expect(Array.from(q0.painted[0].data)).not.toEqual(Array.from(q1.painted[0].data)); - }); - - it('stars only on a dark sky', () => { - const night = canvasWith(); - const a = createTerrainSkyScene({ canvas: night.canvas, tier: 'low', sky: 'midnight' })!; - expect(night.parentAppend).toHaveBeenCalledTimes(1); - expect(arcs).toBeGreaterThan(0); - a.dispose(); - expect(overlay.remove).toHaveBeenCalled(); - arcs = 0; - const day = canvasWith(); - createTerrainSkyScene({ canvas: day.canvas, tier: 'low', sky: 'noonday' })!.dispose(); - expect(day.parentAppend).not.toHaveBeenCalled(); - expect(arcs).toBe(0); - }); - - it('repaints on resize, and dispose stops listening', () => { - vi.useFakeTimers(); - vi.stubGlobal('window', { - ...(window as any), - setTimeout, - addEventListener: (window as any).addEventListener, - }); - const { canvas, painted } = canvasWith(); - const s = createTerrainSkyScene({ canvas, tier: 'low', sky: 'noonday' })!; - expect(windowListeners.resize).toBeDefined(); - windowListeners.resize(); - vi.advanceTimersByTime(300); - expect(painted).toHaveLength(2); - s.dispose(); - expect(windowListeners.resize).toBeUndefined(); - vi.useRealTimers(); - }); -}); - -describe('the sky-only tier label', () => { - const labels = (parentAppend: ReturnType) => - parentAppend.mock.calls.filter(([e]) => e?.textContent === 'terrain · sky-only'); - - it('shows for ?tierlabel=1 only where the overlays are allowed', () => { - search = '?tierlabel=1'; - const off = canvasWith(); - createTerrainSkyScene({ canvas: off.canvas, tier: 'low' })!.dispose(); - expect(labels(off.parentAppend)).toHaveLength(0); - const on = canvasWith(); - createTerrainSkyScene({ canvas: on.canvas, tier: 'low', debug: true })!.dispose(); - expect(labels(on.parentAppend)).toHaveLength(1); - }); - - it('the door allows it from the config flag, and not from a plain production config', async () => { - vi.stubEnv('DEV', false); - vi.stubEnv('VITE_PREVIEW_DEMO', ''); - search = '?tierlabel=1'; - const plain = canvasWith(); - ( - await startBackgroundScene({ tier: 'low', style: 'terrain' }, {}, { canvas: plain.canvas }) - )?.dispose(); - expect(labels(plain.parentAppend)).toHaveLength(0); - const flagged = canvasWith(); - ( - await startBackgroundScene( - { tier: 'low', style: 'terrain', debugOverlays: true }, - {}, - { canvas: flagged.canvas } - ) - )?.dispose(); - expect(labels(flagged.parentAppend)).toHaveLength(1); - vi.unstubAllEnvs(); - }); -}); - -describe('startBackgroundScene, terrain style', () => { - it('without WebGL2 mounts the sky on the same canvas instead of returning null', async () => { - const { canvas, painted } = canvasWith({ gl: null }); - const scene = await startBackgroundScene({ tier: 'low', style: 'terrain' }, {}, { canvas }); - expect(scene).not.toBeNull(); - expect(canvas.getContext.mock.calls.map((c: unknown[]) => c[0])).toEqual(['webgl2', '2d']); - expect(painted).toHaveLength(1); - scene!.dispose(); - }); - - it('with WebGL2 the terrain runs and the 2D sky is never requested', async () => { - const gl: any = new Proxy( - {}, - { - get(_t, name: string) { - if (name === 'getShaderParameter' || name === 'getProgramParameter') return () => true; - if (name === 'checkFramebufferStatus') return () => 1; - if (name === 'getParameter') return () => 16; - if (/^[A-Z_0-9]+$/.test(name)) return 1; - return () => ({}); - }, - } - ); - Object.assign(document, { - addEventListener() {}, - removeEventListener() {}, - visibilityState: 'visible', - }); - vi.stubGlobal('requestAnimationFrame', () => 1); - vi.stubGlobal('cancelAnimationFrame', () => {}); - vi.stubGlobal('performance', { now: () => 0 }); - (window as any).matchMedia = () => ({ - matches: false, - addEventListener() {}, - removeEventListener() {}, - }); - const { canvas, painted } = canvasWith({ gl }); - const scene = await startBackgroundScene({ tier: 'low', style: 'terrain' }, {}, { canvas }); - expect(scene).not.toBeNull(); - expect(canvas.getContext.mock.calls.map((c: unknown[]) => c[0])).toEqual(['webgl2']); - expect(painted).toHaveLength(0); - scene!.dispose(); - }); - - it('a canvas that took a GL context but gives no scene still ends as null: no 2D context to paint on', async () => { - const { canvas } = canvasWith({ gl: null, twoD: false }); - expect( - await startBackgroundScene({ tier: 'low', style: 'terrain' }, {}, { canvas }) - ).toBeNull(); - }); -}); - -describe('the 2D sky lies in the band of its state', () => { - // The painted pixels, read back through the sRGB curve as a screen shows them. - const lumOf = (rgb: number[]) => { - const [r, g, b] = rgb.map((v) => { - const e = v / 255; - return e <= 0.04045 ? e / 12.92 : ((e + 0.055) / 1.055) ** 2.4; - }); - return 0.2126 * r + 0.7152 * g + 0.0722 * b; - }; - const painted = (state: 'day' | 'dusk' | 'night') => { - const c = canvasWith(); - createTerrainSkyScene({ canvas: c.canvas, tier: 'low', ...terrainSkyFor(state) })!.dispose(); - const img = c.painted[0]; - const out: number[] = []; - for (let y = 0; y < img.height; y += 1) { - for (let x = 0; x < img.width; x += 1) out.push(lumOf(pixel(img, x, y))); - } - return out; - }; - - it.each([['day'], ['dusk']] as const)('%s: no pixel below the text bound 0.2983', (state) => { - expect(Math.min(...painted(state))).toBeGreaterThanOrEqual(0.2983); - }); - - it('night: no pixel above the text bound 0.0931', () => { - expect(Math.max(...painted('night'))).toBeLessThanOrEqual(0.0931); - }); -}); diff --git a/src/app/features/scene/terrain/TerrainSky2D.ts b/src/app/features/scene/terrain/TerrainSky2D.ts deleted file mode 100644 index 4653d470..00000000 --- a/src/app/features/scene/terrain/TerrainSky2D.ts +++ /dev/null @@ -1,90 +0,0 @@ -import type { Scene } from '../Scene'; -import type { TerrainOptions } from './Terrain'; -import { chooseSky, skyColour, START_TURNS, Vec3 } from './terrainSky'; -import { createTerrainStars } from './terrainStars'; -import { showTierLabel } from './tierLabel'; -import { CAMERA, view } from './terrainWorld'; - -/** The sky is smooth, so it is painted this many px wide and stretched by the canvas's CSS size. */ -export const SKY_WIDTH = 96; - -/** The sky of the terrain scene without WebGL2: the camera's first frame of `skyColour`, once, on a 2D canvas, with the star layer on top. */ -export type TerrainSkyOptions = Pick< - TerrainOptions, - 'canvas' | 'tier' | 'sky' | 'sun' | 'band' | 'debug' ->; - -/** - * Same contract as `createTerrainScene`. Paints the terrain scene's sky (the CPU twin of its sky shader, from the - * same baked tables and the same `?sun=` `?az=` `?sky=` choice) for the camera at its start, still: nothing moves, so - * a device that cannot run WebGL2 pays one paint and one resize repaint. Below the horizon there is no terrain, so - * the image continues with the horizon's colour. Null for "keep the CSS ground": tier off, or the canvas already - * holds a WebGL context and gives no 2D one. - */ -export function createTerrainSkyScene(opts: TerrainSkyOptions): Scene | null { - if ((opts.tier ?? 'full') === 'off') return null; - const { canvas } = opts; - const ctx = canvas.getContext('2d'); - if (!ctx) return null; - const sky = chooseSky(opts); - const stars = createTerrainStars(canvas, sky); - const heading = START_TURNS; - const tanHalf = Math.tan(CAMERA.fov / 2); - let disposed = false; - let resizeTimer = 0; - - const paint = () => { - const w = SKY_WIDTH; - const cw = canvas.clientWidth || window.innerWidth; - const ch = canvas.clientHeight || window.innerHeight; - const h = Math.max(1, Math.round((w * ch) / cw)); - canvas.width = w; - canvas.height = h; - const v = view(cw / ch, heading); - const image = ctx.createImageData(w, h); - for (let y = 0; y < h; y += 1) { - const ny = 1 - ((y + 0.5) / h) * 2; - for (let x = 0; x < w; x += 1) { - const nx = ((x + 0.5) / w) * 2 - 1; - const d = [0, 1, 2].map( - (i) => v.forward[i] + nx * tanHalf * (cw / ch) * v.right[i] + ny * tanHalf * v.up[i] - ); - const len = Math.hypot(d[0], d[1], d[2]); - const c: Vec3 = skyColour(sky, [d[0] / len, d[1] / len, d[2] / len]); - const at = (y * w + x) * 4; - for (let i = 0; i < 3; i += 1) { - image.data[at + i] = Math.round(255 * Math.min(1, Math.max(0, c[i])) ** (1 / 2.2)); - } - image.data[at + 3] = 255; - } - } - ctx.putImageData(image, 0, 0); - stars?.draw(heading); - }; - - const onResize = () => { - clearTimeout(resizeTimer); - resizeTimer = window.setTimeout(() => { - if (disposed) return; - stars?.resize(); - paint(); - }, 250); - }; - window.addEventListener('resize', onResize); - paint(); - const removeLabel = showTierLabel(canvas, 'sky-only', opts.debug === true); - - return { - login() { - // Nothing moves, so there is no pull-back to start. - }, - dispose() { - if (disposed) return; - disposed = true; - clearTimeout(resizeTimer); - window.removeEventListener('resize', onResize); - removeLabel?.(); - stars?.dispose(); - }, - }; -} diff --git a/src/app/features/scene/terrain/terrainAlbedo.test.ts b/src/app/features/scene/terrain/terrainAlbedo.test.ts deleted file mode 100644 index 6afac79d..00000000 --- a/src/app/features/scene/terrain/terrainAlbedo.test.ts +++ /dev/null @@ -1,226 +0,0 @@ -/* eslint-disable no-restricted-syntax -- tests loop over skies, heights and slopes */ -import { describe, expect, it } from 'vitest'; -import { SKY } from './terrainSky'; -import { - ALBEDO, - albedoAt, - albedoPalette, - bilinearHeight, - CAVITY, - cavityAt, - curvatureAt, - grainAt, - triWeights, - wobble, - wobbleAt, -} from './terrainAlbedo'; -import { GRID_FRAG } from './terrainShaders'; - -const near = (a: readonly number[], b: readonly number[], eps = 1e-6) => - a.every((v, i) => Math.abs(v - b[i]) < eps); -const luma = (c: readonly number[]) => 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]; -// A point where the wobble is zero, so band edges sit exactly where the palette says. -const FLAT_X = Math.PI / 0.043; -// A normal for the xz plane alone (all the weight on it), carrying `ny` for the slope bands. -const facing = (ny: number) => [0, ny, 0] as const; -const at = (sky: keyof typeof SKY, h: number, ny: number) => - albedoAt(albedoPalette(SKY[sky]), h, facing(ny), FLAT_X, 0); - -describe('albedo by slope and height', () => { - it('the test point really has no wobble', () => { - expect(Math.abs(wobble(FLAT_X, 0))).toBeLessThan(1e-9); - }); - - it('steep faces are rock at every height, gentle low ones are soil, gentle high ones are snow', () => { - const p = albedoPalette(SKY.noonday); - for (const h of [10, 90, 160, 220]) expect(near(at('noonday', h, 0.3), p.rock)).toBe(true); - expect(near(at('noonday', 10, 1), p.soil)).toBe(true); - expect(near(at('noonday', 220, 1), p.snow)).toBe(true); - }); - - it('soil grades to scree by height on gentle ground, halfway at the middle of the band', () => { - const p = albedoPalette(SKY.noonday); - const half = p.soil.map((v, i) => (v + p.scree[i]) / 2); - expect(near(at('noonday', (ALBEDO.screeFrom + ALBEDO.screeTo) / 2, 1), half)).toBe(true); - }); - - it('snow is shed as the face steepens: the same height goes snow, then mixed, then rock', () => { - const l = [1, 0.8, 0.5].map((ny) => luma(at('noonday', 220, ny))); - expect(l[0]).toBeGreaterThan(l[1]); - expect(l[1]).toBeGreaterThan(l[2]); - }); - - it('is continuous: a small step in height or slope never jumps a channel by more than a tenth', () => { - for (const sky of ['midnight', 'noonday'] as const) - for (let h = 0; h < 250; h += 1) - for (let ny = 0.3; ny <= 1; ny += 0.05) { - const a = at(sky, h, ny); - const b = at(sky, h + 1, ny + 0.01); - a.forEach((v, i) => expect(Math.abs(v - b[i])).toBeLessThan(0.1)); - } - }); - - it('never returns a negative or a super-white channel', () => { - for (const sky of ['midnight', 'noonday'] as const) - for (let h = -20; h < 300; h += 7) - for (let ny = 0; ny <= 1; ny += 0.1) - for (const v of albedoAt(albedoPalette(SKY[sky]), h, facing(ny), h * 3, ny * 91)) { - expect(v).toBeGreaterThanOrEqual(0); - expect(v).toBeLessThanOrEqual(1); - } - }); - - it('the wobble moves band edges but stays inside its stated amplitude', () => { - for (let i = 0; i < 400; i += 1) - expect(Math.abs(wobble(i * 13.7, i * -9.1))).toBeLessThanOrEqual(1); - }); -}); - -describe('per-sky palette', () => { - const mid = albedoPalette(SKY.midnight); - const noon = albedoPalette(SKY.noonday); - - it('midnight snows lower than noonday', () => { - expect(mid.snowLine).toBeLessThan(noon.snowLine); - }); - - it('midnight is tinted toward the cool horizon haze, noonday toward the warm sun', () => { - // blue share of the same material is higher at night - const blueShare = (c: readonly number[]) => c[2] / (c[0] + c[1] + c[2]); - expect(blueShare(mid.scree)).toBeGreaterThan(blueShare(noon.scree)); - expect(blueShare(mid.snow)).toBeGreaterThan(blueShare(noon.snow)); - }); - - it('a sun at the horizon lands between the two palettes', () => { - const dusk = albedoPalette({ ...SKY.noonday, elevation: 2 }); - expect(dusk.snowLine).toBeLessThan(noon.snowLine); - expect(dusk.snowLine).toBeGreaterThan(mid.snowLine); - }); - - it('keeps every material in 0..1', () => { - for (const p of [mid, noon]) - for (const c of [p.soil, p.scree, p.rock, p.snow]) - c.forEach((v) => { - expect(v).toBeGreaterThan(0); - expect(v).toBeLessThanOrEqual(1); - }); - }); -}); - -describe('shader agrees with the pure function on its numbers', () => { - it('takes every band number from ALBEDO, and reads no texture for colour', () => { - expect(GRID_FRAG).toContain(`#define ALB_SNOW_BAND ${ALBEDO.snowBand.toFixed(1)}`); - expect(GRID_FRAG).toContain(`#define ALB_ROCK_LO ${ALBEDO.rockLo}`); - expect(GRID_FRAG).toContain(`#define ALB_WOBBLE_S ${ALBEDO.wobbleSlope}`); - expect(GRID_FRAG).toContain(`#define ALB_GRAIN_COARSE ${ALBEDO.grainCoarse}`); - expect(GRID_FRAG).toContain(`#define ALB_STRATA ${ALBEDO.strata}`); - expect(GRID_FRAG).toContain(`#define ALB_FINE_WARP ${ALBEDO.fineWarp.toFixed(1)}`); - expect(GRID_FRAG).toContain('waves3(warpq(qy),'); - // the only fetch for colour-by-material would be a texture; the height map's texelFetch is the only other read, and the sky lookup is the baked scattering table's - expect(GRID_FRAG.match(/texelFetch|texture\((?!uSky|uAP)/g)).toHaveLength(1); - }); -}); - -const UP = [0, 1, 0] as const; -const EAST = [1, 0, 0] as const; - -describe('grain', () => { - const samples = (rock: number, distance: number) => - Array.from({ length: 400 }, (_, i) => - grainAt(i * 1.7, 100 + i * 0.3, i * 0.9, UP, rock, distance) - ); - const spread = (v: number[]) => Math.max(...v) - Math.min(...v); - - it('varies the surface near the eye, never goes negative, and averages about 1', () => { - const v = samples(0, 50); - expect(spread(v)).toBeGreaterThan(0.4); - expect(Math.min(...v)).toBeGreaterThanOrEqual(0); - expect(v.reduce((a, b) => a + b, 0) / v.length).toBeGreaterThan(0.85); - }); - - it('drops its fine octave with distance, so far ground does not shimmer', () => { - const rangeOf = (d: number) => - spread(Array.from({ length: 400 }, (_, i) => grainAt(i * 0.37, 100, i * 0.21, UP, 0, d))); - expect(rangeOf(900)).toBeLessThan(rangeOf(50)); - }); - - it('layers the rock: strata show only where the face is rock', () => { - const height = (rock: number) => - spread(Array.from({ length: 400 }, (_, i) => grainAt(0, 100 + i * 0.05, 0, UP, rock, 2000))); - expect(height(1)).toBeGreaterThan(0.2); - expect(height(0)).toBeLessThan(1e-9); - }); -}); - -describe('triplanar projection', () => { - it('weights sum to 1 and go to the plane the face looks along', () => { - for (const n of [UP, EAST, [0.6, 0.6, 0.529], [0, 0, 1]] as const) { - const w = triWeights(n); - expect(w[0] + w[1] + w[2]).toBeCloseTo(1, 9); - } - expect(triWeights(UP)).toEqual([0, 1, 0]); - expect(triWeights(EAST)).toEqual([1, 0, 0]); - expect(triWeights([0.8, 0.5, 0.33])[0]).toBeGreaterThan(0.7); - }); - - it('a cliff facing east takes its pattern over (z, y), so it varies with height and not with x: no vertical smear', () => { - const col = (x: number, y: number) => grainAt(x, y, 40, EAST, 0, 50); - const alongY = Array.from({ length: 200 }, (_, i) => col(10, 50 + i * 0.7)); - const alongX = Array.from({ length: 200 }, (_, i) => col(i * 0.7, 50)); - expect(Math.max(...alongY) - Math.min(...alongY)).toBeGreaterThan(0.3); - expect(Math.max(...alongX) - Math.min(...alongX)).toBeLessThan(1e-9); - expect(wobbleAt(5, 80, 40, EAST)).toBeCloseTo(wobbleAt(500, 80, 40, EAST), 12); - expect(wobbleAt(5, 80, 40, EAST)).not.toBeCloseTo(wobbleAt(5, 120, 40, EAST), 3); - }); - - it('level ground takes its pattern over (x, z) alone, as before', () => { - expect(grainAt(12, 10, 30, UP, 0, 50)).toBeCloseTo(grainAt(12, 900, 30, UP, 0, 50), 12); - expect(wobbleAt(12, 10, 30, UP)).toBeCloseTo(wobble(12, 30), 12); - }); -}); - -describe('cavity shading', () => { - // A texel grid of heights with one bump; `hAt` is the nearest texel, `bilinearAt` the continuous reading. - const bump = (i: number, j: number) => 6 * Math.exp(-((i - 20) ** 2 + (j - 20) ** 2) / 40); - const nearestAt = (px: number, pz: number) => bump(Math.floor(px + 0.5), Math.floor(pz + 0.5)); - // Largest change in curvature between neighbouring sample positions a hundredth of a texel apart, over a few texels. - const worstStep = (read: (px: number, pz: number) => number) => { - let worst = 0; - for (let px = 14; px < 26; px += 0.01) - worst = Math.max( - worst, - Math.abs(curvatureAt(read, px + 0.01, 20.3, 4) - curvatureAt(read, px, 20.3, 4)) - ); - return worst; - }; - - it('curvature is the mean of four neighbours at the radius minus the centre', () => { - expect(curvatureAt((px, pz) => px * 2 + pz, 7, 9, 3)).toBeCloseTo(0, 12); - expect(curvatureAt((px, pz) => (px - 5) ** 2 + (pz - 5) ** 2, 5, 5, 2)).toBeCloseTo(4, 12); - }); - - it('bilinear height reads the texel exactly at a texel centre and the mean at the middle of four', () => { - const t = (i: number, j: number) => i * 10 + j * 100; - expect(bilinearHeight(t, 3, 4)).toBe(430); - expect(bilinearHeight(t, 3.5, 4.5)).toBeCloseTo(485, 9); - }); - - it('shading from a bilinear read changes smoothly across texel borders; from the nearest texel it jumps', () => { - const smooth = worstStep((px, pz) => bilinearHeight(bump, px, pz)); - const blocky = worstStep(nearestAt); - expect(blocky).toBeGreaterThan(0.1); - expect(smooth).toBeLessThan(0.02); - }); - - it('the cavity factor darkens a hollow, lights a rise and leaves flat ground alone', () => { - expect(cavityAt(0)).toBe(1); - expect(cavityAt(CAVITY.range)).toBeCloseTo(1 - CAVITY.dark, 12); - expect(cavityAt(-CAVITY.range)).toBeCloseTo(1 + CAVITY.light, 12); - expect(cavityAt(10 * CAVITY.range)).toBeCloseTo(1 - CAVITY.dark, 12); - }); - - it('the grid shader reads the cavity through the bilinear height, the same constants as CAVITY', () => { - expect(GRID_FRAG).toContain(`#define CAV_RANGE ${CAVITY.range.toFixed(1)}`); - expect(GRID_FRAG).not.toMatch(/curv[^;]*hAt\(/); - }); -}); diff --git a/src/app/features/scene/terrain/terrainAlbedo.ts b/src/app/features/scene/terrain/terrainAlbedo.ts deleted file mode 100644 index fdbd9360..00000000 --- a/src/app/features/scene/terrain/terrainAlbedo.ts +++ /dev/null @@ -1,206 +0,0 @@ -// Terrain surface colour as a pure function of height, slope and world position, no texture reads: the shader -// (terrainShaders.ts GRID_FRAG) does the same arithmetic with these numbers as uniforms and #defines. No DOM, no GL. -// Rock where the face is steep, then by height soil, scree and snow; snow only settles on gentle faces. The per-sky -// part reads the baked sky (./terrainSky.ts): the snow line drops and every material is tinted toward the sky's colour -// as the sun goes down, warm by the sun's own colour by day and cool by the horizon haze at night. -import { coldness, hazeColour, SkyData, Vec3 } from './terrainSky'; - -const clamp01 = (x: number) => Math.min(1, Math.max(0, x)); -const smooth = (a: number, b: number, x: number) => { - const t = clamp01((x - a) / (b - a)); - return t * t * (3 - 2 * t); -}; -const mix = (a: number, b: number, t: number) => a + (b - a) * t; - -/** Every number the shader shares: band edges in metres, slope edges as the normal's y (cosine of the slope angle). */ -export const ALBEDO = { - /** soil fades to scree across these heights. */ - screeFrom: 80, - screeTo: 160, - /** half-width in metres of the snow line's fade. */ - snowBand: 22, - /** n.y edges: faces with n.y below `rockLo` are all rock, above `rockHi` none. */ - rockLo: 0.78, - rockHi: 0.95, - /** n.y edges: snow is shed entirely below `snowLo` and settles fully above `snowHi`. */ - snowLo: 0.74, - snowHi: 0.93, - /** world-position wobble of the height edges (metres) and the slope edges, so bands are not contour lines. */ - wobbleHeight: 14, - wobbleSlope: 0.05, - /** Albedo grain: relative swing of the two sine-product octaves (about 20 m and 5 m periods), and of the rock strata. */ - grainCoarse: 0.35, - grainFine: 0.3, - /** Metres the fine octave's coordinates are pushed by a slower sine, so its parallel stripes bend and do not read as hatching. */ - fineWarp: 7, - /** The fine octave fades out between these distances (metres): beyond them it is under a pixel and only shimmers. */ - fineNear: 250, - fineFar: 700, - strata: 0.22, -} as const; - -export interface AlbedoPalette { - soil: Vec3; - scree: Vec3; - rock: Vec3; - snow: Vec3; - /** Metres where snow is half in. */ - snowLine: number; -} - -const BASE = { - soil: [0.045, 0.08, 0.02], - scree: [0.3, 0.235, 0.16], - rock: [0.075, 0.062, 0.06], - snow: [0.72, 0.75, 0.8], -} as const; - -const SNOW_LINE_DAY = 165; -const SNOW_LINE_NIGHT = 135; - -const unit = (c: Vec3): Vec3 => { - const m = Math.max(c[0], c[1], c[2], 1e-6); - return [c[0] / m, c[1] / m, c[2] / m]; -}; - -/** The palette one baked sky gives: base reflectances tinted toward the sky's colour, and its snow line. */ -export function albedoPalette(d: SkyData): AlbedoPalette { - const cold = coldness(d); - const sun = unit(d.direct); - const haze = unit(hazeColour(d)); - const tint = [0, 1, 2].map((i) => mix(sun[i], haze[i], cold)); - const k = mix(0.15, 0.5, cold); - const tinted = (c: Vec3): Vec3 => - [0, 1, 2].map((i) => c[i] * mix(1, tint[i], k)) as unknown as Vec3; - return { - soil: tinted(BASE.soil), - scree: tinted(BASE.scree), - rock: tinted(BASE.rock), - snow: tinted(BASE.snow), - snowLine: mix(SNOW_LINE_DAY, SNOW_LINE_NIGHT, cold), - }; -} - -/** Cheap two-sine value in -1..1 from a 2D world position; stands in for noise so no texture or hash is read. */ -export const wobble = (x: number, z: number): number => - Math.sin(x * 0.043 + z * 0.017) * Math.sin(z * 0.051 - x * 0.023); - -/** - * How much each axis-aligned projection plane counts at a surface with unit normal `n`: weights for (yz, xz, xy), summing - * to 1, sharply favouring the plane the face looks along. Procedural patterns are evaluated on all three and blended by - * these (triplanar), so a cliff is not the floor pattern smeared down it. - */ -export function triWeights(n: Vec3): Vec3 { - const w = n.map((c) => Math.abs(c) ** 4); - const sum = w[0] + w[1] + w[2] || 1; - return [w[0] / sum, w[1] / sum, w[2] / sum]; -} - -/** `wobble` blended over the three projection planes, at a surface point with unit normal `n`. */ -export function wobbleAt(x: number, y: number, z: number, n: Vec3): number { - const w = triWeights(n); - return w[0] * wobble(z, y) + w[1] * wobble(x, z) + w[2] * wobble(x, y); -} - -/** - * Linear albedo at a surface point. `y` the height in metres, `n` the unit normal, `x`/`z` world metres. - * Rock takes the steep faces at any height; on the rest, soil to scree by height, then snow above the snow - * line, thinning to nothing as the face steepens. - */ -export function albedoAt(p: AlbedoPalette, y: number, n: Vec3, x: number, z: number): Vec3 { - const w = wobbleAt(x, y, z, n); - const h = y + ALBEDO.wobbleHeight * w; - const flat = n[1] + ALBEDO.wobbleSlope * w; - const ground = (i: number) => - mix(p.soil[i], p.scree[i], smooth(ALBEDO.screeFrom, ALBEDO.screeTo, h)); - const snow = - smooth(p.snowLine - ALBEDO.snowBand, p.snowLine + ALBEDO.snowBand, h) * - smooth(ALBEDO.snowLo, ALBEDO.snowHi, flat); - const rock = 1 - smooth(ALBEDO.rockLo, ALBEDO.rockHi, flat); - return [0, 1, 2].map((i) => - mix(mix(ground(i), p.snow[i], snow), p.rock[i], rock) - ) as unknown as Vec3; -} - -const COARSE = [ - [0.31, 0.27], - [-0.22, 0.35], - [0.38, -0.12], -] as const; -const FINE = [ - [1.1, 0.7], - [-0.8, 1.2], - [1.3, -0.6], -] as const; -const waves = (k: ReadonlyArray, a: number, b: number) => - k.reduce((sum, [ka, kb]) => sum + Math.sin(a * ka + b * kb), 0) / 3; -/** `waves` of coordinates warped by a sine each (the shader's `warpq`): three plane waves alone make a regular lattice. */ -const wavesWarped = (k: ReadonlyArray, a: number, b: number) => - waves( - k, - a + ALBEDO.fineWarp * Math.sin(b * 0.55 + 1.3), - b + ALBEDO.fineWarp * Math.sin(a * 0.47 + 0.7) - ); - -/** - * The multiplier on albedo that gives the surface grain and the rock its layers, at a surface point (metres) with unit - * normal `n`, `rock` (0..1, how much of the face is rock) and the distance from the eye. Grain is triplanar like the - * wobble. The shader's `ALB_GRAIN_*` block does the same arithmetic. The cavity term beside it in the shader reads the - * height map and has no twin here. - */ -export function grainAt( - x: number, - y: number, - z: number, - n: Vec3, - rock: number, - distance: number -): number { - const w = triWeights(n); - const over = (k: ReadonlyArray, f: typeof waves) => - w[0] * f(k, z, y) + w[1] * f(k, x, z) + w[2] * f(k, x, y); - const coarse = over(COARSE, waves); - const fine = over(FINE, wavesWarped) * (1 - smooth(ALBEDO.fineNear, ALBEDO.fineFar, distance)); - const layers = Math.sin(y * 0.9 + wobbleAt(x, y, z, n) * 3); - return Math.max( - 0, - 1 + ALBEDO.grainCoarse * coarse + ALBEDO.grainFine * fine + ALBEDO.strata * rock * layers - ); -} - -/** The cavity term's numbers: curvature (metres) at which a hollow is fully shaded / a rise fully lit, and by how much. */ -export const CAVITY = { radius: 12, range: 12, dark: 0.55, light: 0.3 } as const; - -/** Height at a continuous texel position, bilinear over the four texels around it (the shader's `hBil`). */ -export function bilinearHeight( - texel: (i: number, j: number) => number, - px: number, - pz: number -): number { - const i = Math.floor(px); - const j = Math.floor(pz); - const fx = px - i; - const fz = pz - j; - return mix( - mix(texel(i, j), texel(i + 1, j), fx), - mix(texel(i, j + 1), texel(i + 1, j + 1), fx), - fz - ); -} - -/** Mean of the four neighbours `r` texels away minus the centre: positive in a hollow, negative on a rise. */ -export function curvatureAt( - height: (px: number, pz: number) => number, - px: number, - pz: number, - r: number -): number { - return ( - 0.25 * (height(px + r, pz) + height(px - r, pz) + height(px, pz + r) + height(px, pz - r)) - - height(px, pz) - ); -} - -/** The multiplier on lit colour for a curvature: a hollow sits in shade, a rise catches light (the shader's `cavity`). */ -export const cavityAt = (curv: number): number => - 1 - CAVITY.dark * clamp01(curv / CAVITY.range) + CAVITY.light * clamp01(-curv / CAVITY.range); diff --git a/src/app/features/scene/terrain/terrainScatter.test.ts b/src/app/features/scene/terrain/terrainScatter.test.ts deleted file mode 100644 index c153eb5f..00000000 --- a/src/app/features/scene/terrain/terrainScatter.test.ts +++ /dev/null @@ -1,141 +0,0 @@ -/* eslint-disable no-restricted-syntax -- tests walk table texels */ -import { describe, expect, it } from 'vitest'; -import { baked } from '../../../../sky/baked'; -import { - aerialRay, - AP_ELEVATIONS, - AP_SLICES, - apElevation, - apSliceKm, - decode, - SUN_ELEVATIONS_DEG, - viewElevation, -} from '../../../../sky/scatter.js'; -import { - AERIAL_GLSL, - aerialAt, - AP_VOLUME, - apVolumeWords, - SCATTER_GLSL, - scatterRadiance, - skyViewWords, - SKY_VIEW, - tableWords, - transmittanceAt, -} from './terrainScatter'; - -const S = baked.scatter.sky_view; - -describe('the table upload', () => { - it('decodes the baked base64 to one half-float word per channel per texel', () => { - const w = skyViewWords(); - expect(w.length).toBe(S.width * S.height * S.depth * S.channels); - expect(SKY_VIEW).toEqual({ width: S.width, height: S.height, depth: S.depth }); - expect(tableWords(baked.scatter.transmittance.data)).toHaveLength(32 * 3); - }); - - it('words are little-endian: the base64 bytes lo, hi make a word hi << 8 | lo', () => { - expect(Array.from(tableWords(btoa(String.fromCharCode(0x34, 0x12, 0xff, 0x7b))))).toEqual([ - 0x1234, 0x7bff, - ]); - }); -}); - -describe('scatterRadiance (the CPU twin of the sampler)', () => { - it('returns the stored texel exactly at a texel centre: layout x azimuth, y view, z sun', () => { - const w = skyViewWords(); - for (const [z, y, x] of [ - [10, 31, 0], - [8, 5, 3], - [5, 20, 6], - [11, 0, 2], - ]) { - const base = ((z * S.height + y) * S.width + x) * 3; - const got = scatterRadiance( - S.sun_elevations_deg[z], - viewElevation(y), - x * S.azimuth_step_deg - ); - got.forEach((v, c) => expect(v).toBeCloseTo(decode(w[base + c]), 9)); - } - }); - - it('interpolates between texels and clamps beyond the table', () => { - const a = scatterRadiance(25, 10, 0)[2]; - const b = scatterRadiance(45, 10, 0)[2]; - const mid = scatterRadiance(35, 10, 0)[2]; // 35 is halfway between 25 and 45 on the sun axis - expect(mid).toBeCloseTo((a + b) / 2, 9); - expect(scatterRadiance(500, 10, 400)).toEqual(scatterRadiance(90, 10, 180)); - expect(scatterRadiance(30, 10, -90)).toEqual(scatterRadiance(30, 10, 90)); - }); - - it('is black under the planet’s shadow limit and blue at a high noon zenith', () => { - scatterRadiance(-18, 30, 0).forEach((v) => expect(v).toBeLessThan(1e-6)); - const noon = scatterRadiance(45, 85, 90); - expect(noon[2]).toBeGreaterThan(1.5 * noon[0]); - }); -}); - -describe('transmittanceAt', () => { - it('is the zenith transmittance exp(-TAU) overhead and redder at the horizon', () => { - const z = transmittanceAt(90); - [0.06, 0.12, 0.26].forEach((tau, i) => expect(z[i]).toBeCloseTo(Math.exp(-tau), 2)); - const h = transmittanceAt(2); - expect(h[2] / h[0]).toBeLessThan(0.5 * (z[2] / z[0])); - }); - - it('is zero where the ground is in the way', () => { - expect(transmittanceAt(-4)).toEqual([0, 0, 0]); - }); -}); - -describe('the GLSL sampler', () => { - it('uses the layout the README documents: texel-centre coordinates over a 7 x 32 x 12 texture, decoded by the store scale', () => { - expect(SCATTER_GLSL).toContain('(x + 0.5) / 7.0'); - expect(SCATTER_GLSL).toContain('(y + 0.5) / 32.0'); - expect(SCATTER_GLSL).toContain('(uSunIndex + 0.5) / 12.0'); - expect(SCATTER_GLSL).toContain('/ 64.0'); - expect(SCATTER_GLSL).toContain('sqrt(clamp((el - (-4.0)) / 94.0, 0.0, 1.0)) * 31.0'); - expect(SCATTER_GLSL).toContain('* 6.0'); - }); -}); - -describe('the aerial perspective volume as the terrain reads it', () => { - it('uploads RGBA half floats in the baked layout', () => { - const a = baked.scatter.aerial_perspective; - expect(apVolumeWords()).toHaveLength(a.width * a.height * a.depth * 4); - expect(AP_VOLUME).toEqual({ width: a.width, height: a.height, depth: a.depth }); - }); - - it('on a texel centre the CPU twin returns the baked ray exactly (to half-float precision)', () => { - const sunI = 8; - const ei = 5; - const slice = 6; - const want = aerialRay(SUN_ELEVATIONS_DEG[sunI], apElevation(ei), 90)[slice]; - const got = aerialAt(SUN_ELEVATIONS_DEG[sunI], apElevation(ei), 90, apSliceKm(slice)); - for (let c = 0; c < 3; c += 1) expect(got.L[c]).toBeCloseTo(want[c], 3); - expect(got.alpha).toBeCloseTo(want[3], 3); - }); - - it('between texels it is near the model: the filtering error is small against the signal', () => { - const want = aerialRay(10, -1.3, 75)[AP_SLICES - 2]; - const got = aerialAt(10, -1.3, 75, apSliceKm(AP_SLICES - 2)); - expect(Math.abs(got.alpha - want[3])).toBeLessThan(0.03); - expect(got.L[0] / want[0]).toBeGreaterThan(0.6); - expect(got.L[0] / want[0]).toBeLessThan(1.6); - }); - - it('fades to nothing at the observer, and clamps past the last slice', () => { - expect(aerialAt(45, -2, 90, 0)).toEqual({ L: [0, 0, 0], alpha: 0 }); - const last = aerialAt(45, -2, 90, apSliceKm(AP_SLICES - 1)); - const beyond = aerialAt(45, -2, 90, 1e6); - expect(beyond.alpha).toBeCloseTo(last.alpha, 9); - }); - - it('the shader lookup carries the same constants as the table', () => { - const a = baked.scatter.aerial_perspective; - expect(AERIAL_GLSL).toContain(`/ ${a.height}.0`); - expect(AERIAL_GLSL).toContain(`${a.max_km.toFixed(1)}`); - expect(AERIAL_GLSL).toContain(`${AP_ELEVATIONS}.0 +`); - }); -}); diff --git a/src/app/features/scene/terrain/terrainScatter.ts b/src/app/features/scene/terrain/terrainScatter.ts deleted file mode 100644 index 72ebfb5c..00000000 --- a/src/app/features/scene/terrain/terrainScatter.ts +++ /dev/null @@ -1,179 +0,0 @@ -// The baked scattering tables (src/sky/baked.ts `scatter`, layout in src/sky/README.md) as the terrain scene -// uses them: decoded to half-float words for the GPU, a CPU twin of the shader's sky lookup for tests and -// for the sun's colour at an arbitrary elevation, and the GLSL both shaders share. No DOM, no GL. -import { baked } from '../../../../sky/baked'; -import { - AP_DISTANCE_SCALE, - AP_ELEVATIONS, - AP_SLICES, - apElevationIndex, - apSliceIndex, - decode, - sunIndex, - viewIndex, -} from '../../../../sky/scatter.js'; -import type { Vec3 } from './terrainSky'; - -const S = baked.scatter; -const AP = S.aerial_perspective; -const SKY = S.sky_view; -const VIEW = S.view_elevation_deg; - -/** Raw little-endian half-float words of a base64 table, ready for `texImage3D(..., HALF_FLOAT, words)`. */ -export function tableWords(b64: string): Uint16Array { - const bytes = atob(b64); - return Uint16Array.from( - { length: bytes.length / 2 }, - (_, i) => bytes.charCodeAt(2 * i) + 256 * bytes.charCodeAt(2 * i + 1) - ); -} - -export const SKY_VIEW = { width: SKY.width, height: SKY.height, depth: SKY.depth } as const; -export const STORE_SCALE = S.store_scale; -export const skyViewWords = (): Uint16Array => tableWords(SKY.data); - -/** The aerial perspective volume (layout in src/sky/scatter.js): RGBA16F, x azimuth from the light, y slice-major block of elevations, z light elevation. */ -export const AP_VOLUME = { width: AP.width, height: AP.height, depth: AP.depth } as const; -export const apVolumeWords = (): Uint16Array => tableWords(AP.data); -export { AP_DISTANCE_SCALE }; - -/** Decode a stored table to values, once. */ -const decoded = (data: string) => { - let values: Float32Array | undefined; - return (): Float32Array => { - if (!values) values = Float32Array.from(tableWords(data), decode); - return values; - }; -}; -const transmittanceTable = decoded(S.transmittance.data); -const skyTable = decoded(SKY.data); -const apTable = decoded(AP.data); - -/** Sun colour at normal incidence for a sun at `elevationDeg`: the baked transmittance, per channel. Zero under the horizon. */ -export function transmittanceAt(elevationDeg: number): Vec3 { - const t = transmittanceTable(); - const f = Math.min(viewIndex(elevationDeg), VIEW.samples - 1); - const i = Math.min(Math.floor(f), VIEW.samples - 2); - const k = f - i; - return [0, 1, 2].map((c) => t[i * 3 + c] * (1 - k) + t[(i + 1) * 3 + c] * k) as unknown as Vec3; -} - -/** - * Sky radiance per steradian for a sun of unit irradiance, trilinear in (azimuth from the sun, view - * elevation, sun elevation) on texel centres, clamped at the edges: what the GPU's LINEAR sampler returns. - */ -export function scatterRadiance(sunElDeg: number, viewElDeg: number, azFromSunDeg: number): Vec3 { - const t = skyTable(); - const at = [ - Math.min(Math.abs(azFromSunDeg) / 180, 1) * (SKY.width - 1), - viewIndex(viewElDeg), - sunIndex(sunElDeg), - ]; - const lo = at.map((v, a) => Math.min(Math.floor(v), [SKY.width, SKY.height, SKY.depth][a] - 2)); - const f = at.map((v, a) => v - lo[a]); - const out = [0, 0, 0]; - for (let corner = 0; corner < 8; corner += 1) { - const dx = corner % 2; - const dy = Math.floor(corner / 2) % 2; - const dz = Math.floor(corner / 4); - const w = (dx ? f[0] : 1 - f[0]) * (dy ? f[1] : 1 - f[1]) * (dz ? f[2] : 1 - f[2]); - const base = (((lo[2] + dz) * SKY.height + lo[1] + dy) * SKY.width + lo[0] + dx) * 3; - for (let c = 0; c < 3; c += 1) out[c] += w * t[base + c]; - } - return [out[0], out[1], out[2]]; -} - -/** - * Aerial perspective along a view ray: in-scatter luminance per channel (for a light of unit irradiance) and opacity - * (1 - mean transmittance), for a light at `lightElDeg`, a ray `viewElDeg` (0 and below) and `azDeg` from the light, - * `km` of baked path along it. Trilinear in (azimuth, elevation, light elevation) and linear between slices, the arithmetic the - * shader's `aerial()` does on the GPU; below the first slice it fades to nothing at the observer (Hillaire's near-slice fade). - */ -export function aerialAt( - lightElDeg: number, - viewElDeg: number, - azDeg: number, - km: number -): { L: Vec3; alpha: number } { - const t = apTable(); - const x = Math.min(Math.abs(azDeg) / 180, 1) * (AP.width - 1); - const e = apElevationIndex(viewElDeg); - const z = sunIndex(lightElDeg); - const texel = (slice: number): number[] => { - const lo = [ - Math.min(Math.floor(x), AP.width - 2), - Math.min(Math.floor(e), AP_ELEVATIONS - 2), - Math.min(Math.floor(z), AP.depth - 2), - ]; - const f = [x - lo[0], e - lo[1], z - lo[2]]; - const out = [0, 0, 0, 0]; - for (let corner = 0; corner < 8; corner += 1) { - const dx = corner % 2; - const dy = Math.floor(corner / 2) % 2; - const dz = Math.floor(corner / 4); - const w = (dx ? f[0] : 1 - f[0]) * (dy ? f[1] : 1 - f[1]) * (dz ? f[2] : 1 - f[2]); - const base = - (((lo[2] + dz) * AP.height + slice * AP_ELEVATIONS + lo[1] + dy) * AP.width + lo[0] + dx) * - 4; - for (let c = 0; c < 4; c += 1) out[c] += w * t[base + c]; - } - return out; - }; - const f = apSliceIndex(km); - const fs = Math.min(Math.max(f, 0), AP_SLICES - 1); - const k = Math.min(Math.floor(fs), AP_SLICES - 2); - const a = texel(k); - const b = texel(k + 1); - const fade = Math.min(Math.max(f + 1, 0), 1); - const v = [0, 1, 2, 3].map((c) => (a[c] + (b[c] - a[c]) * (fs - k)) * fade); - return { L: [v[0], v[1], v[2]], alpha: v[3] }; -} - -/** - * The lowest view elevation the sky is sampled at, degrees. The table dips toward the ground over its last degree - * (its rows below the horizon are for an observer who would hit the ground), so at and below this the sky and the - * terrain's haze both take the colour here, flat to the horizon, and meet without a seam. - */ -export const HORIZON_FLOOR = 1.5; - -/** The sky shader's lookup, in GLSL: `skyScatter(viewDirection)` is unit-sun radiance, needs uSky, uSunIndex, uSun. */ -export const SCATTER_GLSL = ` -uniform highp sampler3D uSky; -uniform float uSunIndex; -uniform vec3 uSun; -vec3 skyScatter(vec3 d) { - float el = max(degrees(asin(clamp(d.y, -1.0, 1.0))), ${HORIZON_FLOOR.toFixed(1)}); - vec2 h = d.xz, s = uSun.xz; - float az = (length(h) < 1e-4 || length(s) < 1e-4) ? 0.0 - : degrees(acos(clamp(dot(normalize(h), normalize(s)), -1.0, 1.0))); - float y = sqrt(clamp((el - (${VIEW.min.toFixed(1)})) / ${(VIEW.max - VIEW.min).toFixed( - 1 -)}, 0.0, 1.0)) * ${(VIEW.samples - 1).toFixed(1)}; - float x = clamp(az / 180.0, 0.0, 1.0) * ${(SKY.width - 1).toFixed(1)}; - return texture(uSky, vec3((x + 0.5) / ${SKY.width}.0, (y + 0.5) / ${ - SKY.height -}.0, (uSunIndex + 0.5) / ${SKY.depth}.0)).rgb / ${S.store_scale.toFixed(1)}; -}`; - -/** - * The aerial perspective lookup, in GLSL: `aerial(lightIndex, viewElDeg, azDeg, km)` is `aerialAt` on the GPU. Needs uAP. - * Each slice is one hardware-filtered fetch, kept inside its block of elevation rows so the filter never reads a - * neighbouring slice; two fetches and a lerp per call. - */ -export const AERIAL_GLSL = ` -uniform highp sampler3D uAP; -vec4 apSlice(float k, float e, float x, float z) { - return texture(uAP, vec3((x + 0.5) / ${AP.width}.0, (k * ${AP.elevations}.0 + e + 0.5) / ${ - AP.height -}.0, (z + 0.5) / ${AP.depth}.0)) / ${S.store_scale.toFixed(1)}; -} -vec4 aerial(float lightIndex, float viewElDeg, float azDeg, float km) { - float e = ${(AP.elevations - 1).toFixed( - 1 - )} * (1.0 - sqrt(clamp(-viewElDeg / ${(-AP.elevation_min_deg).toFixed(1)}, 0.0, 1.0))); - float x = clamp(abs(azDeg) / 180.0, 0.0, 1.0) * ${(AP.width - 1).toFixed(1)}; - float f = ${AP.slices}.0 * sqrt(max(km, 0.0) / ${AP.max_km.toFixed(1)}) - 1.0; - float fs = clamp(f, 0.0, ${(AP.slices - 1).toFixed(1)}); - float k = min(floor(fs), ${(AP.slices - 2).toFixed(1)}); - return mix(apSlice(k, e, x, lightIndex), apSlice(k + 1.0, e, x, lightIndex), fs - k) * clamp(f + 1.0, 0.0, 1.0); -}`; diff --git a/src/app/features/scene/terrain/terrainShaders.ts b/src/app/features/scene/terrain/terrainShaders.ts deleted file mode 100644 index f6bcce37..00000000 --- a/src/app/features/scene/terrain/terrainShaders.ts +++ /dev/null @@ -1,255 +0,0 @@ -// GLSL ES 3.00. The height map is baked once by CultMath's Phacelle noise (vendored, unedited, MPL-2.0: Rune -// Skovbo Johansen's Phacelle noise, https://blog.runevision.com/2026/01/) composed into a slope-directed gully -// filter after the description in his March 2026 erosion-filter post. The composition is ours, written from -// that description; it is not his filter and has not been compared against it (see harness terrainDemo.ts on -// the terrain-tier-spike branch, from which this is promoted). The height is packed in two bytes of an RGBA8 -// target, so no float colour-buffer extension is needed. -import cultmath from '../shaders/CultMath.glsl?raw'; -import phacelle from '../shaders/CultMath.Phacelle.glsl?raw'; -import { trimGlsl } from '../cultmathTrim'; -import { LUMA } from '../skyBand'; -import { ALBEDO, CAVITY } from './terrainAlbedo'; -import { AERIAL_GLSL, AP_DISTANCE_SCALE, SCATTER_GLSL } from './terrainScatter'; -import { GLOW_ZENITH, MOON_HAZE, SKY_EXPOSURE, SKY_FADE, STAR_FLOOR } from './terrainSky'; -import { TERRAIN } from './terrainWorld'; - -const HEADER = - '#version 300 es\nprecision highp float;\nprecision highp int;\nprecision highp sampler2D;\n'; -const f1 = (x: number) => x.toFixed(1); -const lit = (x: number) => (Number.isInteger(x) ? x.toFixed(1) : String(x)); - -export const FULLSCREEN_VERT = `${HEADER} -void main() { - vec2 p = vec2(float((gl_VertexID << 1) & 2), float(gl_VertexID & 2)); - gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0); -}`; - -const HEIGHT_STAGE = ` -uniform float uSpan; -uniform vec2 uSeed; -uniform float uTexels; -out vec4 o; - -const float BASE_AMP = 60.0; -const float BASE_FREQ = 1.0 / 520.0; -const float BASE_LIFT = 110.0; -const float CELL0 = 160.0; -const float SIDE_LEN = 3.0; -const float NORM = 0.5; -const float SLOPE_REF = 0.55; -const float DETAIL = 1.5; -const float AMP0 = 11.0; -const float HLO = 20.0, HHI = 200.0; - -float easeOut(float t) { t = clamp(t, 0.0, 1.0); return 1.0 - (1.0 - t) * (1.0 - t); } -float powInv(float t, float p) { return 1.0 - pow(1.0 - t, p); } - -float height(vec2 xz) { - vec4 fg = cultmath_fbm_grad(vec3(xz * BASE_FREQ, 0.0), 4, 2.0, 0.45); - float h = BASE_LIFT + BASE_AMP * fg.w; - vec2 g = BASE_AMP * BASE_FREQ * fg.xy; - float target = clamp((h - HLO) / (HHI - HLO) * 2.0 - 1.0, -1.0, 1.0); - float combi = 1.0; - float amp = AMP0; - float cell = CELL0; - for (int i = 0; i < OCTAVES; i++) { - float slope = length(g); - vec2 downhill = slope > 1e-4 ? -g / slope : vec2(1.0, 0.0); - vec2 across = vec2(-downhill.y, downhill.x); - CultPhasor ph = cultmath_phacelle(vec3(xz / cell, 0.5), vec3(across * SIDE_LEN, 0.0), 0.0, NORM); - float mask = easeOut(slope / SLOPE_REF) * combi; - float faded = mix(target, ph.cos.w, mask); - h += amp * faded; - g += amp * mask * ph.cos.xy / cell; - combi = powInv(combi, DETAIL) * (1.0 - abs(ph.sin.w)); - target = faded; - amp *= 0.5; - cell *= 0.5; - } - return h; -} - -void main() { - vec2 uv = gl_FragCoord.xy / vec2(uTexels); - float h = clamp(height((uv - 0.5) * uSpan + uSeed) / ${f1(TERRAIN.hmax)}, 0.0, 1.0); - float q = floor(h * 65535.0 + 0.5); - o = vec4(floor(q / 256.0) / 255.0, mod(q, 256.0) / 255.0, 0.0, 1.0); -}`; - -/** The height-bake fragment shader: header, the part of CultMath that Phacelle and the stage reach, Phacelle, the stage. */ -export function heightFragmentSource(): string { - const math = trimGlsl(cultmath, [phacelle, HEIGHT_STAGE]); - return `${HEADER}#define OCTAVES 4\n${math}\n${phacelle}\n${HEIGHT_STAGE}`; -} - -const FETCH = ` -uniform sampler2D uHeight; -uniform int uTex; -float hAt(ivec2 t) { - t = clamp(t, ivec2(0), ivec2(uTex - 1)); - vec4 s = texelFetch(uHeight, t, 0); - return (floor(s.r * 255.0 + 0.5) * 256.0 + floor(s.g * 255.0 + 0.5)) / 65535.0 * ${f1( - TERRAIN.hmax - )}; -} -// The height at a point in texel units, bilinear over the four texels around it (the packed texture cannot be filtered by the GPU). -float hBil(vec2 p) { - ivec2 i = ivec2(floor(p)); - vec2 f = fract(p); - return mix(mix(hAt(i), hAt(i + ivec2(1, 0)), f.x), mix(hAt(i + ivec2(0, 1)), hAt(i + ivec2(1, 1)), f.x), f.y); -}`; - -export const GRID_VERT = `${HEADER} -layout(location = 0) in vec2 a_uv; -uniform mat4 uViewProj; -uniform float uSpan; -out vec2 v_uv; -out vec3 v_world; -${FETCH} -void main() { - // The grid is packed toward the centre, where the camera stands (terrainWorld.warpUv): s = 2u - 1, 0.5 + 0.5 (0.5 s + 0.5 s |s|). - vec2 s = a_uv * 2.0 - 1.0; - vec2 uv = 0.5 + 0.5 * (0.5 * s + 0.5 * s * abs(s)); - // The patch's rim sinks to zero so the grid has no cliff edge to show through the haze. - float rim = 1.0 - smoothstep(0.78, 1.0, 2.0 * max(abs(uv.x - 0.5), abs(uv.y - 0.5))); - float h = hBil(uv * float(uTex - 1)) * rim; - v_uv = uv; - v_world = vec3((uv.x - 0.5) * uSpan, h, (uv.y - 0.5) * uSpan); - gl_Position = uViewProj * vec4(v_world, 1.0); -}`; - -// Lit by the baked sky: uSun (direction), uSunColour (linear, zero when the sun is down), uAmbient; hazed toward the -// scattered sky at the horizon in the ray's azimuth (SKY_COLOUR_GLSL). -// The same arithmetic as terrainSky.shade(); the normal comes from the height map so shading carries detail finer than the mesh. -const ALBEDO_DEFINES = ` -#define ALB_SCREE_FROM ${lit(ALBEDO.screeFrom)} -#define ALB_SCREE_TO ${lit(ALBEDO.screeTo)} -#define ALB_SNOW_BAND ${lit(ALBEDO.snowBand)} -#define ALB_ROCK_HI ${lit(ALBEDO.rockHi)} -#define ALB_ROCK_LO ${lit(ALBEDO.rockLo)} -#define ALB_SNOW_HI ${lit(ALBEDO.snowHi)} -#define ALB_SNOW_LO ${lit(ALBEDO.snowLo)} -#define ALB_WOBBLE_H ${lit(ALBEDO.wobbleHeight)} -#define ALB_WOBBLE_S ${lit(ALBEDO.wobbleSlope)} -#define ALB_GRAIN_COARSE ${lit(ALBEDO.grainCoarse)} -#define ALB_GRAIN_FINE ${lit(ALBEDO.grainFine)} -#define ALB_FINE_WARP ${lit(ALBEDO.fineWarp)} -#define ALB_STRATA ${lit(ALBEDO.strata)} -#define ALB_FINE_NEAR ${lit(ALBEDO.fineNear)} -#define ALB_FINE_FAR ${lit(ALBEDO.fineFar)} -#define CAV_RADIUS ${lit(CAVITY.radius)} -#define CAV_RANGE ${lit(CAVITY.range)} -#define CAV_DARK ${lit(CAVITY.dark)} -#define CAV_LIGHT ${lit(CAVITY.light)} -`; -// The GLSL twin of skyBand.shapeToBand: clamp to 0..1, mix toward uLift to land on the floor uBand.x, or scale down to the ceiling uBand.y. -// No band is uBand = (0, 1). -export const SHAPE_SKY_GLSL = ` -uniform vec2 uBand; -uniform vec3 uLift; -const vec3 LUMA = vec3(${LUMA.map(lit).join(', ')}); -vec3 shapeSky(vec3 c) { - c = clamp(c, 0.0, 1.0); - float l = dot(c, LUMA); - if (l < uBand.x) return mix(c, uLift, (uBand.x - l) / (dot(uLift, LUMA) - l)); - if (l > uBand.y) return c * (uBand.y / l); - return c; -}`; -// The sky colour along a unit direction: scattering lifted by the exposure, tone-mapped, plus the night glow, shaped into -// the state's luminance band. The same arithmetic as terrainSky.skyColour(). uGlow is the baked horizon colour already -// scaled by how dark the sun is. -const SKY_COLOUR_GLSL = `${SCATTER_GLSL}${SHAPE_SKY_GLSL} -uniform vec3 uGlow; -vec3 skyColour(vec3 d) { - return shapeSky(1.0 - exp(-${lit(SKY_EXPOSURE)} * skyScatter(d)) + uGlow * mix(1.0, ${lit( - GLOW_ZENITH -)}, sqrt(clamp(d.y, 0.0, 1.0)))); -}`; - -export const GRID_FRAG = `${HEADER}${ALBEDO_DEFINES}${SKY_COLOUR_GLSL}${AERIAL_GLSL} -in vec2 v_uv; -in vec3 v_world; -uniform vec3 uCamera, uLightDir, uLight, uAmbient, uSoil, uScree, uRock, uSnow; -uniform float uSpan, uSnowLine, uNight, uMoonIndex; -out vec4 o; -${FETCH} -// Triplanar patterns: each projection plane's value, blended by the weights of the face's normal (terrainAlbedo.triWeights). -float wob2(vec2 q) { return sin(q.x * 0.043 + q.y * 0.017) * sin(q.y * 0.051 - q.x * 0.023); } -float waves3(vec2 q, vec2 a, vec2 b, vec2 c) { return (sin(dot(q, a)) + sin(dot(q, b)) + sin(dot(q, c))) / 3.0; } -// The fine octave's coordinates pushed by a slower sine each (terrainAlbedo wavesWarped): three plane waves alone make a regular lattice. -vec2 warpq(vec2 q) { return q + ALB_FINE_WARP * vec2(sin(q.y * 0.55 + 1.3), sin(q.x * 0.47 + 0.7)); } -void main() { - // Normal from the bilinear height at a continuous position, a stencil 1.5 texels each side: smooth across texel borders. - vec2 p = v_uv * float(uTex - 1); - float texel = uSpan / float(uTex - 1); - float dx = hBil(p + vec2(1.5, 0.0)) - hBil(p - vec2(1.5, 0.0)); - float dz = hBil(p + vec2(0.0, 1.5)) - hBil(p - vec2(0.0, 1.5)); - vec3 n = normalize(vec3(-dx, 3.0 * texel, -dz)); - vec3 tw = pow(abs(n), vec3(4.0)); - tw /= tw.x + tw.y + tw.z; - vec2 qx = v_world.zy, qy = v_world.xz, qz = v_world.xy; - // Procedural albedo, no texture reads; the same arithmetic as terrainAlbedo.albedoAt(). - float w = tw.x * wob2(qx) + tw.y * wob2(qy) + tw.z * wob2(qz); - float h = v_world.y + ALB_WOBBLE_H * w; - float flat_ = n.y + ALB_WOBBLE_S * w; - vec3 ground = mix(uSoil, uScree, smoothstep(ALB_SCREE_FROM, ALB_SCREE_TO, h)); - float snow = smoothstep(uSnowLine - ALB_SNOW_BAND, uSnowLine + ALB_SNOW_BAND, h) * smoothstep(ALB_SNOW_LO, ALB_SNOW_HI, flat_); - float rockW = 1.0 - smoothstep(ALB_ROCK_LO, ALB_ROCK_HI, flat_); - vec3 albedo = mix(mix(ground, uSnow, snow), uRock, rockW); - // Surface grain and rock strata, the same arithmetic as terrainAlbedo.grainAt(). - float coarse = tw.x * waves3(qx, vec2(0.31, 0.27), vec2(-0.22, 0.35), vec2(0.38, -0.12)) + tw.y * waves3(qy, vec2(0.31, 0.27), vec2(-0.22, 0.35), vec2(0.38, -0.12)) + tw.z * waves3(qz, vec2(0.31, 0.27), vec2(-0.22, 0.35), vec2(0.38, -0.12)); - float fine = tw.x * waves3(warpq(qx), vec2(1.1, 0.7), vec2(-0.8, 1.2), vec2(1.3, -0.6)) + tw.y * waves3(warpq(qy), vec2(1.1, 0.7), vec2(-0.8, 1.2), vec2(1.3, -0.6)) + tw.z * waves3(warpq(qz), vec2(1.1, 0.7), vec2(-0.8, 1.2), vec2(1.3, -0.6)); - float near = 1.0 - smoothstep(ALB_FINE_NEAR, ALB_FINE_FAR, length(v_world - uCamera)); - float layers = sin(v_world.y * 0.9 + w * 3.0); - albedo *= max(0.0, 1.0 + ALB_GRAIN_COARSE * coarse + ALB_GRAIN_FINE * near * fine + ALB_STRATA * rockW * layers); - // Cavity: a point lower than its surroundings sits in shade, one higher catches light (terrainAlbedo.cavityAt). Shader-only, from the height map, - // read bilinear at a continuous position so it does not snap to a texel (that made the shading blocks of one texel, 3 m). - float cr = CAV_RADIUS / texel; - float curv = 0.25 * (hBil(p + vec2(cr, 0.0)) + hBil(p - vec2(cr, 0.0)) + hBil(p + vec2(0.0, cr)) + hBil(p - vec2(0.0, cr))) - hBil(p); - float cavity = 1.0 - CAV_DARK * clamp(curv / CAV_RANGE, 0.0, 1.0) + CAV_LIGHT * clamp(-curv / CAV_RANGE, 0.0, 1.0); - vec3 lit = albedo * cavity * (uLight * max(dot(n, uLightDir), 0.0) + uAmbient * (0.5 + 0.5 * n.y)); - vec3 toSurface = v_world - uCamera; - float dist = length(toSurface); - // Aerial perspective (terrainSky.aerialPerspective): the baked volume by this ray's elevation, azimuth from the light and path. - vec3 ray = toSurface / dist; - float el = min(degrees(asin(clamp(ray.y, -1.0, 1.0))), 0.0); - vec2 hz = ray.xz, sz = uSun.xz; - float az = (length(hz) < 1e-4 || length(sz) < 1e-4) ? 0.0 : degrees(acos(clamp(dot(normalize(hz), normalize(sz)), -1.0, 1.0))); - float km = dist * ${lit(AP_DISTANCE_SCALE / 1000)}; - vec4 ap = aerial(uSunIndex, el, az, km); - vec3 L = ap.rgb; - // The moon lights the haze from where the sun is mirrored above the horizon, sharing its azimuth; a starlight floor stays. - if (uNight > 0.0) L += uNight * vec3(${MOON_HAZE.map(lit).join( - ', ' - )}) * aerial(uMoonIndex, el, az, km).rgb; - vec3 haze = 1.0 - exp(-${lit(SKY_EXPOSURE)} * L) + uNight * ap.a * vec3(${STAR_FLOOR.map( - lit -).join(', ')}); - // Past SKY_FADE the surface is the sky at the horizon in this ray's azimuth, the colour the sky pass draws there (terrainSky.aerialPerspective). - float toSky = smoothstep(${lit(SKY_FADE[0])}, ${lit(SKY_FADE[1])}, dist); - vec3 horizon = skyColour(vec3(ray.x, 0.0, ray.z)); - o = vec4(pow(mix(lit * (1.0 - ap.a) + haze, horizon, toSky), vec3(1.0 / 2.2)), 1.0); -}`; - -// The sky behind: the baked scattering tables by the view ray's elevation and azimuth from the sun, a sun disc, and a -// dither of +-0.5/255 on the 8-bit output so the dusk glow does not band. -const DISC = { - inner: Math.cos((0.5 * Math.PI) / 180), - outer: Math.cos((1.1 * Math.PI) / 180), - gain: 6.0, -}; -export const SKY_FRAG = `${HEADER}${SKY_COLOUR_GLSL} -uniform vec3 uSunColour; -uniform vec3 uRight, uUp, uForward; -uniform vec2 uSize; -uniform float uTanHalf; -out vec4 o; -void main() { - vec2 ndc = gl_FragCoord.xy / uSize * 2.0 - 1.0; - vec3 d = normalize(uForward + ndc.x * uTanHalf * uSize.x / uSize.y * uRight + ndc.y * uTanHalf * uUp); - vec3 c = skyColour(d) + uSunColour * ${lit(DISC.gain)} * smoothstep(${DISC.outer}, ${ - DISC.inner -}, dot(d, uSun)); - float dither = fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715)))) - 0.5; - o = vec4(pow(c, vec3(1.0 / 2.2)) + dither / 255.0, 1.0); -}`; diff --git a/src/app/features/scene/terrain/terrainSky.test.ts b/src/app/features/scene/terrain/terrainSky.test.ts deleted file mode 100644 index f409471a..00000000 --- a/src/app/features/scene/terrain/terrainSky.test.ts +++ /dev/null @@ -1,322 +0,0 @@ -/* eslint-disable no-restricted-syntax -- tests loop over skies, normals and distances */ -import { AP_DISTANCE_SCALE } from './terrainScatter'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { baked } from '../../../../sky/baked'; -import { - chooseSky, - coldness, - glowColour, - hazeColour, - hexToLinear, - nightness, - shade, - SKY, - skyAtSun, - skyData, - skyColour, - sunDirection, - aerialPerspective, - SKY_FADE, - metresToKm, - groundLight, - HAZE_K, - HAZE_POWER, - START_TURNS, - Vec3, -} from './terrainSky'; - -const UP = [0, 1, 0] as const; -const luma = (c: readonly number[]) => 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]; -/** Unit view direction at an elevation (degrees) and an azimuth clockwise from north. */ -const look = (el: number, az: number): Vec3 => { - const e = (el * Math.PI) / 180; - const a = (az * Math.PI) / 180; - return [Math.sin(a) * Math.cos(e), Math.sin(e), -Math.cos(a) * Math.cos(e)]; -}; - -describe('the baked sky is read, not copied', () => { - it('SKY carries Void’s numbers: sun, ambient, horizon', () => { - for (const name of ['midnight', 'noonday'] as const) { - const b = baked[name]; - expect(SKY[name].elevation).toBe(b.sun.elevation_deg); - expect(SKY[name].azimuth).toBe(b.sun.azimuth_deg); - expect(SKY[name].direct).toEqual(b.sun.color_linear); - expect(SKY[name].ambient).toEqual(b.ambient_linear); - expect(SKY[name].horizon).toEqual(hexToLinear(b.horizon_hex)); - } - }); - - it('keeps the two moments apart: night sun below the horizon, noon sun well above', () => { - expect(SKY.midnight.elevation).toBeLessThan(0); - expect(SKY.noonday.elevation).toBeGreaterThan(30); - }); - - it('sunDirection is a unit vector with y = sin(elevation), north at -z, south at +z', () => { - for (const d of Object.values(SKY)) { - const s = sunDirection(d); - expect(Math.hypot(...s)).toBeCloseTo(1, 9); - expect(s[1]).toBeCloseTo(Math.sin((d.elevation * Math.PI) / 180), 9); - } - expect(sunDirection({ ...SKY.noonday, elevation: 0, azimuth: 0 })[2]).toBeCloseTo(-1, 9); - expect(sunDirection({ ...SKY.noonday, elevation: 0, azimuth: 180 })[2]).toBeCloseTo(1, 9); - }); - - it('hexToLinear decodes sRGB', () => { - expect(hexToLinear('#000000')).toEqual([0, 0, 0]); - expect(hexToLinear('#ffffff')).toEqual([1, 1, 1]); - expect(hexToLinear('#808080')[0]).toBeCloseTo(0.2158, 3); - }); -}); - -describe('a sun at any elevation (skyAtSun)', () => { - it('lights nothing under the horizon and fades in across the last degrees, as sun.js does', () => { - expect(skyAtSun(-2).direct).toEqual([0, 0, 0]); - expect(skyAtSun(-30).direct).toEqual([0, 0, 0]); - const at = (e: number) => luma(skyAtSun(e).direct); - expect(at(0.3)).toBeGreaterThan(0); - expect(at(0.3)).toBeLessThan(at(1.5)); - expect(at(1.5)).toBeLessThan(at(60)); - }); - - it('agrees with the baked noon sun colour where they overlap, to a couple of percent', () => { - const want = SKY.noonday.direct; - const got = skyAtSun(SKY.noonday.elevation).direct; - got.forEach((v, i) => expect(Math.abs(v / want[i] - 1)).toBeLessThan(0.02)); - }); - - it('the sun goes red as it sets: less blue left in the direct light at 2 degrees than at 45', () => { - const lo = skyAtSun(2).direct; - const hi = skyAtSun(45).direct; - expect(lo[2] / lo[0]).toBeLessThan(0.6 * (hi[2] / hi[0])); - }); - - it('ambient and horizon run from the midnight bake to the noonday one as the sun climbs', () => { - expect(luma(skyAtSun(-30).ambient)).toBeCloseTo(luma(SKY.midnight.ambient), 9); - expect(luma(skyAtSun(60).ambient)).toBeCloseTo(luma(SKY.noonday.ambient), 9); - expect(luma(skyAtSun(5).ambient)).toBeGreaterThan(luma(SKY.midnight.ambient)); - expect(luma(skyAtSun(5).ambient)).toBeLessThan(luma(SKY.noonday.ambient)); - expect(skyAtSun(10, 270).azimuth).toBe(270); - }); -}); - -describe('lighting', () => { - it('noonday lights an upward face with the sun; midnight has none', () => { - expect(luma(SKY.noonday.direct)).toBeGreaterThan(0.5); - expect(SKY.midnight.direct).toEqual([0, 0, 0]); - }); - - it('shade never goes negative on any normal at either sky, at any distance', () => { - for (const d of [...Object.values(SKY), skyAtSun(-3), skyAtSun(1)]) - for (const n of [UP, [0, -1, 0], [1, 0, 0], [-0.6, 0.0, 0.8]] as const) - for (const dist of [0, 100, 5000]) - for (const ch of shade(d, [0.3, 0.3, 0.3], n, dist, look(-5, 40))) - expect(ch).toBeGreaterThanOrEqual(0); - }); - - it('a face turned to the noon sun is brighter than one turned away; at midnight the two match to ambient', () => { - const toSun = sunDirection(SKY.noonday); - const away = [-toSun[0], 0, -toSun[2]] as const; - const view = look(-5, 0); - const lit = luma(shade(SKY.noonday, [0.5, 0.5, 0.5], toSun, 0, view)); - const dark = luma(shade(SKY.noonday, [0.5, 0.5, 0.5], away, 0, view)); - expect(lit).toBeGreaterThan(3 * dark); - const m = (n: readonly [number, number, number]) => - shade(SKY.midnight, [0.5, 0.5, 0.5], n, 0, view); - expect(luma(m(UP))).toBeGreaterThan(0); // moonlit fill, not black - expect(luma(m(UP))).toBeLessThan(0.12); - }); - - it('noon is much brighter than midnight, ambient included', () => { - expect(luma(SKY.noonday.ambient)).toBeGreaterThan(2 * luma(SKY.midnight.ambient)); - const view = look(-5, 0); - expect(luma(shade(SKY.noonday, [0.4, 0.4, 0.4], UP, 0, view))).toBeGreaterThan( - 3 * luma(shade(SKY.midnight, [0.4, 0.4, 0.4], UP, 0, view)) - ); - }); - - it('the cold tint (albedo) is 0 with the sun up and 1 once it is below -6', () => { - expect(coldness(SKY.noonday)).toBe(0); - expect(coldness(SKY.midnight)).toBe(1); - expect(hazeColour(SKY.noonday)).toEqual(SKY.noonday.horizon); - }); -}); - -describe('the scattered sky', () => { - it('noon is blue overhead: more blue than red, much brighter than the night glow', () => { - const zenith = skyColour(SKY.noonday, [0, 1, 0]); - expect(zenith[2]).toBeGreaterThan(1.5 * zenith[0]); - expect(luma(zenith)).toBeGreaterThan(5 * luma(skyColour(SKY.midnight, [0, 1, 0]))); - zenith.forEach((v) => expect(v).toBeLessThan(1)); - }); - - it('a sun at the horizon reddens the sky toward it and darkens it away', () => { - const dusk = skyAtSun(-1, 270); - const toward = skyColour(dusk, look(3, 270)); - const away = skyColour(dusk, look(3, 90)); - const blueShare = (c: Vec3) => c[2] / (c[0] + c[1] + c[2]); - expect(blueShare(toward)).toBeLessThan(blueShare(away)); - expect(luma(toward)).toBeGreaterThan(3 * luma(away)); - }); - - it('under a deep night sun the tables are black and only the glow remains, brightest at the horizon', () => { - const d = SKY.midnight; - const horizon = skyColour(d, look(0, 180)); - const zenith = skyColour(d, [0, 1, 0]); - horizon.forEach((v, i) => expect(v).toBeCloseTo(d.horizon[i], 6)); - expect(luma(zenith)).toBeLessThan(luma(horizon)); - expect(luma(zenith)).toBeGreaterThan(0.5 * luma(horizon)); - }); - - it('the night glow fades out as the sun reaches the horizon', () => { - expect(nightness(-10)).toBe(1); - expect(nightness(5)).toBe(0); - expect(glowColour(SKY.noonday)).toEqual([0, 0, 0]); - expect(glowColour(SKY.midnight)).toEqual(SKY.midnight.horizon); - expect(luma(glowColour(skyAtSun(-2)))).toBeLessThan(luma(glowColour(skyAtSun(-6)))); - }); - - it('is continuous in the sun’s elevation through dusk: no step between neighbours', () => { - const at = (e: number) => luma(skyColour(skyAtSun(e, 270), look(10, 200))); - for (let e = -20; e < 30; e += 0.5) { - expect(Math.abs(at(e + 0.5) - at(e))).toBeLessThan(0.05); - } - }); -}); - -describe('aerial perspective', () => { - const ray = (el: number, az: number): Vec3 => look(el, az); - const along = (d: typeof SKY.midnight, el: number, az: number, m: number) => - aerialPerspective(d, ray(el, az), m); - - it('opacity grows with distance from nothing at the eye toward the far value, never past 1', () => { - let prev = along(SKY.noonday, -2, 200, 0).alpha; - expect(prev).toBe(0); - for (const m of [10, 100, 400, 800, 1000, 1300]) { - const a = along(SKY.noonday, -2, 200, m).alpha; - expect(a).toBeGreaterThan(prev); - expect(a).toBeLessThanOrEqual(1); - prev = a; - } - }); - - it('leaves the near ground its own colour and takes the far ridges', () => { - expect(along(SKY.noonday, -2, 200, 100).alpha).toBeLessThan(0.15); - expect(along(SKY.noonday, -2, 200, SKY_FADE[0]).alpha).toBeGreaterThan(0.1); - }); - - it('the in-scatter is a function of the baked volume: its colour is bluer than the sun far by day', () => { - const far = along(SKY.noonday, -2, 90, SKY_FADE[0]).colour; - expect(far[2]).toBeGreaterThan(far[0]); - }); - - it('haze toward a setting sun is brighter than away from it, and red, not blue (the sun is reddened on its way)', () => { - const dusk = skyAtSun(2, 270); - const toward = along(dusk, -1, 270, SKY_FADE[0]).colour; - const away = along(dusk, -1, 90, SKY_FADE[0]).colour; - expect(luma(toward)).toBeGreaterThan(3 * luma(away)); - expect(toward[0]).toBeGreaterThan(toward[2]); - }); - - it('night haze is a deep blue floor, not grey: dark, blue over red by a wide margin, brighter than black', () => { - const c = along(SKY.midnight, -2, 0, SKY_FADE[0]).colour; - expect(luma(c)).toBeGreaterThan(0.0003); - expect(luma(c)).toBeLessThan(0.08); - expect(c[2]).toBeGreaterThan(2.5 * c[0]); - expect(luma(along(SKY.noonday, -2, 0, SKY_FADE[0]).colour)).toBeGreaterThan(5 * luma(c)); - }); - - it('moonlight lights the night haze toward the moon more than away from it', () => { - const moon = groundLight(SKY.midnight).dir; - const toward = aerialPerspective(SKY.midnight, [moon[0], -0.02, moon[2]], SKY_FADE[0]).colour; - const away = aerialPerspective(SKY.midnight, [-moon[0], -0.02, -moon[2]], SKY_FADE[0]).colour; - expect(luma(toward)).toBeGreaterThan(luma(away)); - }); - - it('with distance a dark surface rises toward the haze and its own colour is lost', () => { - const d = SKY.noonday; - const view = ray(-4, 200); - const dark = (x: number) => luma(shade(d, [0.02, 0.02, 0.02], UP, x, view)); - expect(dark(SKY_FADE[0])).toBeGreaterThan(dark(100)); - const own = (x: number) => 1 - aerialPerspective(d, view, x).alpha; - expect(own(SKY_FADE[0])).toBeLessThan(0.9 * own(100)); - }); - - it('is continuous in the sun elevation through dusk: no step between neighbours', () => { - const at = (e: number) => luma(along(skyAtSun(e, 270), -1, 270, SKY_FADE[0]).colour); - for (let e = -12; e < 12; e += 0.5) expect(Math.abs(at(e + 0.5) - at(e))).toBeLessThan(0.45); - }); - - it('far terrain is the sky: past the fade it is the horizon sky colour in its azimuth, by day, dusk and night, whatever it was', () => { - for (const [d, az] of [ - [SKY.midnight, 0], - [skyAtSun(-1, 90), 90], - [skyAtSun(2, 270), 200], - [SKY.noonday, 120], - ] as const) { - const view = ray(-0.5, az); - const hz = skyColour(d, [view[0], 0, view[2]]); - const far = aerialPerspective(d, view, SKY_FADE[1]); - expect(far.alpha).toBe(1); - for (let i = 0; i < 3; i += 1) expect(far.colour[i]).toBeCloseTo(hz[i], 9); - expect(shade(d, [0.5, 0.5, 0.5], UP, SKY_FADE[1] + 500, view)).toEqual(far.colour); - } - }); - - it('the metres-to-km law is the scene metres times the baked distance scale', () => { - expect(metresToKm(1000)).toBeCloseTo(AP_DISTANCE_SCALE, 9); - expect(metresToKm(-5)).toBe(0); - }); -}); - -describe('ground light and haze', () => { - it("at night the ground has a moon above the horizon on the sun's mirrored side, and a lifted ambient; by day it is the sun", () => { - const night = groundLight(SKY.midnight); - expect(night.dir[1]).toBeGreaterThan(0.5); - expect(luma(night.colour)).toBeGreaterThan(0.03); - expect(luma(night.ambient)).toBeGreaterThan(2 * luma(SKY.midnight.ambient)); - const day = groundLight(SKY.noonday); - expect(Array.from(day.dir)).toEqual(Array.from(sunDirection(SKY.noonday))); - expect(Array.from(day.colour)).toEqual(Array.from(SKY.noonday.direct)); - expect(Array.from(day.ambient)).toEqual(Array.from(SKY.noonday.ambient)); - }); - - it('the ground light is continuous through sunset', () => { - const at = (e: number) => luma(groundLight(skyAtSun(e)).colour); - for (let e = -10; e < 10; e += 0.5) expect(Math.abs(at(e + 0.5) - at(e))).toBeLessThan(0.35); - }); - - it('the camera starts with the noon sun off its axis, so the light rakes the relief', () => { - const yaw = 2 * Math.PI * START_TURNS; - const forward = [Math.sin(yaw), 0, -Math.cos(yaw)]; - const sun = sunDirection(SKY.noonday); - const along = (forward[0] * sun[0] + forward[2] * sun[2]) / Math.hypot(sun[0], sun[2]); - expect(Math.abs(along)).toBeLessThan(0.4); - }); -}); - -describe('chooseSky: an explicit sky wins over the page URL', () => { - const at = (search: string) => vi.stubGlobal('window', { location: { search } }); - afterEach(() => { - vi.unstubAllGlobals(); - }); - - it('lets the URL steer when no option is given', () => { - at('?sun=40&az=90'); - expect(chooseSky({})).toEqual(skyAtSun(40, 90)); - at('?sky=noonday'); - expect(chooseSky({})).toEqual(skyData('noonday')); - }); - - it('prefers an explicit baked sky to ?sun= and ?sky=', () => { - at('?sun=40&az=90&sky=noonday'); - expect(chooseSky({ sky: 'midnight' })).toEqual(skyData('midnight')); - at('?sky=noonday'); - expect(chooseSky({ sky: 'midnight' })).toEqual(skyData('midnight')); - }); - - it('prefers an explicit sun to ?sun=, and takes no azimuth from ?az=', () => { - at('?sun=40&az=90&sky=noonday'); - expect(chooseSky({ sun: { elevation: 2 } })).toEqual(skyAtSun(2, undefined)); - expect(chooseSky({ sun: { elevation: 2, azimuth: 10 } })).toEqual(skyAtSun(2, 10)); - }); -}); diff --git a/src/app/features/scene/terrain/terrainSky.ts b/src/app/features/scene/terrain/terrainSky.ts deleted file mode 100644 index 92a2ab22..00000000 --- a/src/app/features/scene/terrain/terrainSky.ts +++ /dev/null @@ -1,253 +0,0 @@ -// Lighting, haze and sky for the terrain scene, as pure functions of one sky's baked numbers (src/sky/baked.ts, Void's -// bake, GameCult/Void PR #22). No DOM, no GL. The fragment shaders do the same arithmetic with these results as uniforms. -import { baked } from '../../../../sky/baked'; -import { hexToLinear, shapeToBand } from '../skyBand'; -import type { SkyBand } from '../skyBand'; -import { - AP_DISTANCE_SCALE, - aerialAt, - HORIZON_FLOOR, - scatterRadiance, - transmittanceAt, -} from './terrainScatter'; - -export type SkyName = 'midnight' | 'noonday'; -export type Vec3 = readonly [number, number, number]; - -export interface SkyData { - /** Degrees above the horizon, no refraction. Negative: the sun is down. */ - elevation: number; - /** Degrees clockwise from north. */ - azimuth: number; - /** Sun colour at normal incidence, linear RGB. Black when the sun is down. */ - direct: Vec3; - /** Sky ambient on an upward surface, linear RGB; at night a moonlit floor, not black. */ - ambient: Vec3; - /** The horizon, linear RGB: the baked `horizon_hex`. */ - horizon: Vec3; - /** The luminance band `skyColour` shapes the sky into (skyBand.ts); absent: the physical sky as it is. */ - band?: SkyBand; -} - -const RAD = Math.PI / 180; -const clamp01 = (x: number) => Math.min(1, Math.max(0, x)); -const smooth = (a: number, b: number, x: number) => { - const t = clamp01((x - a) / (b - a)); - return t * t * (3 - 2 * t); -}; -const mixVec = (a: Vec3, b: Vec3, t: number): Vec3 => - [0, 1, 2].map((i) => a[i] + (b[i] - a[i]) * t) as unknown as Vec3; - -export const isSkyName = (s: unknown): s is SkyName => s === 'midnight' || s === 'noonday'; - -export { hexToLinear }; - -const fromBaked = (b: typeof baked.midnight | typeof baked.noonday): SkyData => ({ - elevation: b.sun.elevation_deg, - azimuth: b.sun.azimuth_deg, - direct: b.sun.color_linear, - ambient: b.ambient_linear, - horizon: hexToLinear(b.horizon_hex), -}); - -export const SKY: Record = { - midnight: fromBaked(baked.midnight), - noonday: fromBaked(baked.noonday), -}; - -export const skyData = (name: SkyName): SkyData => SKY[name]; - -/** - * A sky for a sun at any elevation, between the two baked ones. The sun's colour is the baked transmittance at - * that elevation, faded out across the disc's last degrees the way sun.js does (gone at -0.83, whole by 1.5); - * ambient and horizon blend from the midnight bake to the noonday one as the sun climbs from -8 to 25 degrees. - */ -export function skyAtSun(elevation: number, azimuth: number = SKY.noonday.azimuth): SkyData { - const day = smooth(-8, 25, elevation); - const fade = smooth(-0.83, 1.5, elevation); - const t = transmittanceAt(Math.max(elevation, -4)); - return { - elevation, - azimuth, - direct: [t[0] * fade, t[1] * fade, t[2] * fade], - ambient: mixVec(SKY.midnight.ambient, SKY.noonday.ambient, day), - horizon: mixVec(SKY.midnight.horizon, SKY.noonday.horizon, day), - }; -} - -/** Unit vector toward the sun: x east, y up, z south (so azimuth 0, north, is -z). */ -export function sunDirection(d: SkyData): Vec3 { - const el = d.elevation * RAD; - const az = d.azimuth * RAD; - return [Math.sin(az) * Math.cos(el), Math.sin(el), -Math.cos(az) * Math.cos(el)]; -} - -/** 0 with the sun well up, 1 once it is below -6 degrees (civil twilight over): the night notion the palette shares. */ -export const coldness = (d: SkyData): number => 1 - smooth(-6, 25, d.elevation); - -/** The colour distance fades to when the air has nothing to scatter: the baked horizon. Albedo tints toward it at night. */ -export const hazeColour = (d: SkyData): Vec3 => d.horizon; - -/** Sky radiance (see the sun's `skyScatter` in terrainScatter.ts) is for unit sun irradiance; this lifts it to the image. EYEBALLED. */ -export const SKY_EXPOSURE = 45; -/** How far the night glow dims from the horizon to the zenith (1 at the horizon). EYEBALLED. */ -export const GLOW_ZENITH = 0.75; - -/** 1 with the sun below -4 degrees, 0 above 4: where the midnight horizon colour stands in for light the single-scattering tables lack. */ -export const nightness = (elevation: number): number => 1 - smooth(-4, 4, elevation); - -/** The night glow colour: the midnight bake's horizon, fading out as the sun nears the horizon (whatever horizon the day blend gives `d`). */ -export const glowColour = (d: SkyData): Vec3 => { - const k = nightness(d.elevation); - const h = SKY.midnight.horizon; - return [h[0] * k, h[1] * k, h[2] * k]; -}; - -/** - * Linear colour of the sky along a unit view direction (x east, y up, z south): the baked single-scattering - * radiance for this sun, lifted by SKY_EXPOSURE and tone-mapped `1 - exp(-x)`, plus the night glow, which sits - * brightest at the horizon; at and below the horizon, the horizon's colour; then shaped into `d.band` when it has one. - * The fragment shader does the same. - */ -export function skyColour(d: SkyData, dir: Vec3): Vec3 { - const el = Math.max(HORIZON_FLOOR, Math.asin(Math.min(1, Math.max(-1, dir[1]))) / RAD); - const sun = sunDirection(d); - const h = Math.hypot(dir[0], dir[2]); - const s = Math.hypot(sun[0], sun[2]); - const az = - h < 1e-4 || s < 1e-4 - ? 0 - : Math.acos(Math.min(1, Math.max(-1, (dir[0] * sun[0] + dir[2] * sun[2]) / (h * s)))) / RAD; - const r = scatterRadiance(d.elevation, el, az); - const glow = glowColour(d); - const shape = 1 + (GLOW_ZENITH - 1) * Math.sqrt(clamp01(dir[1])); - const c = [0, 1, 2].map( - (i) => 1 - Math.exp(-SKY_EXPOSURE * r[i]) + glow[i] * shape - ) as unknown as Vec3; - return d.band ? shapeToBand(c, d.band) : c; -} - -/** - * Aerial perspective: the baked volume of src/sky/scatter.js (after Hillaire 2020, see there for what follows the paper - * and what does not), looked up by the view ray relative to the light and the metres to the surface. The surface keeps - * (1 - alpha) of its own colour (alpha = 1 - mean transmittance, a grey transmittance as the paper) and gains the in-scatter L, - * lifted by the sky's exposure and tone-mapped the way the sky is, so far ground meets the sky's colour. SHORTCUT: the path is - * the scene's metres times AP_DISTANCE_SCALE (a real atmosphere is nearly clear over 3 km). - */ -export const metresToKm = (metres: number): number => - (Math.max(0, metres) / 1000) * AP_DISTANCE_SCALE; - -/** Moonlight's irradiance on the haze, relative to the sun's 1, at full night. EYEBALLED, far above a real moon (about 3e-6) as the sky exposure is. */ -export const MOON_HAZE: Vec3 = [0.0004, 0.0007, 0.0018]; -/** Starlight and airglow scattered by the air, added to the in-scatter in proportion to alpha, at full night: a deep blue floor, not grey. EYEBALLED. */ -export const STAR_FLOOR: Vec3 = [0.0006, 0.0012, 0.0045]; - -/** - * Metres from the eye over which the terrain gives itself up to the sky: past the far end a surface is the sky's own - * colour at the horizon in its azimuth (`skyColour` flat along the horizon, night glow included), so the patch's rim - * meets the sky above and beyond it with no seam. The volume alone is only ~40% opaque by then. EYEBALLED. - */ -export const SKY_FADE: readonly [number, number] = [600, 1350]; - -/** Haze in front of a surface seen along `dir` (unit, eye to surface) `distance` metres away: the colour it adds and the surface's loss. */ -export function aerialPerspective( - d: SkyData, - dir: Vec3, - distance: number -): { colour: Vec3; alpha: number } { - const el = Math.min(0, Math.asin(Math.min(1, Math.max(-1, dir[1]))) / RAD); - const sun = sunDirection(d); - const h = Math.hypot(dir[0], dir[2]); - const s = Math.hypot(sun[0], sun[2]); - const az = - h < 1e-4 || s < 1e-4 - ? 0 - : Math.acos(Math.min(1, Math.max(-1, (dir[0] * sun[0] + dir[2] * sun[2]) / (h * s)))) / RAD; - const km = metresToKm(distance); - const night = nightness(d.elevation); - const day = aerialAt(d.elevation, el, az, km); - const L = [...day.L]; - if (night > 0) { - // The moon stands where the sun is mirrored above the horizon (groundLight), so it shares the sun's azimuth. - const moon = aerialAt(Math.abs(d.elevation), el, az, km); - for (let i = 0; i < 3; i += 1) L[i] += MOON_HAZE[i] * night * moon.L[i]; - } - const horizon = skyColour(d, [dir[0], 0, dir[2]]); - const f = smooth(SKY_FADE[0], SKY_FADE[1], distance); - const colour = [0, 1, 2].map( - (i) => - (1 - f) * (1 - Math.exp(-SKY_EXPOSURE * L[i]) + STAR_FLOOR[i] * night * day.alpha) + - f * horizon[i] - ) as unknown as Vec3; - return { colour, alpha: (1 - f) * day.alpha + f }; -} - -/** Added to the ambient on a dark sky, scaled by `nightness`: the baked night floor is too dark to show any form on a phone. */ -export const NIGHT_AMBIENT_LIFT = 3; -/** Cool light from the mirror of the sun's below-horizon position, linear, scaled by `nightness`: gives the terrain a lit side at night. */ -export const MOON_COLOUR: Vec3 = [0.05, 0.07, 0.13]; - -/** The light on the ground: the sun, or at night the moon standing where the sun is mirrored above the horizon. Continuous through sunset. */ -export function groundLight(d: SkyData): { dir: Vec3; colour: Vec3; ambient: Vec3 } { - const sun = sunDirection(d); - const k = nightness(d.elevation); - return { - dir: [sun[0], Math.abs(sun[1]), sun[2]], - colour: [0, 1, 2].map((i) => d.direct[i] + MOON_COLOUR[i] * k) as unknown as Vec3, - ambient: [0, 1, 2].map((i) => d.ambient[i] * (1 + NIGHT_AMBIENT_LIFT * k)) as unknown as Vec3, - }; -} - -/** - * The heading the camera starts at, in turns from north: the noonday sun a hundred degrees to its right, so the light - * rakes across the relief instead of flattening it from behind. Fixed, so `?az=` still moves the sun in the picture. - */ -export const START_TURNS = ((SKY.noonday.azimuth - 100) / 360 + 1) % 1; - -/** - * Linear colour of a surface seen along the unit direction `view` (from the eye to the surface): lambert from - * the ground light plus ambient (full on an upward face, half on a vertical one, none on a downward one: `0.5 + 0.5 n.y`), - * then aerial perspective (`aerialPerspective`). `normal` is a unit vector. Never negative. - */ -export function shade(d: SkyData, albedo: Vec3, normal: Vec3, distance: number, view: Vec3): Vec3 { - const light = groundLight(d); - const sun = light.dir; - const lambert = Math.max(0, normal[0] * sun[0] + normal[1] * sun[1] + normal[2] * sun[2]); - const hemi = 0.5 + 0.5 * normal[1]; - const haze = aerialPerspective(d, view, distance); - return [0, 1, 2].map((i) => { - const lit = albedo[i] * (light.colour[i] * lambert + light.ambient[i] * Math.max(0, hemi)); - return lit * (1 - haze.alpha) + haze.colour[i]; - }) as unknown as Vec3; -} - -/** What the page URL asks of the sky, if anything: `?sun=` (with `?az=`) wins over `?sky=midnight|noonday`; a bad value asks nothing. */ -export function urlSky(): - | { sky?: SkyName; sun?: { elevation: number; azimuth?: number } } - | undefined { - const q = new URLSearchParams(window.location.search); - const number = (key: string) => (q.get(key)?.trim() ? Number(q.get(key)) : NaN); - const elevation = number('sun'); - if (Number.isFinite(elevation)) { - const azimuth = number('az'); - return { sun: { elevation, azimuth: Number.isFinite(azimuth) ? azimuth : undefined } }; - } - const name = q.get('sky'); - return isSkyName(name) ? { sky: name } : undefined; -} - -/** - * The sky to use. An explicit option wins over the page URL, so a person who picked a sky sees it: a sun - * elevation (with its azimuth, default noonday's), else a baked sky. Only without either does the URL steer - * (`urlSky`), else midnight. A band, when given, shapes whichever sky that is. - */ -export function chooseSky(opts: { - sky?: SkyName; - sun?: { elevation: number; azimuth?: number }; - band?: SkyBand; -}): SkyData { - const banded = (d: SkyData): SkyData => (opts.band ? { ...d, band: opts.band } : d); - const want = opts.sun || opts.sky ? opts : urlSky() ?? { sky: 'midnight' as const }; - if (want.sun) return banded(skyAtSun(want.sun.elevation, want.sun.azimuth)); - return banded(skyData(want.sky ?? 'midnight')); -} diff --git a/src/app/features/scene/terrain/terrainStars.test.ts b/src/app/features/scene/terrain/terrainStars.test.ts deleted file mode 100644 index c1231bd8..00000000 --- a/src/app/features/scene/terrain/terrainStars.test.ts +++ /dev/null @@ -1,241 +0,0 @@ -/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-empty-function -- DOM stubs, as the other scene tests */ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { SKY, skyAtSun } from './terrainSky'; -import { - BRIGHTEN, - createTerrainStars, - elevationOf, - ELEVATION_TOP, - FRAME_MS, - horizonY, - PERIOD, - nightColours, - project, - starGain, -} from './terrainStars'; -import { CAMERA, view } from './terrainWorld'; -import { isNight, makeStars } from '../ridge/stars'; - -/** A 2D context that only counts: arcs painted and clears since the last reset. */ -function fakeCtx() { - const c = { - arcs: [] as Array<[number, number, number]>, - clears: 0, - alpha: 1, - alphas: [] as number[], - }; - const ctx: any = { - clearRect: () => { - c.clears += 1; - c.arcs = []; - c.alphas = []; - }, - beginPath() {}, - fill() { - c.alphas.push(ctx.globalAlpha); - }, - arc: (x: number, y: number, r: number) => c.arcs.push([x, y, r]), - globalAlpha: 1, - fillStyle: '', - }; - return { c, ctx }; -} - -let overlay: any; -let ctx2d: ReturnType; -let parent: any; -beforeEach(() => { - ctx2d = fakeCtx(); - overlay = { - style: {}, - width: 0, - height: 0, - setAttribute: vi.fn(), - getContext: vi.fn(() => ctx2d.ctx), - remove: vi.fn(), - }; - parent = { appendChild: vi.fn() }; - vi.stubGlobal('document', { createElement: () => overlay }); - vi.stubGlobal('window', { devicePixelRatio: 1, innerWidth: 390, innerHeight: 844 }); -}); -afterEach(() => vi.unstubAllGlobals()); - -const glCanvas = (w = 390, h = 844) => - ({ clientWidth: w, clientHeight: h, parentElement: parent } as any); - -describe('which skies get stars', () => { - it('the field is placed against the baked night gradient, which the ridge module calls dark', () => { - expect(isNight(nightColours())).toBe(true); - }); - - it('starGain: full below -12 degrees, none above -6, smooth and monotone between', () => { - expect(starGain(-44.6)).toBe(1); - expect(starGain(-12)).toBe(1); - expect(starGain(-6)).toBe(0); - expect(starGain(45.2)).toBe(0); - expect(starGain(-9)).toBeCloseTo(0.5, 9); - let prev = 1; - for (let e = -12; e <= -6; e += 0.25) { - expect(starGain(e)).toBeLessThanOrEqual(prev); - prev = starGain(e); - } - }); - - it('noonday gets no layer and no element', () => { - expect(createTerrainStars(glCanvas(), SKY.noonday)).toBeNull(); - expect(parent.appendChild).not.toHaveBeenCalled(); - }); - - it('twilight is a fade, not a gate: a sun at -9 degrees paints the stars at half alpha', () => { - createTerrainStars(glCanvas(), skyAtSun(-9))?.draw(0); - const half = Math.max(...ctx2d.c.alphas); - ctx2d.c.alphas = []; - createTerrainStars(glCanvas(), SKY.midnight)?.draw(0); - expect(half).toBeGreaterThan(0); - expect(half / Math.max(...ctx2d.c.alphas)).toBeCloseTo(0.5, 6); - expect(createTerrainStars(glCanvas(), skyAtSun(-6.5))).not.toBeNull(); - expect(createTerrainStars(glCanvas(), skyAtSun(-6))).toBeNull(); - }); - - it('midnight adds one overlay to the canvas parent; dispose removes it', () => { - const s = createTerrainStars(glCanvas(), SKY.midnight)!; - expect(parent.appendChild).toHaveBeenCalledWith(overlay); - s.dispose(); - expect(overlay.remove).toHaveBeenCalledOnce(); - }); - - it('is absent without a parent or a 2D context', () => { - expect( - createTerrainStars({ ...glCanvas(), parentElement: null } as any, SKY.midnight) - ).toBeNull(); - overlay.getContext = () => null; - expect(createTerrainStars(glCanvas(), SKY.midnight)).toBeNull(); - expect(parent.appendChild).not.toHaveBeenCalled(); - }); -}); - -describe('sky only', () => { - it('the overlay is as tall as the horizon line is low, never the whole screen', () => { - createTerrainStars(glCanvas(), SKY.midnight); - expect(overlay.height).toBe(Math.ceil(horizonY(844))); - expect(overlay.height).toBeLessThan(844 / 2); - expect(overlay.style.pointerEvents).toBe('none'); - }); - - it('a star at the horizon lands on the horizon line, one above it lands above', () => { - for (const aspect of [0.46, 1.78]) { - const h = 800; - const w = h * aspect; - const onLine = project(0.2, 0, w, h)!; - expect(onLine.y).toBeCloseTo(horizonY(h), 5); - expect(project(0.2, 0.05, w, h)!.y).toBeLessThan(horizonY(h)); - } - }); - - it('the camera eye clears the peaks, so the horizon line bounds the terrain', () => { - expect(CAMERA.eye).toBeGreaterThan(256); - }); - - it('every painted star is above the horizon line, at any heading', () => { - const s = createTerrainStars(glCanvas(), SKY.midnight)!; - for (let k = 0; k < 40; k += 1) { - s.draw(k / 40); - for (const [, y] of ctx2d.c.arcs) expect(y).toBeLessThanOrEqual(overlay.height); - } - }); - - it('agrees with the camera the terrain draws: the projection matches view()', () => { - const w = 390; - const h = 844; - const turns = 0.137; - const v = view(w / h, turns); - const yaw = 2 * Math.PI * turns; - const az = yaw + 0.1; - const e = 0.15; - const d = [Math.sin(az) * Math.cos(e), Math.sin(e), -Math.cos(az) * Math.cos(e)]; - const dot = (a: number[], b: readonly number[]) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; - const t = Math.tan(CAMERA.fov / 2); - const f = dot(d, v.forward); - const nx = dot(d, v.right) / f / (t * (w / h)); - const ny = dot(d, v.up) / f / t; - const at = project(0.1, e, w, h)!; - expect(at.x).toBeCloseTo(((nx + 1) / 2) * w, 6); - expect(at.y).toBeCloseTo(((1 - ny) / 2) * h, 6); - }); -}); - -describe('turning with the camera', () => { - it('stars are on screen, and slide sideways as the camera turns', () => { - const s = createTerrainStars(glCanvas(), SKY.midnight)!; - s.draw(0); - const first = ctx2d.c.arcs.slice(); - expect(first.length).toBeGreaterThan(10); - s.draw(0.002); - const later = ctx2d.c.arcs; - expect(later).not.toEqual(first); - const m = (a: number[][]) => a.reduce((t, p) => t + p[0], 0) / a.length; - expect(m(later)).not.toBeCloseTo(m(first), 1); - }); - - it('repeats every PERIOD of heading', () => { - const s = createTerrainStars(glCanvas(), SKY.midnight)!; - s.draw(0.1); - const a = ctx2d.c.arcs.map((p) => p.map((n) => Math.round(n * 1e3))); - s.draw(0.1 + PERIOD / (2 * Math.PI)); - expect(ctx2d.c.arcs.map((p) => p.map((n) => Math.round(n * 1e3)))).toEqual(a); - }); - - it('the field fills the screen top and thins toward the horizon, inside the elevation band', () => { - expect(elevationOf(0)).toBeCloseTo(ELEVATION_TOP, 9); - expect(elevationOf(0.78)).toBeCloseTo(0, 9); - }); -}); - -describe('brightness', () => { - it('draws every star at BRIGHTEN times its ridge-field alpha, capped at 1', () => { - createTerrainStars(glCanvas(), SKY.midnight)?.draw(0); - const want = makeStars(nightColours(), 390, 844).map((st) => Math.min(1, st.alpha * BRIGHTEN)); - ctx2d.c.alphas.forEach((a) => expect(want.some((w) => Math.abs(w - a) < 1e-9)).toBe(true)); - // and it is brighter than the ridge field's own top alpha - const top = Math.max(...makeStars(nightColours(), 390, 844).map((st) => st.alpha)); - expect(Math.max(...ctx2d.c.alphas)).toBeGreaterThan(top * 1.5); - }); -}); - -describe('motion', () => { - it('with no clock every star is at base and a repeat draw repaints; no twinkle', () => { - const s = createTerrainStars(glCanvas(), SKY.midnight)!; - s.draw(0.3); - const alphas = ctx2d.c.alphas.slice(); - s.draw(0.3); - expect(ctx2d.c.alphas).toEqual(alphas); - }); - - it('with the clock the twinklers swing away from base, and the repaint is throttled', () => { - const s = createTerrainStars(glCanvas(), SKY.midnight)!; - s.draw(0.3); - const still = ctx2d.c.alphas.slice(); - let moved = false; - for (let t = 1; t < 60 && !moved; t += 1.7) { - s.draw(0.3, t); - moved = ctx2d.c.alphas.some((a, i) => a !== still[i]); - } - expect(moved).toBe(true); - const clears = ctx2d.c.clears; - s.draw(0.3, 100); - s.draw(0.3, 100 + FRAME_MS / 4000); - expect(ctx2d.c.clears).toBe(clears + 1); - }); - - it('resize refits the canvas and the next draw repaints at once', () => { - const c = glCanvas(); - const s = createTerrainStars(c, SKY.midnight)!; - s.draw(0.1, 5); - c.clientHeight = 400; - s.resize(); - expect(overlay.height).toBe(Math.ceil(horizonY(400))); - const clears = ctx2d.c.clears; - s.draw(0.1, 5.001); - expect(ctx2d.c.clears).toBe(clears + 1); - }); -}); diff --git a/src/app/features/scene/terrain/terrainStars.ts b/src/app/features/scene/terrain/terrainStars.ts deleted file mode 100644 index a7275062..00000000 --- a/src/app/features/scene/terrain/terrainStars.ts +++ /dev/null @@ -1,173 +0,0 @@ -// The terrain scene's star layer: the ridge scene's starfield (ridge/stars.ts: placement, alpha, tint, the -// rolling twinkle schedule) on a 2D overlay canvas above the WebGL canvas, faded by the sun's elevation (starGain). -// -// The WebGL canvas is opaque, so the overlay sits on top and is cut to the sky: it is only as tall as the -// horizon line is low on screen. The camera has no roll and the eye (CAMERA.eye) is above the highest peak -// (TERRAIN.hmax), so terrain never rises above that line and a star above the horizon is never over terrain. -// -// Stars turn with the camera, as sky does: the ridge field's x becomes azimuth, repeated every PERIOD (so 400 -// stars fill a sky that only ever shows 55 deg to ~120 deg of it), and y becomes elevation from the horizon -// up to ELEVATION_TOP, the top of the screen. Placement is projected with the terrain's own camera (CAMERA, -// the yaw the terrain draws at), nothing is baked, and the whole overlay is redrawn at most every FRAME_MS: a -// visible star is a few arcs on a canvas a quarter of the screen tall. The stars stop when the terrain stops: -// the layer only paints when Terrain.ts draws, and a draw with no clock (reduced motion, still tier, resize) -// paints every star at base brightness. - -import { baked } from '../../../../sky/baked'; -import type { SkyColours, Srgb } from '../ridge/skyColour'; -import { activeAt, makeStars, SKY_STOPS, Star } from '../ridge/stars'; -import { SkyData } from './terrainSky'; -import { CAMERA } from './terrainWorld'; - -/** Azimuth the star field repeats at (radians); wider than any horizontal field of view the layer is shown at. */ -export const PERIOD = (2 * Math.PI) / 3; -/** Elevation of the field's top, radians: a little above the top edge of the screen at the camera's pitch. */ -export const ELEVATION_TOP = (16 * Math.PI) / 180; -/** The overlay repaints at most this often while the terrain turns (12 px/s on a phone: under half a pixel a step). */ -export const FRAME_MS = 33; -/** The twinkle schedule is re-read this often; the swings are 2 to 7 s. */ -const TWINKLE_MS = 50; - -const hex = (h: string): Srgb => - [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16)) as unknown as Srgb; - -/** - * How much of the starfield shows with the sun at `elevation` degrees: all of it below -12 (where the baked - * scattering goes dark: the planet's shadow covers every sunlit air path), none above -6 (civil twilight), a smooth - * fade between. Not a dark/day gate: a sun at -9 shows the stars at half. - */ -export function starGain(elevation: number): number { - const t = Math.min(1, Math.max(0, (elevation + 12) / 6)); - return 1 - t * t * (3 - 2 * t); -} - -/** The ridge star module's view of the night sky it places stars against: the baked midnight gradient's zenith, middle and horizon stops. */ -export function nightColours(): SkyColours { - const g = baked.midnight.gradient; - return { - top: hex(g[0]), - mid: hex(g[Math.floor(g.length / 2)]), - horizon: hex(g[g.length - 1]), - ground: [0, 0, 0], - }; -} - -/** Screen height in px below which there is no sky: where the horizon plane meets the image, a straight line. */ -export const horizonY = (height: number): number => - height * (0.5 - Math.tan(CAMERA.pitch) / Math.tan(CAMERA.fov / 2) / 2); - -export interface Placed { - x: number; - y: number; -} - -/** - * Where a star at azimuth `da` from the camera's heading and elevation `e` (radians) lands in a `w` x `h` px - * viewport, or null if it is behind or off the screen. The same camera as `view()` in terrainWorld.ts - * (forward, right and up are its basis written out for a camera with yaw and pitch only). - */ -export function project(da: number, e: number, w: number, h: number): Placed | null { - const p = CAMERA.pitch; - const ce = Math.cos(e); - const front = ce * Math.cos(p) * Math.cos(da) - Math.sin(e) * Math.sin(p); - if (front <= 0.01) return null; - const tanHalf = Math.tan(CAMERA.fov / 2); - const nx = (ce * Math.sin(da)) / front / (tanHalf * (w / h)); - const ny = (ce * Math.sin(p) * Math.cos(da) + Math.sin(e) * Math.cos(p)) / front / tanHalf; - if (Math.abs(nx) > 1.05) return null; - return { x: ((nx + 1) / 2) * w, y: ((1 - ny) / 2) * h }; -} - -/** Elevation in radians for a ridge-field height fraction y (0 zenith side .. SKY_STOPS.horizon at the horizon). */ -export const elevationOf = (y: number): number => ELEVATION_TOP * (1 - y / SKY_STOPS.horizon); - -const wrap = (a: number): number => a - PERIOD * Math.round(a / PERIOD); - -/** The terrain overlay draws the ridge field's stars brighter and a little larger: a phone's small, hazy sky needs it to read. */ -export const BRIGHTEN = 2.4; -export const GROW = 1.3; - -export interface TerrainStars { - /** Paint for the camera `turns` into its turn (0..1). `seconds` is the clock while the terrain moves; absent: every star at base. */ - draw(turns: number, seconds?: number): void; - /** Re-fit the overlay to the canvas's current size; the next draw repaints. */ - resize(): void; - dispose(): void; -} - -/** The layer for `canvas`'s parent, or null: the sun is too high for any star, no parent, no 2D context. */ -export function createTerrainStars(canvas: HTMLCanvasElement, sky: SkyData): TerrainStars | null { - const colours = nightColours(); - const gain = starGain(sky.elevation); - const parent = canvas.parentElement; - if (!parent || gain <= 0) return null; - const el = document.createElement('canvas'); - const ctx = el.getContext?.('2d'); - if (!ctx) return null; - el.setAttribute?.('aria-hidden', 'true'); - Object.assign(el.style, { position: 'absolute', left: '0', top: '0', pointerEvents: 'none' }); - parent.appendChild(el); - - let w = 1; - let h = 1; - let scale = 1; - let field: Star[] = []; - let lit: Array<{ star: Star; az: number; e: number }> = []; - let gains = new Map(); - let gainsAt = -Infinity; - let last = -Infinity; - - const fit = () => { - w = canvas.clientWidth || window.innerWidth; - h = canvas.clientHeight || window.innerHeight; - scale = Math.min(window.devicePixelRatio || 1, 2); - const sky = Math.max(1, Math.ceil(horizonY(h))); - el.width = Math.max(1, Math.round(w * scale)); - el.height = Math.max(1, Math.round(sky * scale)); - el.style.width = `${w}px`; - el.style.height = `${sky}px`; - field = makeStars(colours, w, h); - lit = field.map((star) => ({ star, az: star.x * PERIOD, e: elevationOf(star.y) })); - gains = new Map(); - gainsAt = -Infinity; - }; - - const paint = (turns: number, seconds: number | undefined) => { - ctx.clearRect(0, 0, el.width, el.height); - if (seconds !== undefined && seconds * 1000 - gainsAt >= TWINKLE_MS) { - gains = new Map(activeAt(field.length, seconds).map((a) => [a.star, a.gain])); - gainsAt = seconds * 1000; - } - const yaw = 2 * Math.PI * turns; - lit.forEach(({ star, az, e }, i) => { - const da = wrap(az - yaw); - const twinkle = seconds === undefined ? 1 : gains.get(i) ?? 1; - ctx.globalAlpha = Math.min(1, star.alpha * twinkle * BRIGHTEN) * gain; - ctx.fillStyle = star.fill; - [da, da > 0 ? da - PERIOD : da + PERIOD].forEach((d) => { - const at = project(d, e, w, h); - if (!at || at.y < 0 || at.y > el.height / scale) return; - ctx.beginPath(); - ctx.arc(at.x * scale, at.y * scale, star.r * GROW * scale, 0, 2 * Math.PI); - ctx.fill(); - }); - }); - ctx.globalAlpha = 1; - }; - - fit(); - return { - draw(turns, seconds) { - if (seconds !== undefined && seconds * 1000 - last < FRAME_MS) return; - last = seconds === undefined ? -Infinity : seconds * 1000; - paint(turns, seconds); - }, - resize() { - fit(); - last = -Infinity; - }, - dispose() { - el.remove(); - }, - }; -} diff --git a/src/app/features/scene/terrain/terrainWorld.test.ts b/src/app/features/scene/terrain/terrainWorld.test.ts deleted file mode 100644 index 70a9d763..00000000 --- a/src/app/features/scene/terrain/terrainWorld.test.ts +++ /dev/null @@ -1,140 +0,0 @@ -/* eslint-disable no-restricted-syntax -- tests loop over skies, normals and distances */ -import { describe, expect, it } from 'vitest'; -import { - buildGrid, - CAMERA, - GRID, - seedOffset, - TERRAIN, - triangleCount, - view, - warpUv, -} from './terrainWorld'; -import { heightFragmentSource } from './terrainShaders'; - -describe('seed', () => { - it('same seed, same offset, so the baked height map is the same; a different seed moves it', () => { - expect(seedOffset(7)).toEqual(seedOffset(7)); - expect(seedOffset(0)).toEqual([0, 0]); - expect(seedOffset(1)).not.toEqual(seedOffset(2)); - }); - - it('the height-bake source is a pure function of nothing but the world constants', () => { - expect(heightFragmentSource()).toBe(heightFragmentSource()); - const src = heightFragmentSource(); - expect(src.startsWith('#version 300 es')).toBe(true); - expect(src).toContain('cultmath_phacelle'); - expect(src).toContain(`/ ${TERRAIN.hmax.toFixed(1)}`); - expect(src).toContain('uSeed'); - }); -}); - -describe('grid', () => { - it('has (n+1)^2 vertices in 0..1 and 2n^2 triangles that index them all in range', () => { - const n = 8; - const g = buildGrid(n); - expect(g.uv.length).toBe((n + 1) * (n + 1) * 2); - expect(g.indices.length / 3).toBe(triangleCount(n)); - expect(Math.max(...g.indices)).toBe((n + 1) * (n + 1) - 1); - expect(Math.min(...g.uv)).toBe(0); - expect(Math.max(...g.uv)).toBe(1); - }); - - it('each tier fits a 32-bit index and the cheap tiers stay cheap', () => { - // 524k at 512 quads (low), 1.18M at 768 (full): Meta asked for denser terrain on 2026-11-10, up from 205k at 320. No - // phone frame time is measured (SwiftShader only); kept as a ceiling so a bigger grid is a deliberate change. - expect(triangleCount(GRID.low.grid)).toBeLessThan(540000); - expect(triangleCount(GRID.full.grid)).toBeLessThan(1200000); - (['still', 'low', 'full'] as const).forEach((t) => - expect((GRID[t].grid + 1) ** 2).toBeLessThan(2 ** 32) - ); - expect(GRID.full.grid).toBeGreaterThan(GRID.low.grid); - expect(GRID.still.tex).toBeLessThanOrEqual(GRID.low.tex); - }); -}); - -describe('camera', () => { - const project = (m: Float32Array, p: number[]) => { - const x = m[0] * p[0] + m[4] * p[1] + m[8] * p[2] + m[12]; - const y = m[1] * p[0] + m[5] * p[1] + m[9] * p[2] + m[13]; - const z = m[2] * p[0] + m[6] * p[1] + m[10] * p[2] + m[14]; - const w = m[3] * p[0] + m[7] * p[1] + m[11] * p[2] + m[15]; - return { x: x / w, y: y / w, z: z / w, w }; - }; - - it('a point straight ahead lands in the middle of the screen, in front, inside the depth range', () => { - for (const turns of [0, 0.25, 0.6]) { - const v = view(0.46, turns); - const p = v.eye.map((e, i) => e + 800 * v.forward[i]); - const s = project(v.viewProj, p); - expect(s.w).toBeGreaterThan(0); - expect(s.x).toBeCloseTo(0, 5); - expect(s.y).toBeCloseTo(0, 5); - expect(Math.abs(s.z)).toBeLessThan(1); - } - }); - - it('looks down by the pitch, and one full turn comes back to the same heading', () => { - const a = view(1, 0); - const b = view(1, 1); - expect(a.forward[1]).toBeCloseTo(-Math.sin(CAMERA.pitch), 9); - for (let i = 0; i < 3; i += 1) expect(a.forward[i]).toBeCloseTo(b.forward[i], 9); - }); - - it('sits above the highest possible terrain, so the eye is never inside a hill', () => { - expect(CAMERA.eye).toBeGreaterThan(TERRAIN.hmax); - }); - - it('the basis is orthonormal', () => { - const v = view(0.5, 0.37); - const dot = (a: number[], b: number[]) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; - expect(dot(v.right, v.up)).toBeCloseTo(0, 9); - expect(dot(v.right, v.forward)).toBeCloseTo(0, 9); - expect(dot(v.up, v.forward)).toBeCloseTo(0, 9); - expect(Math.hypot(...v.up)).toBeCloseTo(1, 9); - }); -}); - -describe('grid resolution', () => { - // The mesh must carry what the height map shows: where a quad is wider than a couple of texels the shading (read from the - // height map) has gullies the polygons cannot, and the near ground reads as hard-edged facets (the 'terrain · low' phone - // shots, 2026-11-09). Metres from the patch centre to the nearest ground the camera can see: the bottom view ray meets - // the highest terrain, hmax below the eye, at (eye - hmax) / tan(pitch + fov / 2). - const nearest = (CAMERA.eye - TERRAIN.hmax) / Math.tan(CAMERA.pitch + CAMERA.fov / 2); - const spacingAt = (grid: number, metres: number) => { - for (let i = 0; i < grid; i += 1) { - const x = (warpUv((i + 1) / grid) - 0.5) * TERRAIN.span; - if (x >= metres) return (warpUv((i + 1) / grid) - warpUv(i / grid)) * TERRAIN.span; - } - throw new Error('beyond the patch'); - }; - - it.each(['still', 'low', 'full'] as const)( - 'the %s tier has a quad no wider than two height texels at the nearest ground the camera can see', - (tier) => { - const { grid, tex } = GRID[tier]; - expect(spacingAt(grid, nearest)).toBeLessThanOrEqual((2 * TERRAIN.span) / (tex - 1)); - } - ); - - it('a dearer tier never has a coarser mesh', () => { - expect(GRID.low.grid).toBeGreaterThanOrEqual(GRID.still.grid); - expect(GRID.full.grid).toBeGreaterThanOrEqual(GRID.low.grid); - }); -}); - -describe('warpUv', () => { - it('maps the patch onto itself, monotonic, centre fixed', () => { - expect(warpUv(0)).toBe(0); - expect(warpUv(1)).toBe(1); - expect(warpUv(0.5)).toBe(0.5); - for (let i = 0; i < 100; i += 1) expect(warpUv((i + 1) / 100)).toBeGreaterThan(warpUv(i / 100)); - }); - - it('packs the vertices toward the camera at the centre: finer there, coarser at the rim, than a plain grid', () => { - const plain = 1 / 192; - const step = (u: number) => warpUv(u + 1 / 192) - warpUv(u); - expect(step(0.5)).toBeLessThan(0.6 * plain); - expect(step(0.99)).toBeGreaterThan(1.3 * plain); - }); -}); diff --git a/src/app/features/scene/terrain/terrainWorld.ts b/src/app/features/scene/terrain/terrainWorld.ts deleted file mode 100644 index 82a16bfb..00000000 --- a/src/app/features/scene/terrain/terrainWorld.ts +++ /dev/null @@ -1,140 +0,0 @@ -// The terrain scene's fixed numbers, grid and camera, as pure functions. No DOM, no GL. -// The height field itself is a function of world position written in GLSL (terrainShaders.ts), baked once -// into a texture; the CPU owns only where it is looked at from, and the seed offset it is sampled at. - -/** Metres across the patch, and the height in metres that normalised height 1.0 stands for. */ -export const TERRAIN = { span: 3000, hmax: 256 }; - -/** - * Grid quads per side and height-map texels per side, by tier. 'still' draws one frame, so it takes the cheap pair. The - * mesh is dense enough that a quad is at most two texels wide at the nearest ground (terrainWorld.test.ts); a coarser mesh - * under shading read from the height map shows as hard-edged facets and stepped crests. - */ -export const GRID = { - still: { grid: 320, tex: 1024 }, - low: { grid: 512, tex: 1024 }, - full: { grid: 768, tex: 2048 }, -} as const; - -/** The camera: at the patch centre, above the highest peak, turning slowly and looking a little down. */ -export const CAMERA = { - eye: 330, - pitch: (13 * Math.PI) / 180, - fov: (55 * Math.PI) / 180, - near: 10, - far: 6000, - /** Seconds for one full turn. */ - seconds: 420, -}; - -/** The height map's sample offset in metres for a seed: same seed, same terrain. Seed 0 is the origin. */ -export function seedOffset(seed: number): [number, number] { - const s = Math.trunc(seed); - return [(s * 7919) % 65536, (s * 104729) % 65536]; -} - -/** - * Where grid coordinate `u` (0..1 across the patch) lands in the patch, 0..1. The camera stands at the centre, so the - * grid is packed toward it: with s = 2u - 1 the spacing grows as 0.5 + |s| of the plain grid's, about half of it at the - * centre and half again as much at the rim. The vertex shader does the same arithmetic (terrainShaders.ts GRID_VERT). - */ -export const warpUv = (u: number): number => { - const s = 2 * u - 1; - return 0.5 + 0.5 * (0.5 * s + 0.5 * s * Math.abs(s)); -}; - -export const triangleCount = (grid: number): number => 2 * grid * grid; - -/** Vertex grid in unit uv: (grid + 1)^2 positions, then the two-triangle-per-quad index list. */ -export function buildGrid(grid: number): { uv: Float32Array; indices: Uint32Array } { - const uv = new Float32Array((grid + 1) * (grid + 1) * 2); - for (let j = 0, k = 0; j <= grid; j += 1) - for (let i = 0; i <= grid; i += 1, k += 2) { - uv[k] = i / grid; - uv[k + 1] = j / grid; - } - const indices = new Uint32Array(grid * grid * 6); - for (let j = 0, k = 0; j < grid; j += 1) - for (let i = 0; i < grid; i += 1, k += 6) { - const a = j * (grid + 1) + i; - indices.set([a, a + grid + 1, a + 1, a + 1, a + grid + 1, a + grid + 2], k); - } - return { uv, indices }; -} - -export interface View { - /** Column-major perspective * view. */ - viewProj: Float32Array; - eye: [number, number, number]; - /** Camera basis in world space, for the sky pass. */ - right: [number, number, number]; - up: [number, number, number]; - forward: [number, number, number]; -} - -const norm = (a: number[]): [number, number, number] => { - const l = Math.hypot(a[0], a[1], a[2]) || 1; - return [a[0] / l, a[1] / l, a[2] / l]; -}; -const cross = (a: number[], b: number[]): [number, number, number] => [ - a[1] * b[2] - a[2] * b[1], - a[2] * b[0] - a[0] * b[2], - a[0] * b[1] - a[1] * b[0], -]; - -/** The camera `turns` full turns round (0..1 wraps), for a viewport aspect (width / height). */ -export function view(aspect: number, turns: number): View { - const yaw = 2 * Math.PI * turns; - const cp = Math.cos(CAMERA.pitch); - const forward = norm([Math.sin(yaw) * cp, -Math.sin(CAMERA.pitch), -Math.cos(yaw) * cp]); - const right = norm(cross(forward, [0, 1, 0])); - const up = cross(right, forward); - const eye: [number, number, number] = [0, CAMERA.eye, 0]; - const t = (a: number[]) => -(a[0] * eye[0] + a[1] * eye[1] + a[2] * eye[2]); - const v = [ - right[0], - up[0], - -forward[0], - 0, - right[1], - up[1], - -forward[1], - 0, - right[2], - up[2], - -forward[2], - 0, - t(right), - t(up), - -t(forward), - 1, - ]; - const f = 1 / Math.tan(CAMERA.fov / 2); - const { near: n, far } = CAMERA; - const p = [ - f / aspect, - 0, - 0, - 0, - 0, - f, - 0, - 0, - 0, - 0, - (far + n) / (n - far), - -1, - 0, - 0, - (2 * far * n) / (n - far), - 0, - ]; - const viewProj = new Float32Array(16); - for (let c = 0; c < 4; c += 1) - for (let r = 0; r < 4; r += 1) { - let s = 0; - for (let k = 0; k < 4; k += 1) s += p[k * 4 + r] * v[c * 4 + k]; - viewProj[c * 4 + r] = s; - } - return { viewProj, eye, right, up, forward }; -} diff --git a/src/app/features/scene/terrain/tierLabel.test.ts b/src/app/features/scene/terrain/tierLabel.test.ts deleted file mode 100644 index e3f18871..00000000 --- a/src/app/features/scene/terrain/tierLabel.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -/* eslint-disable @typescript-eslint/no-explicit-any -- DOM stubs, as the other scene tests */ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { showTierLabel } from './tierLabel'; - -let search: string; -let appended: any[]; -const canvas = (parent: boolean) => - ({ - parentElement: parent - ? { - appendChild: (e: any) => appended.push(e), - } - : null, - } as any); - -beforeEach(() => { - search = ''; - appended = []; - vi.stubGlobal('window', { - get location() { - return { search }; - }, - }); - vi.stubGlobal('document', { - createElement: () => ({ style: {}, remove: vi.fn(), textContent: '' }), - }); -}); -afterEach(() => vi.unstubAllGlobals()); - -describe('showTierLabel', () => { - it('adds nothing in a normal build', () => { - expect(showTierLabel(canvas(true), 'full', true)).toBeNull(); - expect(appended).toHaveLength(0); - }); - - it('names the path on screen when asked with ?tierlabel=1, and removes itself', () => { - search = '?tierlabel=1'; - const remove = showTierLabel(canvas(true), 'sky-only', true); - expect(appended).toHaveLength(1); - expect(appended[0].textContent).toBe('terrain · sky-only'); - remove!(); - expect(appended[0].remove).toHaveBeenCalled(); - }); - - it('ignores ?tierlabel=1 where the overlays are not allowed (a production page)', () => { - search = '?tierlabel=1'; - expect(showTierLabel(canvas(true), 'full', false)).toBeNull(); - expect(appended).toHaveLength(0); - }); - - it('has nowhere to go without a parent', () => { - search = '?tierlabel=1'; - expect(showTierLabel(canvas(false), 'full', true)).toBeNull(); - }); -}); diff --git a/src/app/features/scene/terrain/tierLabel.ts b/src/app/features/scene/terrain/tierLabel.ts deleted file mode 100644 index 4afc8a69..00000000 --- a/src/app/features/scene/terrain/tierLabel.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { overlayRequested } from '../debugOverlays'; - -// A tiny label naming which terrain path is on screen ('full', 'low', 'still', or 'sky-only' where WebGL2 is missing), -// so a screenshot of a preview says what it shows. Built into preview builds (VITE_PREVIEW_DEMO=1), or by `?tierlabel=1` -// where the diagnostic overlays are allowed (debugOverlays.ts). -const wanted = (allowed: boolean): boolean => - import.meta.env?.VITE_PREVIEW_DEMO === '1' || overlayRequested('tierlabel', allowed); - -/** Adds the label to the canvas's parent; returns its remover, or null when no label is wanted. */ -export function showTierLabel( - canvas: HTMLCanvasElement, - text: string, - allowed: boolean -): (() => void) | null { - const parent = canvas.parentElement; - if (!parent || !wanted(allowed)) return null; - const el = document.createElement('div'); - el.textContent = `terrain · ${text}`; - Object.assign(el.style, { - position: 'absolute', - left: '2px', - top: '16px', - font: '10px monospace', - color: 'rgba(255,255,255,.75)', - background: 'rgba(0,0,0,.4)', - padding: '1px 5px', - borderRadius: '3px', - pointerEvents: 'none', - }); - parent.appendChild(el); - return () => el.remove(); -} diff --git a/src/app/features/scene/tier.ts b/src/app/features/scene/tier.ts index ba338f37..0f1c96be 100644 --- a/src/app/features/scene/tier.ts +++ b/src/app/features/scene/tier.ts @@ -16,14 +16,16 @@ export interface Capabilities { } /** - * 'ridge': baked parallax ridges, no WebGL (default). 'raymarch': the sphere-traced world with its tree and - * clouds. 'terrain': a baked height map on a displaced grid, lit and hazed by the baked sky (WebGL2). + * 'ridge': baked ridge cards lit once per sky in WebGL2, no per-frame WebGL (default). 'raymarch': the sphere-traced world with its tree and + * clouds. */ -export type SceneStyle = 'ridge' | 'raymarch' | 'terrain'; +export type SceneStyle = 'ridge' | 'raymarch'; export interface BackgroundSceneConfig { tier?: SceneTier; style?: SceneStyle; + /** The baked ridge place to show (a key of the ridge index); unknown or absent: the index's default. */ + place?: string; /** Let the page URL switch on the diagnostic overlays (`?probe=1`, `?tierlabel=1`) in a production build. Default: no. */ debugOverlays?: boolean; } diff --git a/src/app/features/scene/view/PlaceSubmenu.test.tsx b/src/app/features/scene/view/PlaceSubmenu.test.tsx new file mode 100644 index 00000000..9dfc670a --- /dev/null +++ b/src/app/features/scene/view/PlaceSubmenu.test.tsx @@ -0,0 +1,224 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { parseManifest } from '../ridge/manifest'; +import type { PlaceListing } from '../ridge/manifest'; +import { wireManifest } from '../ridge/manifest.fixture'; +import type { SkyChoice } from '../ridge/skyMoment'; +import { FALLBACK_VIEW } from '../ridge/view'; +import { LINES_CREDIT, STARS_CREDIT } from '../ridge/credits'; +import { WEATHER_FEEDS, creditLine } from '../ridge/weatherFeed'; +import { PlaceCarousel, PlaceSubmenu, SETTLE_MS } from './PlaceSubmenu'; +import { SkySubmenu } from './SkySubmenu'; + +// The hooks are held still (TimeSubmenu.test.tsx): the element tree is read, a function component is expanded by calling it. +const held = vi.hoisted(() => ({ + choice: { kind: 'auto' } as unknown, + clock: new Date('2030-06-21T10:00:00Z'), + live: undefined as boolean | undefined, + place: undefined as unknown, + places: undefined as unknown, + picked: [] as string[], +})); +vi.mock('react', async (importOriginal) => { + const actual = await importOriginal(); + const useRef = (init: unknown) => ({ current: init }); + const useEffect = () => undefined; + return { ...actual, default: { ...actual, useRef, useEffect }, useRef, useEffect }; +}); +vi.mock('../../../hooks/useSkyState', () => ({ + useDrawnPlace: () => held.place, + useSkyChoice: () => held.choice, + useSkyMinute: (live: boolean) => { + held.live = live; + return held.clock; + }, +})); +vi.mock('../../../hooks/useSceneView', () => ({ + usePlaceList: () => held.places, + useConstellationLines: () => false, +})); +vi.mock('../placeState', () => ({ setPlaceChoice: (id: string) => held.picked.push(id) })); +vi.mock('../skyState', () => ({ + setConstellationLines: () => undefined, +})); + +type El = { type?: unknown; props?: Record }; +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 ''; +}; +const strings = (node: unknown): string[] => { + if (typeof node === 'string') return [node]; + if (Array.isArray(node)) return node.flatMap(strings); + if (node && typeof node === 'object' && 'props' in node) + return Object.values((node as { props: object }).props).flatMap(strings); + return []; +}; +const text = (node: unknown) => strings(node).join(' '); + +const manifest = parseManifest(wireManifest(), 'http://x/ridge/vienna/'); +const at = (id: string, name: string, lat: number, lon: number, tz: string): PlaceListing => ({ + id, + name, + place: { id, lat, lon, altitudeKm: 0, tz }, +}); +const FIVE: PlaceListing[] = [ + at('vienna', 'Vienna', 48.2, 16.4, 'Europe/Vienna'), + at('fuji', 'Fuji', 35.36, 138.73, 'Asia/Tokyo'), + at('matterhorn', 'Matterhorn', 45.98, 7.66, 'Europe/Zurich'), + at('amadablam', 'Ama Dablam', 27.86, 86.86, 'Asia/Kathmandu'), + at('grandcanyon', 'Grand Canyon', 36.1, -112.1, 'America/Phoenix'), +]; +const AUTO: SkyChoice = { kind: 'auto' }; +const NOW = new Date('2030-06-21T10:00:00Z'); +const cardsOf = (tree: El[]) => tree.filter((e) => e.props?.['aria-current'] !== undefined); + +beforeEach(() => { + held.place = FALLBACK_VIEW.place; + held.places = FIVE; + held.choice = AUTO; + held.live = undefined; + held.picked.length = 0; +}); + +describe('the Place carousel', () => { + it('is one card per baked place, named by the index and showing each place local time now', () => { + const tree = walk(PlaceCarousel({ places: FIVE, current: 'vienna', choice: AUTO, now: NOW, onPick: () => undefined })); + expect(cardsOf(tree).map(textOf)).toEqual([ + 'Vienna12:00 local', + 'Fuji19:00 local', + 'Matterhorn12:00 local', + 'Ama Dablam15:45 local', + 'Grand Canyon03:00 local', + ]); + expect(cardsOf(tree).map((e) => e.props?.['aria-current'])).toEqual([true, false, false, false, false]); + }); + + const minutes = (card: string): number => { + const m = /(\d\d):(\d\d) local/.exec(card); + return Number(m?.[1]) * 60 + Number(m?.[2]); + }; + + it("shows the place-local time of the moment the sky draws: a named moment is that moment at each place, not the real clock, and Auto is the clock", () => { + const noon: SkyChoice = { kind: 'named', id: 'noon' }; + const drawn = (choice: SkyChoice) => + cardsOf(walk(PlaceCarousel({ places: FIVE, current: 'vienna', choice, now: NOW, onPick: () => undefined }))).map(textOf); + const live = drawn(AUTO); + const frozen = drawn(noon); + expect(frozen).not.toEqual(live); + frozen.forEach((card) => { + expect(minutes(card)).toBeGreaterThanOrEqual(11 * 60); // each place's own solar noon, in its own zone + expect(minutes(card)).toBeLessThanOrEqual(14 * 60); + }); + const free: SkyChoice = { kind: 'free', date: '2030-01-15', minutes: 3 * 60 }; + expect(drawn(free).map(minutes)).toEqual([180, 180, 180, 180, 180]); // a free moment is the minute asked, in each zone + }); + + it('is given the sky clock and the choice, and the clock ticks while the sky is live (Auto) and only then', () => { + held.clock = new Date('2030-06-21T10:07:00Z'); + const carousel = () => walk(PlaceSubmenu({ manifest })).find((e) => e.type === PlaceCarousel); + expect(carousel()?.props?.now).toBe(held.clock); + expect(carousel()?.props?.choice).toBe(AUTO); + expect(held.live).toBe(true); + held.choice = { kind: 'named', id: 'dusk' }; + expect(carousel()?.props?.choice).toBe(held.choice); + expect(held.live).toBe(false); + held.clock = NOW; + }); + + it('is in the panel over the index list, and a card or an arrow picks through the choice store', () => { + const carousel = walk(PlaceSubmenu({ manifest })).find((e) => e.type === PlaceCarousel); + expect(carousel?.props?.places).toBe(FIVE); + const onPick = carousel?.props?.onPick as (id: string) => void; + onPick('grandcanyon'); + expect(held.picked).toEqual(['grandcanyon']); + held.picked.length = 0; + const own = walk(PlaceCarousel({ places: FIVE, current: 'vienna', choice: AUTO, now: NOW, onPick })); + const click = (label: string) => + (own.find((e) => e.props?.['aria-label'] === label)?.props?.onClick as () => void)(); + click('Previous place'); // the ring: before Vienna is the last + click('Next place'); + (cardsOf(own)[2].props?.onClick as () => void)(); + expect(held.picked).toEqual(['grandcanyon', 'fuji', 'matterhorn']); + }); + + it('is absent while the index lists one place or none has loaded; the credits stay', () => { + for (const places of [undefined, [FIVE[0]], []]) { + held.places = places; + expect(walk(PlaceSubmenu({ manifest })).some((e) => e.type === PlaceCarousel)).toBe(false); + expect(text(PlaceSubmenu({ manifest }))).toContain(STARS_CREDIT); + } + }); + + it('settles a swipe on the card in the middle and picks it once it rests, not the drawn place', () => { + vi.useFakeTimers(); + try { + const strip = { + scrollLeft: 0, + clientWidth: 100, + children: FIVE.map((_, i) => ({ offsetLeft: i * 100, offsetWidth: 100 })), + }; + const own = walk( + PlaceCarousel({ places: FIVE, current: 'vienna', choice: AUTO, now: NOW, onPick: (id) => held.picked.push(id) }) + ); + const onScroll = own.find((e) => typeof e.props?.onScroll === 'function')?.props?.onScroll as (e: unknown) => void; + const scrollTo = (left: number) => { + strip.scrollLeft = left; + onScroll({ currentTarget: strip }); + }; + scrollTo(100); + scrollTo(200); // still moving: nothing is picked until it rests + expect(held.picked).toEqual([]); + vi.advanceTimersByTime(SETTLE_MS); + expect(held.picked).toEqual(['matterhorn']); + scrollTo(0); // at the drawn place: not a pick + vi.advanceTimersByTime(SETTLE_MS); + expect(held.picked).toEqual(['matterhorn']); + } finally { + vi.useRealTimers(); + } + }); +}); + +describe('the credits follow the place (ruling ridge-view-credits-home: Place alone)', () => { + it('Place carries the terrain, stars and lines credits', () => { + const t = text(PlaceSubmenu({ manifest })); + expect(t).toContain(manifest.attribution.creditLine); + expect(t).toContain(STARS_CREDIT); + expect(t).toContain(LINES_CREDIT); + }); + + it('Sky carries only the lines switch and its note: no credit of any wording', () => { + expect(strings(SkySubmenu()).filter((x) => /\s/.test(x))).toEqual([ + 'Constellation lines', + 'Drawn over the stars of a night sky.', + ]); + }); + + it("the weather's credit is the feed row's, shown for a place with a feed and for no other", () => { + const feed = WEATHER_FEEDS.vienna; + const t = text(PlaceSubmenu({ manifest })); + expect(t).toContain(feed.credit); + expect(t).toContain(feed.url); + expect(t).toContain(feed.dataset); + expect(creditLine(feed)).toBe(`${feed.credit} - ${feed.url}`); + for (const id of ['fuji', 'matterhorn', 'amadablam', 'grandcanyon']) { + held.place = { ...FALLBACK_VIEW.place, id }; + const other = text(PlaceSubmenu({ manifest })); + expect(other).not.toContain(feed.url); + expect(other).not.toContain('GeoSphere'); + expect(other).toContain(STARS_CREDIT); // the other credits do not depend on the place + } + }); +}); diff --git a/src/app/features/scene/view/PlaceSubmenu.tsx b/src/app/features/scene/view/PlaceSubmenu.tsx new file mode 100644 index 00000000..9eb51a55 --- /dev/null +++ b/src/app/features/scene/view/PlaceSubmenu.tsx @@ -0,0 +1,171 @@ +import React, { useEffect, useRef } from 'react'; +import { Box, Icon, IconButton, Icons, Text } from 'folds'; +import { useDrawnPlace, useSkyChoice, useSkyMinute } from '../../../hooks/useSkyState'; +import { usePlaceList } from '../../../hooks/useSceneView'; +import { PhoneHit } from '../../../styles/PhoneHit.css'; +import { LINES_CREDIT, STARS_CREDIT, terrainCredit } from '../ridge/credits'; +import type { RidgeManifest, PlaceListing } from '../ridge/manifest'; +import { localMinutes, momentFor } from '../ridge/skyMoment'; +import type { SkyChoice } from '../ridge/skyMoment'; +import { FALLBACK_VIEW } from '../ridge/view'; +import { feedFor } from '../ridge/weatherFeed'; +import { setPlaceChoice } from '../placeState'; +import { hhmm } from './TimeSubmenu'; +import * as css from './SceneView.css'; + +/** How long a swipe rests before the card it stopped on is picked, ms. */ +export const SETTLE_MS = 120; + +/** Index of the child of `strip` whose centre is nearest the strip's centre. */ +const centredIndex = (strip: HTMLElement): number => { + const mid = strip.scrollLeft + strip.clientWidth / 2; + let best = 0; + let gap = Infinity; + Array.from(strip.children).forEach((c, i) => { + const el = c as HTMLElement; + const d = Math.abs(el.offsetLeft + el.offsetWidth / 2 - mid); + if (d < gap) { + gap = d; + best = i; + } + }); + return best; +}; + +/** + * The baked places, one card each (its name and the place-local time of the moment the sky draws there: `momentFor`, the one owner, so the real clock under Auto and the + * picked moment under a named or free one), swiped or stepped with the arrows; the card in the middle is the place drawn + * (`current`), and a pick, a tap on a card, an arrow or a swipe that comes to rest on another, goes to `onPick`. The list is the index's: nothing here keeps a copy. + */ +export function PlaceCarousel({ + places, + current, + choice, + now, + onPick, +}: { + places: PlaceListing[]; + current: string; + choice: SkyChoice; + now: Date; + onPick: (id: string) => void; +}) { + const strip = useRef(null); + const settle = useRef>(); + const shown = useRef(current); + shown.current = current; + const at = Math.max( + 0, + places.findIndex((p) => p.id === current) + ); + + // The drawn place's card goes to the middle, at once (a programmed scroll is not a swipe: it must not end on a card the viewer did not pick). + useEffect(() => { + const el = strip.current; + const card = el?.children[at] as HTMLElement | undefined; + if (el && card) el.scrollLeft = card.offsetLeft - (el.clientWidth - card.offsetWidth) / 2; + }, [at, places]); + useEffect(() => () => clearTimeout(settle.current), []); + + const step = (by: number) => { + const next = places[(at + by + places.length) % places.length]; + if (next) onPick(next.id); + }; + return ( + + step(-1)} + > + + +
{ + const el = evt.currentTarget; + clearTimeout(settle.current); + settle.current = setTimeout(() => { + const to = places[centredIndex(el)]; + if (to && to.id !== shown.current) onPick(to.id); + }, SETTLE_MS); + }} + > + {places.map((p) => ( + + ))} +
+ step(1)} + > + + +
+ ); +} + +/** + * The Place submenu of the scene view: the carousel of the baked places (ruling ridge-places-dropdown-first-four; absent while the index lists one) and every credit the + * view owes (ruling ridge-view-credits-home: Place alone, no footer, no credit in Sky). The terrain credit is the bake's, the stars and the lines are drawn + * over any place at night, and the weather's credit is the feed row's, shown only where the place shown has a feed (`weatherFeed.ts`). + */ +export function PlaceSubmenu({ manifest }: { manifest: RidgeManifest | undefined }) { + const place = useDrawnPlace() ?? FALLBACK_VIEW.place; + const places = usePlaceList(); + const choice = useSkyChoice(); + const now = useSkyMinute(choice.kind === 'auto'); + const credit = terrainCredit(manifest); + const feed = feedFor(place.id); + return ( + + {places && places.length > 1 ? ( + + ) : ( + {manifest?.name ?? place.id} + )} + + + Data + + {credit && ( + + {credit} + + )} + + {STARS_CREDIT}. + + + {LINES_CREDIT}. + + {feed && ( + + {feed.credit} -{' '} + + {feed.url} + + . {feed.dataset}. + + )} + + + ); +} diff --git a/src/app/features/scene/view/SceneView.css.ts b/src/app/features/scene/view/SceneView.css.ts new file mode 100644 index 00000000..28c876de --- /dev/null +++ b/src/app/features/scene/view/SceneView.css.ts @@ -0,0 +1,122 @@ +import { style } from '@vanilla-extract/css'; +import { color, config } from 'folds'; +import { PLATE_TINT, SKY_PLATE_FALLBACK } from '../skyPlate'; +import { MOBILE_BREAKPOINT } from '../../../hooks/useScreenSize'; + +// The fullscreen scene view (sceneView.ts): the app is hidden behind it, so what is left over the scene is a turning surface and, top left, an icon rail and one +// panel. The rail and the panel are plates, blurred and tinted toward the sky like the chat bubbles (skyPlate.css.ts, PLATE_TINT), so their text reads over any sky. +const fill = `var(--sky-bubble, ${SKY_PLATE_FALLBACK.fill})`; +const text = `var(--sky-bubble-text, ${SKY_PLATE_FALLBACK.text})`; +const PHONE = `screen and (max-width: ${MOBILE_BREAKPOINT}px)`; +const GUTTER = 'max(0.5rem, env(safe-area-inset-top))'; + +export const Root = style({ + position: 'fixed', + inset: 0, +}); + +/** The whole viewport: a drag, a wheel or a swipe on it turns the view. A touch is never the page's (there is none to scroll). */ +export const Surface = style({ + position: 'absolute', + inset: 0, + touchAction: 'none', + overscrollBehavior: 'none', + userSelect: 'none', + cursor: 'grab', + selectors: { '&:active': { cursor: 'grabbing' } }, +}); + +/** How much of the rail and the panel is left while a finger is down: they step out of the way of the turn (ruling ridge-view-phone-one-finger). */ +export const TURNING_CHROME_OPACITY = 0.12; + +/** The rail and the panel, top left. It takes no pointer itself, so a drag over its gaps turns the view; its plates do. It fades while a finger is down. */ +export const Chrome = style({ + position: 'absolute', + top: GUTTER, + left: `max(0.5rem, env(safe-area-inset-left))`, + display: 'flex', + alignItems: 'flex-start', + gap: config.space.S200, + pointerEvents: 'none', + transition: 'opacity 150ms', + selectors: { [`${Root}[data-turning="true"] &`]: { opacity: TURNING_CHROME_OPACITY } }, +}); + +const Plate = style({ + pointerEvents: 'auto', + backgroundColor: [fill, `color-mix(in srgb, ${fill} ${PLATE_TINT * 100}%, transparent)`], + backdropFilter: 'blur(12px)', + WebkitBackdropFilter: 'blur(12px)', + color: text, + borderRadius: config.radii.R400, + vars: { + [color.Background.OnContainer]: text, + [color.Surface.OnContainer]: text, + [color.SurfaceVariant.OnContainer]: text, + }, +}); + +export const Rail = style([ + Plate, + { + display: 'flex', + flexDirection: 'column', + gap: config.space.S100, + padding: config.space.S100, + }, +]); + +export const Panel = style([ + Plate, + { + boxSizing: 'border-box', + width: '22rem', + maxWidth: 'calc(100vw - 5.5rem)', + maxHeight: `calc(100dvh - 2 * ${GUTTER})`, + overflowY: 'auto', + padding: config.space.S300, + '@media': { [PHONE]: { width: 'calc(100vw - 5.5rem)' } }, + }, +]); + +/** The Place submenu's carousel: the baked places side by side, one card centred, snapping as it is swiped; an arrow each side steps it. */ +export const Carousel = style({ + display: 'flex', + alignItems: 'center', + gap: config.space.S100, +}); + +export const Strip = style({ + position: 'relative', + display: 'flex', + flexGrow: 1, + minWidth: 0, + gap: config.space.S200, + overflowX: 'auto', + scrollSnapType: 'x mandatory', + scrollbarWidth: 'none', + overscrollBehaviorX: 'contain', + selectors: { '&::-webkit-scrollbar': { display: 'none' } }, +}); + +/** A place's card. Each is as wide as the strip, so the one in the strip is the one in view. */ +export const PlaceCard = style({ + flex: '0 0 100%', + scrollSnapAlign: 'center', + boxSizing: 'border-box', + display: 'flex', + flexDirection: 'column', + gap: config.space.S100, + padding: config.space.S300, + borderRadius: config.radii.R300, + border: `${config.borderWidth.B300} solid currentColor`, + background: 'transparent', + color: 'inherit', + font: 'inherit', + textAlign: 'center', + cursor: 'pointer', + opacity: 0.6, + selectors: { + '&[aria-current="true"]': { opacity: 1 }, + }, +}); diff --git a/src/app/features/scene/view/SceneView.test.tsx b/src/app/features/scene/view/SceneView.test.tsx new file mode 100644 index 00000000..9d6a24f9 --- /dev/null +++ b/src/app/features/scene/view/SceneView.test.tsx @@ -0,0 +1,241 @@ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { PhoneHit } from '../../../styles/PhoneHit.css'; +import SceneView, { Rail, SUBMENUS } from './SceneView'; +import { TURNING_CHROME_OPACITY } from './SceneView.css'; + +// The hooks are held still (TimeSubmenu.test.tsx): the element tree is read, a function component is expanded by calling it. +const held = vi.hoisted(() => ({ + effects: [] as Array<() => unknown>, + submenu: undefined as unknown, + closed: 0, + picked: [] as unknown[], + turning: [] as boolean[], + turner: [] as Array<[string, ...unknown[]]>, +})); +vi.mock('react', async (importOriginal) => { + const actual = await importOriginal(); + const useState = (init: unknown) => [ + typeof init === 'function' ? (init as () => unknown)() : init, + (v: unknown) => typeof v === 'boolean' && held.turning.push(v), + ]; + const useRef = (init: unknown) => ({ current: init }); + const useMemo = (fn: () => unknown) => fn(); + const useEffect = (fn: () => unknown) => { + held.effects.push(fn); + }; + return { + ...actual, + default: { ...actual, useState, useRef, useEffect, useMemo }, + useState, + useRef, + useEffect, + useMemo, + }; +}); +vi.mock('../../../hooks/useSceneView', () => ({ + useSceneViewState: () => ({ open: true, submenu: held.submenu }), + useRidgeManifest: () => undefined, +})); +vi.mock('../sceneView', () => ({ + closeSceneView: () => { + held.closed += 1; + }, + setSubmenu: (s: unknown) => held.picked.push(s), +})); +vi.mock('./turning', () => ({ + pxPerDegreeOf: () => 20, + createTurner: () => ({ + down: (x: number) => held.turner.push(['down', x]), + move: (x: number) => held.turner.push(['move', x]), + up: () => held.turner.push(['up']), + wheel: (dx: number) => held.turner.push(['wheel', dx]), + key: () => false, + }), +})); +vi.mock('focus-trap-react', () => ({ default: ({ children }: { children: unknown }) => children })); + +type El = { type?: unknown; ref?: unknown; key?: unknown; props?: Record }; +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 labels = (els: El[]) => els.map((e) => e.props?.['aria-label']).filter(Boolean); + +beforeEach(() => { + held.effects.length = 0; + held.submenu = undefined; + held.closed = 0; + held.picked.length = 0; + held.turning.length = 0; + held.turner.length = 0; + vi.stubGlobal('window', { + innerWidth: 1280, + innerHeight: 720, + addEventListener: () => undefined, + removeEventListener: () => undefined, + }); +}); +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('the rail', () => { + const rail = () => + walk( + Rail({ + items: SUBMENUS, + active: undefined, + onReturn: () => undefined, + onPick: () => undefined, + }) + ); + + it('lists Return first, then View, Time, Sky and Place, as a vertical toolbar', () => { + const els = rail(); + expect(els[0].props).toMatchObject({ role: 'toolbar', 'aria-orientation': 'vertical' }); + expect( + els.filter((e) => typeof e.props?.label === 'string').map((e) => e.props?.label) + ).toEqual(['Return', 'View', 'Time', 'Sky', 'Place']); + }); + + it('every rail icon is an IconButton carrying PhoneHit, with a label and a roving tab stop on Return', () => { + const buttons = rail() + .filter((e) => typeof e.props?.label === 'string') + .map((e) => + walk((e.type as (p: unknown) => unknown)(e.props)).find( + (x) => x.props?.className === PhoneHit + ) + ); + expect(buttons).toHaveLength(5); + buttons.forEach((b) => expect(b?.props?.['aria-label']).toBeTruthy()); + expect(buttons.map((b) => b?.props?.tabIndex)).toEqual([0, -1, -1, -1, -1]); + }); + + it('marks the submenu whose panel is up, and Return and a pick go to their handlers', () => { + const onPick = vi.fn(); + const onReturn = vi.fn(); + const els = walk(Rail({ items: SUBMENUS, active: 'time', onReturn, onPick })); + const item = (label: string) => + els.find((e) => e.props?.label === label)?.props as Record; + expect(['View', 'Time', 'Sky', 'Place'].map((l) => item(l).pressed)).toEqual([ + false, + true, + false, + false, + ]); + (item('Return').onClick as () => void)(); + (item('Sky').onClick as () => void)(); + expect(onReturn).toHaveBeenCalledOnce(); + expect(onPick).toHaveBeenCalledWith('sky'); + }); +}); + +describe('the view', () => { + const tree = () => walk(SceneView()); + const panels = () => tree().filter((e) => e.type === 'section'); + + it('shows no panel until a submenu is picked, then exactly one', () => { + expect(panels()).toHaveLength(0); + for (const s of ['view', 'time', 'sky', 'place']) { + held.submenu = s; + expect(panels()).toHaveLength(1); + } + }); + + it('a drag over the rail or its panel does not turn the view: the turning surface holds neither', () => { + held.submenu = 'view'; + const els = walk(SceneView()); + const surface = els.find((e) => typeof e.props?.onPointerDown === 'function') as El; + expect(walk(surface.props?.children)).toEqual([]); + expect(labels(walk(surface))).toEqual([]); + // the chrome is a sibling of the surface, so a pointer on a plate never reaches the surface's handlers + const root = els.find((e) => e.props?.['data-turning'] !== undefined) as El; + const kids = (root.props?.children as El[]).filter(Boolean); + expect(kids).toHaveLength(2); + expect(kids[0]).toBe(surface); + }); + + it('Escape is Return: the key listener closes the view', () => { + const listeners: Record void> = {}; + vi.stubGlobal('window', { + innerWidth: 1280, + innerHeight: 720, + addEventListener: (t: string, cb: (e: unknown) => void) => { + listeners[t] = cb; + }, + removeEventListener: () => undefined, + }); + SceneView(); + held.effects.forEach((run) => run()); + listeners.keydown({ key: 'Escape', stopPropagation: () => undefined }); + expect(held.closed).toBe(1); + }); +}); + +describe('one finger on the phone (ruling ridge-view-phone-one-finger)', () => { + const surface = () => + walk(SceneView()).find((e) => typeof e.props?.onPointerDown === 'function') as El; + const on = (name: string, evt: Record) => + (surface().props?.[name] as (e: unknown) => void)({ + currentTarget: { setPointerCapture: () => undefined }, + pointerId: 1, + pointerType: 'touch', + isPrimary: true, + button: 0, + clientX: 0, + clientY: 0, + ...evt, + }); + + it('the rail and the panel fade while a finger is down and come back when it lifts', () => { + expect(TURNING_CHROME_OPACITY).toBeGreaterThan(0); + expect(TURNING_CHROME_OPACITY).toBeLessThan(0.5); + on('onPointerDown', { clientX: 100 }); + on('onPointerUp', {}); + on('onPointerDown', { clientX: 100 }); + on('onPointerCancel', {}); + expect(held.turning).toEqual([true, false, true, false]); + }); + + it('only horizontal movement turns: the vertical is never given to the turner', () => { + on('onPointerDown', { clientX: 100, clientY: 50 }); + on('onPointerMove', { clientX: 140, clientY: 900 }); + on('onPointerMove', { clientX: 140, clientY: -900 }); + expect(held.turner).toEqual([['down', 100], ['move', 140], ['move', 140]]); + held.turner.length = 0; + on('onWheel', { deltaX: 2, deltaY: 90 }); + expect(held.turner).toEqual([]); // a mostly vertical wheel is not a turn either + }); + + it('a second finger (not the primary pointer) starts nothing', () => { + on('onPointerDown', { isPrimary: false, clientX: 100 }); + expect(held.turner).toEqual([]); + expect(held.turning).toEqual([]); + }); + + it('a mouse turns only with its main button', () => { + on('onPointerDown', { pointerType: 'mouse', button: 2, clientX: 100 }); + expect(held.turner).toEqual([]); + on('onPointerDown', { pointerType: 'mouse', button: 0, clientX: 100 }); + expect(held.turner).toEqual([['down', 100]]); + }); +}); + +describe('the chrome styles (a vanilla-extract rule cannot be read back, so the source is)', () => { + const css = readFileSync(join(__dirname, 'SceneView.css.ts'), 'utf8'); + it('the fade rule uses the constant the test above bounds', () => { + expect(css).toMatch(/data-turning="true"] &`]: { opacity: TURNING_CHROME_OPACITY }/); + }); + it('the chrome takes no pointer itself, so a drag over its gaps turns the view; its plates do', () => { + const chrome = css.slice(css.indexOf('export const Chrome'), css.indexOf('const Plate')); + expect(chrome).toContain("pointerEvents: 'none'"); + const plate = css.slice(css.indexOf('const Plate'), css.indexOf('export const Rail')); + expect(plate).toContain("pointerEvents: 'auto'"); + }); +}); diff --git a/src/app/features/scene/view/SceneView.tsx b/src/app/features/scene/view/SceneView.tsx new file mode 100644 index 00000000..854320b5 --- /dev/null +++ b/src/app/features/scene/view/SceneView.tsx @@ -0,0 +1,236 @@ +import React, { KeyboardEvent, useEffect, useMemo, useRef, useState } from 'react'; +import { Icon, IconButton, Icons } from 'folds'; +import FocusTrap from 'focus-trap-react'; +import { PhoneHit } from '../../../styles/PhoneHit.css'; +import { useRidgeManifest, useSceneViewState } from '../../../hooks/useSceneView'; +import { closeSceneView, setSubmenu } from '../sceneView'; +import type { Submenu } from '../sceneView'; +import { FALLBACK_VIEW } from '../ridge/view'; +import * as css from './SceneView.css'; +import { createTurner, pxPerDegreeOf } from './turning'; +import { PlaceSubmenu } from './PlaceSubmenu'; +import { SkySubmenu } from './SkySubmenu'; +import { TimeSubmenu } from './TimeSubmenu'; +import { ViewSubmenu } from './ViewSubmenu'; + +type IconSrc = React.ComponentProps['src']; + +/** The rail after Return, in order. */ +export const SUBMENUS: ReadonlyArray<{ id: Submenu; label: string; icon: IconSrc }> = [ + { id: 'view', label: 'View', icon: Icons.Eye }, + { id: 'time', label: 'Time', icon: Icons.Clock }, + { id: 'sky', label: 'Sky', icon: Icons.Star }, + { id: 'place', label: 'Place', icon: Icons.Pin }, +]; + +/** One icon of the rail: 44 px to tap on a phone (PhoneHit). */ +function RailButton({ + label, + icon, + pressed, + tabIndex, + buttonRef, + onClick, +}: { + label: string; + icon: IconSrc; + pressed?: boolean; + tabIndex: number; + buttonRef: (el: HTMLButtonElement | null) => void; + onClick: () => void; +}) { + return ( + + + + ); +} + +/** + * The icon rail, a vertical toolbar: Return first, then a submenu each. Roving focus: one stop in the Tab order, the arrow keys (Home, End) move along it. + * `active` is the submenu whose panel is up. + */ +export function Rail({ + items, + active, + onReturn, + onPick, +}: { + items: typeof SUBMENUS; + active: Submenu | undefined; + onReturn: () => void; + onPick: (id: Submenu) => void; +}) { + const [stop, setStop] = useState(0); + const buttons = useRef>([]); + const count = items.length + 1; + const goTo = (to: number) => { + const next = (to + count) % count; + setStop(next); + buttons.current[next]?.focus(); + }; + const onKeyDown = (evt: KeyboardEvent) => { + const moves: Record = { + ArrowDown: stop + 1, + ArrowUp: stop - 1, + Home: 0, + End: count - 1, + }; + const to = moves[evt.key]; + if (typeof to !== 'number') return; + evt.preventDefault(); + goTo(to); + }; + return ( +
+ { + buttons.current[0] = el; + }} + onClick={onReturn} + /> + {items.map((item, i) => ( + { + buttons.current[i + 1] = el; + }} + onClick={() => { + setStop(i + 1); + onPick(item.id); + }} + /> + ))} +
+ ); +} + +const typing = (t: EventTarget | null): boolean => + t instanceof HTMLInputElement || + t instanceof HTMLSelectElement || + t instanceof HTMLTextAreaElement; + +/** + * The scene view (sceneView.ts opens it): the whole viewport is a surface that turns the view by hand, and over it, top left, the rail of submenus and the + * one panel that is up. Return, Escape and the browser's Back all close it. The chat behind it stays mounted; nothing here navigates. + */ +export default function SceneView() { + const { submenu } = useSceneViewState(); + const manifest = useRidgeManifest(); + const surface = useRef(null); + const [turning, setTurning] = useState(false); + const [size, setSize] = useState(() => ({ w: window.innerWidth, h: window.innerHeight })); + + useEffect(() => { + const read = () => { + const el = surface.current; + setSize({ + w: el?.clientWidth || window.innerWidth, + h: el?.clientHeight || window.innerHeight, + }); + }; + read(); + window.addEventListener('resize', read); + return () => window.removeEventListener('resize', read); + }, []); + + // The turner reads the viewport and the place at each event, so a resize or a late manifest changes nothing it holds. + const latest = useRef({ manifest, size }); + latest.current = { manifest, size }; + const turner = useMemo( + () => + createTurner(() => + pxPerDegreeOf( + latest.current.manifest?.view ?? FALLBACK_VIEW, + latest.current.size.w, + latest.current.size.h + ) + ), + [] + ); + + useEffect(() => { + const onKey = (evt: globalThis.KeyboardEvent) => { + if (evt.key === 'Escape') { + evt.stopPropagation(); + closeSceneView(); + } else if (!typing(evt.target) && !evt.altKey && !evt.ctrlKey && !evt.metaKey) { + if (turner.key(evt.key, evt.shiftKey)) evt.preventDefault(); + } + }; + window.addEventListener('keydown', onKey); + return () => window.removeEventListener('keydown', onKey); + }, [turner]); + + const release = () => { + turner.up(); + setTurning(false); + }; + + return ( + +
+
{ + if (!evt.isPrimary || (evt.pointerType === 'mouse' && evt.button !== 0)) return; + evt.currentTarget.setPointerCapture?.(evt.pointerId); + turner.down(evt.clientX); + setTurning(true); + }} + onPointerMove={(evt) => turner.move(evt.clientX)} + onPointerUp={release} + onPointerCancel={release} + onWheel={(evt) => { + if (Math.abs(evt.deltaX) > Math.abs(evt.deltaY)) turner.wheel(evt.deltaX); + }} + /> +
+ + {submenu && ( +
s.id === submenu)?.label} + > + {submenu === 'view' && } + {submenu === 'time' && } + {submenu === 'sky' && } + {submenu === 'place' && } +
+ )} +
+
+ + ); +} diff --git a/src/app/features/scene/view/SkySubmenu.tsx b/src/app/features/scene/view/SkySubmenu.tsx new file mode 100644 index 00000000..22d223e1 --- /dev/null +++ b/src/app/features/scene/view/SkySubmenu.tsx @@ -0,0 +1,26 @@ +import React from 'react'; +import { Box, Switch, Text } from 'folds'; +import { useConstellationLines } from '../../../hooks/useSceneView'; +import { setConstellationLines } from '../skyState'; + +/** The Sky submenu of the scene view: the constellation lines, an explicit option per viewer (it replaces the hidden re-pick of Night). Its data credits are in Place. */ +export function SkySubmenu() { + const lines = useConstellationLines(); + return ( + + + + Constellation lines + + setConstellationLines(on)} + /> + + + Drawn over the stars of a night sky. + + + ); +} diff --git a/src/app/features/scene/view/TimeSubmenu.test.tsx b/src/app/features/scene/view/TimeSubmenu.test.tsx new file mode 100644 index 00000000..5b6b70e9 --- /dev/null +++ b/src/app/features/scene/view/TimeSubmenu.test.tsx @@ -0,0 +1,163 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import type { SkyChoice } from '../ridge/skyMoment'; +import { FALLBACK_VIEW } from '../ridge/view'; +import { + MENU_CHOICES, + SkyMomentPicker, + TimeSubmenu, + choiceLabel, + useNativeChange, +} from './TimeSubmenu'; + +// 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(); + 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, +})); + +type El = { type?: unknown; ref?: unknown; props?: Record }; +/** 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 Time submenu choices', () => { + const tree = () => walk(TimeSubmenu()); + const radios = () => tree().filter((e) => e.props?.role === 'radio'); + + 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(tree().find((e) => e.props?.role === 'radiogroup')?.props?.['aria-label']).toBe('Time'); + 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)); + }); +}); + +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((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+/); + }); +}); diff --git a/src/app/features/scene/view/TimeSubmenu.tsx b/src/app/features/scene/view/TimeSubmenu.tsx new file mode 100644 index 00000000..540079d0 --- /dev/null +++ b/src/app/features/scene/view/TimeSubmenu.tsx @@ -0,0 +1,164 @@ +import React, { useEffect, useRef, useState } from 'react'; +import { Box, config, Icon, Icons, MenuItem, Text } from 'folds'; +import { useDrawnPlace, useSkyChoice } from '../../../hooks/useSkyState'; +import { setSkyChoice, 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'; + +export const MOMENT_LABEL: Record = { + dawn: 'Dawn', + morning: 'Morning', + noon: 'Noon', + golden: 'Golden hour', + dusk: 'Dusk', + night: 'Night', +}; + +export const hhmm = (minutes: number): string => + `${String(Math.floor(minutes / 60)).padStart(2, '0')}:${String(minutes % 60).padStart(2, '0')}`; + +/** What the panel calls a choice: Auto, the moment's name, or the free moment's place-local date and time. */ +export function choiceLabel(c: SkyChoice): string { + if (c.kind === 'auto') return 'Auto'; + return c.kind === 'named' ? MOMENT_LABEL[c.id] : `${c.date} ${hhmm(c.minutes)}`; +} + +/** The choices the panel 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); + +/** + * Run `onChange` on the element's native `change` event: for a slider, its release, not every `input` tick (React's onChange is the + * input event). Each commit rebuilds the scene or re-issues the rig, so a drag must commit once. + */ +export function useNativeChange(onChange: (el: T) => void) { + const ref = useRef(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; + +/** 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((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((el) => { + at.current.minutes = Number(el.value); + onCommit({ kind: 'free', ...at.current }); + }); + const zone = zoneName(zonedInstant(at.current.date, minutes, tz), tz); + return ( + + + setMinutes(Number(evt.currentTarget.value))} + /> + + {hhmm(minutes)} {zone} + + + ); +} + +/** + * The Time submenu of the scene view: Auto, the six named moments of today at the place, and a free date and time (ruling ridge-sky-menu-moments, unchanged; + * this is that menu's contents). A pick goes to the sky choice store, as the menu's did. + */ +export function TimeSubmenu() { + const choice = useSkyChoice(); + const drawn = useDrawnPlace(); + const [picking, setPicking] = useState(false); + const place = drawn ?? FALLBACK_VIEW.place; + return ( + + {MENU_CHOICES.map((c) => { + const checked = sameChoice(c, choice); + return ( + setSkyChoice(c)} + after={checked ? : undefined} + > + + {choiceLabel(c)} + + + ); + })} + setPicking(!picking)} + after={choice.kind === 'free' ? : undefined} + > + + Pick a moment + + + {picking && ( + + )} + + ); +} diff --git a/src/app/features/scene/view/ViewSubmenu.test.tsx b/src/app/features/scene/view/ViewSubmenu.test.tsx new file mode 100644 index 00000000..32d60e06 --- /dev/null +++ b/src/app/features/scene/view/ViewSubmenu.test.tsx @@ -0,0 +1,153 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { parseManifest } from '../ridge/manifest'; +import { wireManifest } from '../ridge/manifest.fixture'; +import { maxSpeed, offsetRange, SPEED_CEILING_DEG_S, windowFor } from '../ridge/view'; +import type { CameraChoice } from '../cameraState'; +import { ViewSubmenu, floorToTenth, offsetBounds, speedBounds } from './ViewSubmenu'; + +// The hooks are held still, as in TimeSubmenu.test.tsx: the element tree is read, a function component is expanded by calling it, and the native events +// are dispatched on a fake input. +const held = vi.hoisted(() => ({ + effects: [] as Array<() => unknown>, + cam: { mode: 'both', speedDegPerS: 0.6, offsetM: 200 } as unknown, + heldView: false, + commits: [] as unknown[], +})); +vi.mock('react', async (importOriginal) => { + const actual = await importOriginal(); + 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/useSceneView', () => ({ + useCamera: () => held.cam, + useCameraHeld: () => held.heldView, +})); +vi.mock('../cameraState', () => ({ setCamera: (c: unknown) => held.commits.push(c) })); + +type El = { type?: unknown; ref?: unknown; props?: Record }; +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 fakeInput = (value: string) => Object.assign(new EventTarget(), { value }); +const fire = (el: EventTarget, type: 'input' | 'change') => el.dispatchEvent(new Event(type)); + +const manifest = parseManifest(wireManifest(), 'http://x/ridge/vienna/'); +const SIZE = { w: 1920, h: 1080 }; +const tree = () => walk(ViewSubmenu({ manifest, size: SIZE })); +const slider = (label: string) => tree().find((e) => e.props?.label === label); + +beforeEach(() => { + held.effects.length = 0; + held.commits.length = 0; + held.cam = { mode: 'both', speedDegPerS: 0.6, offsetM: 200 } satisfies CameraChoice; + held.heldView = false; +}); + +describe('the View submenu', () => { + it('lists the three rotation modes, the chosen one checked, and picking one sets the camera mode', () => { + const radios = () => tree().filter((e) => e.props?.role === 'radio'); + expect(radios().map((e) => e.props?.['aria-checked'])).toEqual([false, false, true]); + held.cam = { mode: 'still', speedDegPerS: 0.6, offsetM: 0 }; + expect(radios().map((e) => e.props?.['aria-checked'])).toEqual([true, false, false]); + (radios()[1].props?.onClick as () => void)(); + expect(held.commits).toEqual([{ mode: 'offset' }]); + }); + + it('the speed slider is bounded by what the baked place sustains in the mode, never past the ceiling', () => { + for (const mode of ['still', 'offset', 'both'] as const) { + const [lo, hi] = speedBounds(manifest, mode); + expect(lo).toBe(0); + expect(hi).toBeLessThanOrEqual(maxSpeed(manifest, mode)); + expect(hi).toBeLessThanOrEqual(SPEED_CEILING_DEG_S); + expect(hi).toBeGreaterThan(maxSpeed(manifest, mode) - 0.1 - 1e-9); + } + held.cam = { mode: 'both', speedDegPerS: 99, offsetM: 0 }; + const s = slider('Rotation speed'); + expect(s?.props?.max).toBe(speedBounds(manifest, 'both')[1]); + expect(s?.props?.value).toBe(speedBounds(manifest, 'both')[1]); // a stored speed past the bound shows at the bound + expect(speedBounds(undefined, 'both')).toEqual([0, SPEED_CEILING_DEG_S]); + }); + + it('the speed bound is the place\'s own, far under the global ceiling, when the ring is cut as the baker cuts it', () => { + const ring = parseManifest(wireManifest({}, 3, 32), 'http://x/ridge/vienna/'); + const slow = maxSpeed(ring, 'both'); + expect(slow).toBeLessThan(SPEED_CEILING_DEG_S / 4); + const [, hi] = speedBounds(ring, 'both'); + expect(hi).toBeLessThanOrEqual(slow); + expect(hi).toBeGreaterThan(slow - 0.1); + expect(hi).toBeLessThan(SPEED_CEILING_DEG_S); + expect(speedBounds(ring, 'offset')[1]).toBe(SPEED_CEILING_DEG_S); // the modes with no bound take the ceiling + held.cam = { mode: 'both', speedDegPerS: 99, offsetM: 0 }; + const s = walk(ViewSubmenu({ manifest: ring, size: SIZE })).find( + (e) => e.props?.label === 'Rotation speed' + ); + expect(s?.props?.max).toBe(hi); + expect(s?.props?.value).toBe(hi); + }); + + it('no stepped bound exceeds the speed it bounds: a tenth multiplied in floats is not trusted', () => { + for (let k = 0; k <= 120; k += 1) { + const v = Number(`${k / 10}`); + expect(floorToTenth(v)).toBeLessThanOrEqual(v); + expect(floorToTenth(v + 0.04)).toBeGreaterThanOrEqual(v); + } + expect(floorToTenth(0.3)).toBeLessThanOrEqual(0.3); + expect(floorToTenth(0.975)).toBe(0.9); + }); + + it('the offset slider spans offsetRange for the mode on this viewport, signed, and follows the mode', () => { + const win = windowFor(manifest.view, SIZE.w, SIZE.h); + const [lo, hi] = offsetRange(manifest, win, 'both'); + const s = slider('Parallax offset'); + expect(s?.props?.min).toBeLessThanOrEqual(0); + expect(s?.props?.min).toBeGreaterThanOrEqual(lo); + expect(s?.props?.min as number).toBeGreaterThan(lo - 5); + expect(s?.props?.max).toBeLessThanOrEqual(hi); + expect(s?.props?.max as number).toBeGreaterThan(hi - 5); + expect(offsetBounds(manifest, SIZE, 'offset')[1]).toBeLessThanOrEqual(manifest.camera.rMaxM); + held.cam = { mode: 'offset', speedDegPerS: 0.6, offsetM: 200 }; + const [, ohi] = offsetRange(manifest, win, 'offset'); + expect((slider('Parallax offset')?.props?.max as number) <= ohi).toBe(true); + }); + + it('a slider commits once, on release, not on each input tick', () => { + const s = slider('Parallax offset') as El; + const expanded = walk((s.type as (p: unknown) => unknown)(s.props)); + const range = expanded.find((e) => e.type === 'input') as El; + const input = fakeInput('120'); + (range.ref as { current: unknown }).current = input; + held.effects.forEach((run) => run()); + for (let i = 0; i < 5; i += 1) fire(input, 'input'); + expect(held.commits).toEqual([]); + fire(input, 'change'); + expect(held.commits).toEqual([{ offsetM: 120 }]); + }); + + it('says so while a manual turn holds the view', () => { + const text = () => + walk(ViewSubmenu({ manifest, size: SIZE })) + .map((e) => e.props?.children) + .filter((c) => typeof c === 'string' && /Held/.test(c)); + expect(text()).toEqual([]); + held.heldView = true; + expect(text()).toHaveLength(1); + }); +}); diff --git a/src/app/features/scene/view/ViewSubmenu.tsx b/src/app/features/scene/view/ViewSubmenu.tsx new file mode 100644 index 00000000..33286fc2 --- /dev/null +++ b/src/app/features/scene/view/ViewSubmenu.tsx @@ -0,0 +1,156 @@ +import React, { useState } from 'react'; +import { Box, Icon, Icons, MenuItem, Text } from 'folds'; +import { setCamera } from '../cameraState'; +import type { CameraChoice } from '../cameraState'; +import { useCamera, useCameraHeld } from '../../../hooks/useSceneView'; +import type { RotationMode } from '../ridge/heading'; +import type { RidgeManifest } from '../ridge/manifest'; +import { maxSpeed, offsetRange, SPEED_CEILING_DEG_S, windowFor } from '../ridge/view'; +import { useNativeChange } from './TimeSubmenu'; + +export const MODE_CHOICES: ReadonlyArray<{ mode: RotationMode; label: string }> = [ + { mode: 'still', label: 'No rotation' }, + { mode: 'offset', label: 'Rotate parallax offset only' }, + { mode: 'both', label: 'Rotate offset and view direction' }, +]; + +const SPEED_STEP = 0.1; +const OFFSET_STEP = 5; + +/** `v` rounded down to a tenth of a degree a second, never above `v` (a step multiplied in floats can overshoot: 3 x 0.1 is more than 0.3). */ +export const floorToTenth = (v: number): number => Math.min(v, Math.floor(v * 10) / 10); + +/** The speed slider's bounds: nothing to the fastest the baked place sustains in the mode picked (`view.ts` `maxSpeed`), the ceiling with no bake to ask; the top never exceeds it. */ +export const speedBounds = ( + manifest: RidgeManifest | undefined, + mode: RotationMode +): [number, number] => [ + 0, + floorToTenth(manifest ? maxSpeed(manifest, mode) : SPEED_CEILING_DEG_S), +]; + +/** The offset slider's bounds in metres, signed: `view.ts` `offsetRange` for the mode on this viewport, rounded in to the slider's step. */ +export const offsetBounds = ( + manifest: RidgeManifest, + size: { w: number; h: number }, + mode: RotationMode +): [number, number] => { + const [lo, hi] = offsetRange(manifest, windowFor(manifest.view, size.w, size.h), mode); + return [Math.ceil(lo / OFFSET_STEP) * OFFSET_STEP, Math.floor(hi / OFFSET_STEP) * OFFSET_STEP]; +}; + +const clamp = (v: number, lo: number, hi: number): number => Math.min(hi, Math.max(lo, v)); +const signed = (m: number): string => `${m > 0 ? '+' : ''}${m} m`; + +/** A slider that commits on release (the native change event), the readout following the drag. */ +function Slider({ + label, + min, + max, + step, + value, + readout, + onCommit, +}: { + label: string; + min: number; + max: number; + step: number; + value: number; + readout: (v: number) => string; + onCommit: (v: number) => void; +}) { + const [shown, setShown] = useState(value); + const ref = useNativeChange((el) => onCommit(Number(el.value))); + return ( + + + {label} + + {readout(shown)} + + + setShown(Number(evt.currentTarget.value))} + /> + + ); +} + +/** + * The View submenu of the scene view: the rotation mode, its speed and the camera's parallax offset, written to the camera store (`cameraState.ts`), which the + * heading owner reads. The sliders commit on release; the speed is bounded by what the baked place sustains in the mode, the offset by `offsetRange`, which + * is signed (ruling ridge-camera-offset-signed). Picking a mode resumes a rotation a manual turn held (ruling ridge-view-turn-handback). + */ +export function ViewSubmenu({ + manifest, + size, +}: { + manifest: RidgeManifest | undefined; + /** The viewport the scene is drawn on, px: the offset's bound depends on it. */ + size: { w: number; h: number }; +}) { + const cam: CameraChoice = useCamera(); + const held = useCameraHeld(); + const [, speedMax] = speedBounds(manifest, cam.mode); + const range = manifest ? offsetBounds(manifest, size, cam.mode) : undefined; + return ( + + + {MODE_CHOICES.map(({ mode, label }) => { + const checked = cam.mode === mode; + return ( + setCamera({ mode })} + after={checked ? : undefined} + > + + {label} + + + ); + })} + {held && ( + + Held where you turned it. Pick a rotation to let it turn again. + + )} + + `${v.toFixed(1)} deg/s`} + onCommit={(speedDegPerS) => setCamera({ speedDegPerS })} + /> + {range && ( + setCamera({ offsetM })} + /> + )} + + ); +} diff --git a/src/app/features/scene/view/turning.test.ts b/src/app/features/scene/view/turning.test.ts new file mode 100644 index 00000000..da1bf6c9 --- /dev/null +++ b/src/app/features/scene/view/turning.test.ts @@ -0,0 +1,80 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { isHeld, resetCamera } from '../cameraState'; +import { poseAt, resetHeading } from '../ridge/heading'; +import { FALLBACK_VIEW } from '../ridge/view'; +import { createTurner, dragHeading, keyTurn, pxPerDegreeOf } from './turning'; + +beforeEach(() => { + vi.stubGlobal('localStorage', { + getItem: () => null, + setItem: () => undefined, + removeItem: () => undefined, + }); + resetCamera(); + resetHeading(); +}); + +const PX = FALLBACK_VIEW.pxPerDegH * 1.65; // 17.78 px per degree of plane at the scale 1.65 + +describe('manual turning', () => { + it('a drag turns the view against the finger, one for one with the far sky: 100 px at plane scale 1.65', () => { + expect(dragHeading(100, 100, PX)).toBeCloseTo(100 - 100 / (17.7777778 * 1.65), 6); + expect(dragHeading(100, -100, PX)).toBeGreaterThan(100); + }); + + it('pxPerDegreeOf is the plane pixels per degree at the viewport scale (windowFor)', () => { + // 1280 x 720 on the fallback plane: scale max(0.6 x 720 / 600, 1280 / (65.45 x 17.78)) = 1.1 + expect(pxPerDegreeOf(FALLBACK_VIEW, 1280, 720)).toBeCloseTo(FALLBACK_VIEW.pxPerDegH * 1.1, 1); + }); + + it('the heading owner holds the view where the drag leaves it, on every move, and not before a move', () => { + let t = 0; + const turner = createTurner( + () => PX, + () => t + ); + poseAt(0); // a fresh page: the owner is anchored at heading 0 + turner.down(500); + expect(isHeld()).toBe(false); // a tap that does not move holds nothing + t = 16; + turner.move(400); + expect(isHeld()).toBe(true); + expect(poseAt(16).h).toBeCloseTo(100 / PX, 6); + t = 32; + turner.move(300); + expect(poseAt(32).h).toBeCloseTo(200 / PX, 6); + turner.up(); + t = 48; + turner.move(0); // no finger down: nothing moves + expect(poseAt(48).h).toBeCloseTo(200 / PX, 6); + }); + + it('arrows turn 5 degrees and with Shift 15; other keys are not turns', () => { + expect(keyTurn('ArrowRight', false)).toBe(5); + expect(keyTurn('ArrowLeft', false)).toBe(-5); + expect(keyTurn('ArrowLeft', true)).toBe(-15); + expect(keyTurn('ArrowUp', false)).toBeUndefined(); + const turner = createTurner( + () => PX, + () => 0 + ); + poseAt(0); + expect(turner.key('ArrowRight', false)).toBe(true); + expect(poseAt(0).h).toBeCloseTo(5, 9); + expect(turner.key('ArrowLeft', true)).toBe(true); + expect(poseAt(0).h).toBeCloseTo(-10, 9); + expect(turner.key('Enter', false)).toBe(false); + }); + + it('a horizontal wheel or swipe turns one for one the other way from a drag', () => { + const turner = createTurner( + () => PX, + () => 0 + ); + poseAt(0); + turner.wheel(PX * 3); + expect(poseAt(0).h).toBeCloseTo(3, 9); + turner.wheel(0); + expect(poseAt(0).h).toBeCloseTo(3, 9); + }); +}); diff --git a/src/app/features/scene/view/turning.ts b/src/app/features/scene/view/turning.ts new file mode 100644 index 00000000..37fd5295 --- /dev/null +++ b/src/app/features/scene/view/turning.ts @@ -0,0 +1,61 @@ +// Manual turning, inside the scene view only: the one place a pointer, a key or a wheel becomes a heading. The sky is at infinity and pans one for one with the +// view direction, so a drag of `dx` px is `dx / (pxPerDegH x plane.scale)` degrees (`view.ts` `windowFor`), against the finger: the sky follows it. Every turn goes to +// the heading owner (`ridge/heading.ts` `hold`), which holds the view where it was left until a rotation mode is picked or Return is pressed (ruling +// ridge-view-turn-handback). The rig is re-issued by the owner on each hold, so while a finger is down this is the one script that moves the ridge besides the +// twinkle. Pitch is never turned (ruling ridge-frame-more-sky-fixed-pitch). +import { hold, poseAt } from '../ridge/heading'; +import { windowFor } from '../ridge/view'; +import type { View } from '../ridge/view'; + +/** Degrees an arrow key turns the view, and with Shift. */ +export const KEY_STEP_DEG = 5; +export const KEY_STEP_SHIFT_DEG = 15; + +/** Screen pixels per degree of the far sky on a viewport `w` x `h`: the plane's pixels per degree at the scale the viewport gives it. */ +export const pxPerDegreeOf = (view: View, w: number, h: number): number => + view.pxPerDegH * windowFor(view, w, h).plane.scale; + +/** The heading after a drag of `dxPx` from where it began at `h0`: against the finger, one for one with the sky. */ +export const dragHeading = (h0: number, dxPx: number, pxPerDeg: number): number => + h0 - dxPx / pxPerDeg; + +/** The turn an arrow key asks, degrees (right positive), or undefined for any other key. */ +export function keyTurn(key: string, shift: boolean): number | undefined { + const step = shift ? KEY_STEP_SHIFT_DEG : KEY_STEP_DEG; + if (key === 'ArrowRight') return step; + return key === 'ArrowLeft' ? -step : undefined; +} + +/** What the view's surface does with the events it is given: `pxPerDeg` is read at each event (a resize or a place changes it), `now` is the heading owner's clock. */ +export function createTurner(pxPerDeg: () => number, now: () => number = () => performance.now()) { + let drag: { x0: number; h0: number } | undefined; + const turnBy = (deg: number) => { + const t = now(); + hold(poseAt(t).h + deg, t); + }; + return { + /** A finger or the mouse went down at `x`. */ + down(x: number): void { + drag = { x0: x, h0: poseAt(now()).h }; + }, + /** It moved to `x`: the view faces where the drag puts it. Nothing before `down`. */ + move(x: number): void { + if (drag) hold(dragHeading(drag.h0, x - drag.x0, pxPerDeg()), now()); + }, + up(): void { + drag = undefined; + }, + isDown: (): boolean => drag !== undefined, + /** A horizontal wheel or trackpad swipe of `deltaX` px: the sky follows the fingers, so the view turns the other way from a drag. */ + wheel(deltaX: number): void { + if (deltaX !== 0) turnBy(deltaX / pxPerDeg()); + }, + /** An arrow key; true when it turned the view. */ + key(key: string, shift: boolean): boolean { + const deg = keyTurn(key, shift); + if (deg === undefined) return false; + turnBy(deg); + return true; + }, + }; +} diff --git a/src/app/features/settings/general/General.tsx b/src/app/features/settings/general/General.tsx index e0835eff..90d2da3a 100644 --- a/src/app/features/settings/general/General.tsx +++ b/src/app/features/settings/general/General.tsx @@ -82,7 +82,6 @@ function SelectTheme({ disabled }: { disabled?: boolean }) { const themes = useThemes(); const themeNames = useThemeNames(); const [themeId, setThemeId] = useSetting(settingsAtom, 'themeId'); - const [, setThemeChosen] = useSetting(settingsAtom, 'themeChosen'); const [menuCords, setMenuCords] = useState(); const selectedTheme = themes.find((theme) => theme.id === themeId) ?? LightTheme; @@ -92,7 +91,6 @@ function SelectTheme({ disabled }: { disabled?: boolean }) { const handleThemeSelect = (theme: Theme) => { setThemeId(theme.id); - setThemeChosen(true); setMenuCords(undefined); }; diff --git a/src/app/hooks/useSceneView.test.ts b/src/app/hooks/useSceneView.test.ts new file mode 100644 index 00000000..6b75a9c8 --- /dev/null +++ b/src/app/hooks/useSceneView.test.ts @@ -0,0 +1,30 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { useSceneViewOffered } from './useSceneView'; + +const held = vi.hoisted(() => ({ config: undefined as unknown })); +vi.mock('./useClientConfig', () => ({ useClientConfig: () => ({ backgroundScene: held.config }) })); + +const device = (nav: Record) => vi.stubGlobal('navigator', nav); +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('whether the scene view is offered', () => { + it('is not with the tier off or absent, and is with any tier on', () => { + device({}); + held.config = undefined; + expect(useSceneViewOffered()).toBe(false); + held.config = { tier: 'off' }; + expect(useSceneViewOffered()).toBe(false); + for (const tier of ['still', 'low', 'full']) { + held.config = { tier }; + expect(useSceneViewOffered()).toBe(true); + } + }); + + it('follows the tier the device allows, not the one configured: no device ceiling turns a configured tier off', () => { + device({ connection: { saveData: true } }); + held.config = { tier: 'full' }; + expect(useSceneViewOffered()).toBe(true); // lowered to still, still a scene + }); +}); diff --git a/src/app/hooks/useSceneView.ts b/src/app/hooks/useSceneView.ts new file mode 100644 index 00000000..a1f33317 --- /dev/null +++ b/src/app/hooks/useSceneView.ts @@ -0,0 +1,79 @@ +import { useEffect, useState, useSyncExternalStore } from 'react'; +import { getCamera, isHeld, subscribe as subscribeCamera } from '../features/scene/cameraState'; +import type { CameraChoice } from '../features/scene/cameraState'; +import { getSceneView, subscribeSceneView } from '../features/scene/sceneView'; +import type { SceneViewState } from '../features/scene/sceneView'; +import { getConstellationLines, subscribe as subscribeSky } from '../features/scene/skyState'; +import { listPlaces } from '../features/scene/ridge/manifest'; +import type { PlaceListing, RidgeManifest } from '../features/scene/ridge/manifest'; +import { getPlaceChoice, subscribePlaceChoice } from '../features/scene/placeState'; +import { loadPlaceManifest } from '../features/scene/skyPlace'; +import { readCapabilities, resolveTier } from '../features/scene/tier'; +import { useClientConfig } from './useClientConfig'; + +/** Whether the scene view is open and which submenu is up (sceneView.ts). */ +export const useSceneViewState = (): SceneViewState => + useSyncExternalStore(subscribeSceneView, getSceneView); + +const onCamera = (cb: () => void): (() => void) => { + const off = subscribeCamera(() => cb()); + return () => { + off(); + }; +}; + +/** The viewer's rotation mode, speed and offset (cameraState.ts). */ +export const useCamera = (): CameraChoice => useSyncExternalStore(onCamera, getCamera); + +/** Whether a manual turn holds the view (cameraState.ts): the rotation waits for a mode pick or Return. */ +export const useCameraHeld = (): boolean => useSyncExternalStore(onCamera, isHeld); + +/** Whether the constellation lines are on (skyState.ts). */ +export const useConstellationLines = (): boolean => + useSyncExternalStore(subscribeSky, getConstellationLines); + +/** The viewer's picked place id (placeState.ts), undefined for none. */ +export const usePlaceChoice = (): string | undefined => + useSyncExternalStore(subscribePlaceChoice, getPlaceChoice); + +/** The baked places the carousel offers (`listPlaces`: memoised, so the session reads them once); undefined until they have loaded, and when the index or its manifests do not load. */ +export function usePlaceList(): PlaceListing[] | undefined { + const [list, setList] = useState(); + useEffect(() => { + let live = true; + listPlaces(import.meta.env.BASE_URL).then( + (l) => live && setList(l), + () => live && setList(undefined) + ); + return () => { + live = false; + }; + }, []); + return list; +} + +/** The manifest of the place being drawn (the viewer's choice, else the config's, else the index's default: skyPlace.ts) when the ridge scene is on and it has loaded (memoised by `loadManifest`, so this fetches nothing the scene did not). */ +export function useRidgeManifest(): RidgeManifest | undefined { + const config = useClientConfig().backgroundScene; + const ridgeOn = !!config && config.style !== 'raymarch'; + const choice = usePlaceChoice(); + const [manifest, setManifest] = useState(); + useEffect(() => { + if (!ridgeOn) return undefined; + let live = true; + loadPlaceManifest(config).then( + (m) => live && setManifest(m), + () => live && setManifest(undefined) + ); + return () => { + live = false; + }; + }, [ridgeOn, config, choice]); + return ridgeOn ? manifest : undefined; +} + +/** Whether the scene view is offered: the background scene is not switched off (tier). The one answer, for the entry and the host. */ +export function useSceneViewOffered(): boolean { + const config = useClientConfig().backgroundScene; + return resolveTier(config, readCapabilities(navigator)) !== 'off'; +} diff --git a/src/app/hooks/useSkyState.test.ts b/src/app/hooks/useSkyState.test.ts new file mode 100644 index 00000000..4e2e7db9 --- /dev/null +++ b/src/app/hooks/useSkyState.test.ts @@ -0,0 +1,64 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { setSkyClock } from '../features/scene/skyState'; +import { useSkyMinute } from './useSkyState'; + +// useSkyMinute is state and one effect: react is held so the effect can be run and cleaned up by hand. +const held = vi.hoisted(() => ({ + value: undefined as unknown, + sets: [] as Date[], + effect: undefined as undefined | (() => (() => void) | undefined), +})); +vi.mock('react', async (importOriginal) => { + const actual = await importOriginal(); + const useState = (init: unknown) => { + held.value ??= typeof init === 'function' ? (init as () => unknown)() : init; + return [held.value, (v: Date) => held.sets.push(v)]; + }; + const useEffect = (fn: () => (() => void) | undefined) => { + held.effect = fn; + }; + return { ...actual, useState, useEffect }; +}); + +const at = (iso: string) => setSkyClock(() => new Date(iso)); +beforeEach(() => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + held.value = undefined; + held.sets.length = 0; +}); +afterEach(() => { + vi.useRealTimers(); + setSkyClock(); +}); + +describe('the sky minute', () => { + it('while live, re-reads the sky clock at each minute boundary and stops when the effect is cleaned up', () => { + at('2030-06-21T10:00:30Z'); + expect(useSkyMinute(true)).toEqual(new Date('2030-06-21T10:00:30Z')); + const stop = held.effect?.(); + held.sets.length = 0; + at('2030-06-21T10:01:00Z'); + vi.advanceTimersByTime(29_999); + expect(held.sets).toHaveLength(0); // not before the minute turns + vi.advanceTimersByTime(1); + expect(held.sets).toEqual([new Date('2030-06-21T10:01:00Z')]); + at('2030-06-21T10:02:00Z'); + vi.advanceTimersByTime(60_000); + expect(held.sets).toHaveLength(2); + stop?.(); + vi.advanceTimersByTime(10 * 60_000); + expect(held.sets).toHaveLength(2); + }); + + it('not live, sets no timer and reads the sky clock at every render', () => { + at('2030-06-21T10:00:30Z'); + useSkyMinute(false); + const stop = held.effect?.(); + expect(stop).toBeUndefined(); + held.sets.length = 0; + vi.advanceTimersByTime(10 * 60_000); + expect(held.sets).toHaveLength(0); + at('2030-06-22T01:00:00Z'); + expect(useSkyMinute(false)).toEqual(new Date('2030-06-22T01:00:00Z')); + }); +}); diff --git a/src/app/hooks/useSkyState.ts b/src/app/hooks/useSkyState.ts index c32979ae..e25b35c7 100644 --- a/src/app/hooks/useSkyState.ts +++ b/src/app/hooks/useSkyState.ts @@ -1,21 +1,41 @@ -import { useSyncExternalStore } from 'react'; -import { - getResolvedSkyState, - getSkyState, - subscribe, - type SkyState, -} from '../features/scene/skyState'; -import type { FixedSkyState } from '../features/scene/skyBand'; -import { readCapabilities, resolveTier } from '../features/scene/tier'; -import { useClientConfig } from './useClientConfig'; +import { useEffect, useState, useSyncExternalStore } from 'react'; +import { getSkyChoice, getSkyPlace, skyNow, subscribe } from '../features/scene/skyState'; +import type { Place } from '../features/scene/ridge/view'; +import type { FixedSkyState, SkyChoice } from '../features/scene/ridge/skyMoment'; +import { getDrawnSky, getSceneDrawn, subscribeSceneDrawn } from '../features/scene/sceneDrawn'; -/** The choice, as the control shows it ('auto' stays 'auto'). The sky being drawn is `useResolvedSkyState`. */ -export const useSkyState = (): SkyState => useSyncExternalStore(subscribe, getSkyState); +/** The choice, as the control shows it (Auto stays Auto). The sky being drawn is `useDrawnSky`. */ +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. */ -export const useResolvedSkyState = (): FixedSkyState => - useSyncExternalStore(subscribe, getResolvedSkyState); +/** The sky the scene that is up draws: day, dusk or night, or undefined with no scene. It moves when a scene replaces the one shown, not when the clock or the choice announces a band the scene has not caught up with. */ +export const useDrawnSky = (): FixedSkyState | undefined => useSyncExternalStore(subscribeSceneDrawn, getDrawnSky); -/** Whether a background scene runs on this device and config (the tier the scene host will mount). */ -export const useSceneOn = (): boolean => - resolveTier(useClientConfig().backgroundScene, readCapabilities(navigator)) !== 'off'; +/** 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. */ +export const useSceneOn = (): boolean => useSyncExternalStore(subscribeSceneDrawn, getSceneDrawn); + +const MINUTE_MS = 60_000; + +/** + * The sky's clock (`skyNow`) for a surface that shows the minute: re-read at every minute boundary while `live` (the sky follows the clock: Auto), and at each + * render otherwise, since a frozen moment does not move with it. The clock is the sky's own; this holds no second one. + */ +export function useSkyMinute(live: boolean): Date { + const [now, setNow] = useState(skyNow); + useEffect(() => { + setNow(skyNow()); + if (!live) return undefined; + let timer: ReturnType; + const next = () => { + timer = setTimeout(() => { + setNow(skyNow()); + next(); + }, MINUTE_MS - (skyNow().getTime() % MINUTE_MS)); + }; + next(); + return () => clearTimeout(timer); + }, [live]); + return live ? now : skyNow(); +} diff --git a/src/app/hooks/useTheme.test.ts b/src/app/hooks/useTheme.test.ts index dcb96e49..90c543f9 100644 --- a/src/app/hooks/useTheme.test.ts +++ b/src/app/hooks/useTheme.test.ts @@ -1,40 +1,95 @@ -import { readFileSync } from 'fs'; -import { beforeAll, describe, expect, it, vi } from 'vitest'; +import { createElement } from 'react'; +import { renderToString } from 'react-dom/server'; +import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; -// settings.ts reads localStorage when it loads, and this suite runs without a DOM. -vi.stubGlobal('localStorage', { getItem: () => null, setItem: () => undefined }); -let chosenTheme: typeof import('./useTheme').chosenTheme; -let defaultThemeId: string; +// settings.ts reads localStorage when it loads; these suites run without a DOM. +const store: Record = {}; +vi.stubGlobal('localStorage', { + getItem: (k: string) => store[k] ?? null, + setItem: (k: string, v: string) => { + store[k] = v; + }, +}); +// Stored before settings.ts loads: a theme of the person's, and the themeChosen key old settings carry. +store['settings'] = JSON.stringify({ + themeId: 'dark-theme', + useSystemTheme: false, + themeChosen: true, +}); +vi.stubGlobal('window', { + matchMedia: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }), +}); +// The skyState hooks are useSyncExternalStore reads of these two sources; the server renderer needs a snapshot of +// each, so the hooks read the same stores directly. +vi.mock('./useSkyState', async () => { + const drawn = await import('../features/scene/sceneDrawn'); + return { + useDrawnSky: () => drawn.getDrawnSky(), + useSkyChoice: () => ({ kind: 'named', id: 'night' }), + useSceneOn: () => drawn.getSceneDrawn(), + }; +}); +// Style modules need a DOM to inject into; the class names are not what is under test. +vi.mock('folds', () => ({ lightTheme: 'light' })); +vi.mock('../../config.css', () => ({ onDarkFontWeight: 'dk', onLightFontWeight: 'lt' })); +vi.mock('../../colors.css', () => ({ + butterTheme: 'b', + darkTheme: 'd', + midnightSkyTheme: 'm', + noondaySkyTheme: 'n', + silverTheme: 's', +})); +vi.mock('../../gamecult.css', () => ({})); +vi.mock('../../sky.css', () => ({})); +vi.mock('./useScreenSize', () => ({ + ScreenSize: { Mobile: 'm' }, + useScreenSizeContext: () => 'd', +})); + +let useActiveTheme: typeof import('./useTheme').useActiveTheme; +let useSceneInk: typeof import('./useTheme').useSceneInk; +let setSceneDrawn: typeof import('../features/scene/sceneDrawn').setSceneDrawn; beforeAll(async () => { - ({ chosenTheme } = await import('./useTheme')); - ({ defaultThemeId } = await import('../state/settings')); + ({ useActiveTheme, useSceneInk } = await import('./useTheme')); + ({ setSceneDrawn } = await import('../features/scene/sceneDrawn')); }); -describe('chosenTheme: what counts as a theme the person chose', () => { - it('is not a theme before anything was picked: no id saved, or the default saved', () => { - expect(chosenTheme(false, undefined, undefined)).toBe(false); - expect(chosenTheme(false, defaultThemeId, undefined)).toBe(false); - expect(chosenTheme(false, defaultThemeId, false)).toBe(false); +const read = () => { + let out = ''; + const Probe = () => { + out = `${useActiveTheme().id}|${JSON.stringify(useSceneInk() ?? null)}`; + return null; + }; + renderToString(createElement(Probe)); + return out; +}; + +describe('the drawn sky decides the theme and ink; the stored theme stands where none is drawn', () => { + beforeEach(() => { + setSceneDrawn(false); }); - it('is a pick of Midnight Sky made in the theme menu, which sets the flag', () => { - expect(chosenTheme(false, defaultThemeId, true)).toBe(true); + it('a scene running over a stored theme wears the sky theme and ink', () => { + setSceneDrawn(true, 'night'); + expect(read()).toBe('midnight-sky|{"state":"night","phone":false}'); }); - it('is a saved id other than the default, with or without the flag', () => { - expect(chosenTheme(false, 'dark-theme', undefined)).toBe(true); - expect(chosenTheme(false, 'noonday-sky', true)).toBe(true); + it('follows the sky of the scene that is up, whatever the clock or the choice announce, and moves when a scene replaces it', () => { + setSceneDrawn(true, 'dusk'); // the choice says night (mocked above); the scene up draws dusk + expect(read()).toBe('noonday-sky|{"state":"dusk","phone":false}'); + setSceneDrawn(true, 'night'); // a rebuilt scene replaced it + expect(read()).toBe('midnight-sky|{"state":"night","phone":false}'); }); - it('is the system scheme', () => { - expect(chosenTheme(true, defaultThemeId, undefined)).toBe(true); + it('a scene that is not drawing (failed, or context lost) leaves the stored theme and its own ink', () => { + expect(read()).toBe('dark-theme|null'); }); - it('the theme menu sets the flag together with the id', () => { - const tsx = readFileSync( - `${process.cwd()}/src/app/features/settings/general/General.tsx`, - 'utf8' - ); - expect(tsx).toMatch(/setThemeId\(theme\.id\);\s*setThemeChosen\(true\);/); + it('a restored context wears the sky again', () => { + setSceneDrawn(true, 'night'); + setSceneDrawn(false); + expect(read()).toBe('dark-theme|null'); + setSceneDrawn(true, 'night'); + expect(read()).toBe('midnight-sky|{"state":"night","phone":false}'); }); }); diff --git a/src/app/hooks/useTheme.ts b/src/app/hooks/useTheme.ts index 730b12d4..a66d88d8 100644 --- a/src/app/hooks/useTheme.ts +++ b/src/app/hooks/useTheme.ts @@ -10,11 +10,11 @@ import { } from '../../colors.css'; import '../../gamecult.css'; import '../../sky.css'; -import { defaultThemeId, settingsAtom } from '../state/settings'; +import { settingsAtom } from '../state/settings'; import { useSetting } from '../state/hooks/settings'; import { sceneThemeId } from '../features/scene/skyTheme'; import { sceneInk, type SkyInk } from '../features/scene/skyInk'; -import { useResolvedSkyState, useSceneOn, useSkyState } from './useSkyState'; +import { useDrawnSky, useSceneOn } from './useSkyState'; import { ScreenSize, useScreenSizeContext } from './useScreenSize'; export enum ThemeKind { @@ -107,33 +107,18 @@ export const useSystemThemeKind = (): ThemeKind => { const toTheme = (id: ReturnType): Theme | undefined => id === NoondaySkyTheme.id ? NoondaySkyTheme : id && MidnightSkyTheme; -/** - * A theme the person chose: the system scheme, any pick made in the theme menu (`themeChosen`, which also covers - * Midnight Sky, the default), or a saved id other than the default (picks from before the flag existed). - */ -export const chosenTheme = (useSystemTheme: boolean, themeId?: string, themeChosen?: boolean) => - useSystemTheme || themeChosen === true || (themeId !== undefined && themeId !== defaultThemeId); - -/** The theme the sky asks for on a page with no theme of its own (signed out), or undefined for none. */ +/** The theme the drawn sky asks for while a scene is on, or undefined for none (signed-out pages then wear Midnight Sky). */ export const useSkyTheme = (): Theme | undefined => - toTheme(sceneThemeId(useSkyState(), useResolvedSkyState(), useSceneOn(), false)); + toTheme(sceneThemeId(useDrawnSky(), useSceneOn())); -/** The sky theme the signed-in page wears, or undefined when the person's own theme wins. */ -const useSceneSkyThemeId = (): ReturnType => { - const sky = useSkyState(); - const resolved = useResolvedSkyState(); - const sceneOn = useSceneOn(); - const [systemTheme] = useSetting(settingsAtom, 'useSystemTheme'); - const [themeId] = useSetting(settingsAtom, 'themeId'); - const [themeChosen] = useSetting(settingsAtom, 'themeChosen'); - // A person's own theme wins over the sky, fixed or 'auto'. - return sceneThemeId(sky, resolved, sceneOn, chosenTheme(systemTheme, themeId, themeChosen)); -}; +/** The sky theme the page wears while a scene is on, or undefined when the person's own theme stands. */ +const useSceneSkyThemeId = (): ReturnType => + sceneThemeId(useDrawnSky(), useSceneOn()); /** The ink the page wears over the scene (`sceneInk`, skyInk.ts), or undefined when the theme's own ink stands. */ export const useSceneInk = (): SkyInk | undefined => { const themeId = useSceneSkyThemeId(); - const state = useResolvedSkyState(); + const state = useDrawnSky(); const sceneOn = useSceneOn(); const phone = useScreenSizeContext() === ScreenSize.Mobile; return useMemo(() => sceneInk(themeId, sceneOn, state, phone), [themeId, sceneOn, state, phone]); diff --git a/src/app/pages/auth/AuthLayout.tsx b/src/app/pages/auth/AuthLayout.tsx index a2d652a3..1e812592 100644 --- a/src/app/pages/auth/AuthLayout.tsx +++ b/src/app/pages/auth/AuthLayout.tsx @@ -22,7 +22,7 @@ import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback'; import { LOGIN_PATH, REGISTER_PATH, RESET_PASSWORD_PATH } from '../paths'; import RatatoskrSVG from '../../../../public/res/svg/ratatoskr.svg'; import { LogoMark } from '../../components/logo/logoMark.css'; -import { SkyStateControl } from '../../features/scene/SkyStateControl'; +import { SceneViewEntry } from '../../features/scene/SceneViewEntry'; import { ServerPicker } from './ServerPicker'; import { AutoDiscoveryAction, autoDiscovery } from '../../cs-api'; import { SpecVersionsLoader } from '../../components/SpecVersionsLoader'; @@ -144,7 +144,7 @@ export function AuthLayout() { /> Ratatoskr - + diff --git a/src/app/pages/auth/styles.css.ts b/src/app/pages/auth/styles.css.ts index f8a7a95b..96994a09 100644 --- a/src/app/pages/auth/styles.css.ts +++ b/src/app/pages/auth/styles.css.ts @@ -117,7 +117,7 @@ globalStyle(`${scene} ${AuthCardContent}`, { gap: config.space.S500, }); -// The footer line sits on the terrain, which is dark at its foot in every sky (luminance 0.02 at dusk), where the +// The footer line sits on the scene's ground, which is dark at its foot in every sky (luminance 0.02 at dusk), where the // sky's dark ink is unreadable. Over the scene it gets a blurred band tinted with the plate's fill and the plate's // ink, faded out at its edges so it reads as haze and not as a bar: the scene shows through and round it. A browser // without color-mix gets the plate's opaque fill, as the chat bubbles do (message/layout/layout.css.ts). The tint diff --git a/src/app/phoneTapTargets.test.ts b/src/app/phoneTapTargets.test.ts index 192f8414..bbcde9e6 100644 --- a/src/app/phoneTapTargets.test.ts +++ b/src/app/phoneTapTargets.test.ts @@ -200,7 +200,9 @@ describe('icon buttons in the room view', () => { // Buttons that were fixed with #125 and had no test. 'components/password-input/PasswordInput.tsx': ['PhoneHit'], 'features/desk/Desk.tsx': ['PhoneHit'], - 'features/scene/SkyStateControl.tsx': ['PhoneHit'], + 'features/scene/SceneViewEntry.tsx': ['PhoneHit'], // the scene view's entry + 'features/scene/SceneViewHost.tsx': ['PhoneHit'], // Return while the scene view loads + 'features/scene/view/SceneView.tsx': ['PhoneHit'], // one rail button, five icons 'pages/auth/login/PasswordLoginForm.tsx': ['PhoneHit'], }; diff --git a/src/app/state/settings.test.ts b/src/app/state/settings.test.ts new file mode 100644 index 00000000..82e164cd --- /dev/null +++ b/src/app/state/settings.test.ts @@ -0,0 +1,14 @@ +import { describe, expect, it, vi } from 'vitest'; + +const stored = JSON.stringify({ themeId: 'dark-theme', themeChosen: true }); +vi.stubGlobal('localStorage', { getItem: () => stored, setItem: () => undefined }); + +describe('settings load', () => { + it('tolerates a themeChosen key stored by an older build: the rest loads, the key is inert', async () => { + const { getSettings, defaultThemeId } = await import('./settings'); + const s = getSettings() as unknown as Record; + expect(s.themeId).toBe('dark-theme'); + expect(s.useSystemTheme).toBe(false); + expect(defaultThemeId).toBeDefined(); + }); +}); diff --git a/src/app/state/settings.ts b/src/app/state/settings.ts index 21c449af..b5165929 100644 --- a/src/app/state/settings.ts +++ b/src/app/state/settings.ts @@ -18,8 +18,6 @@ export enum MessageLayout { export interface Settings { themeId?: string; - /** Set when a theme is picked in the menu, so a picked default (Midnight Sky) reads as chosen. Absent until then. */ - themeChosen?: boolean; useSystemTheme: boolean; lightThemeId?: string; darkThemeId?: string; diff --git a/src/sky/moon.js b/src/sky/moon.js new file mode 100644 index 00000000..70b37736 --- /dev/null +++ b/src/sky/moon.js @@ -0,0 +1,88 @@ +// The moon for a place and a moment. Dependency-free ES module beside sun.js, whose sidereal transform it shares. +// +// moonEquatorial(time) -> { ra, dec, distanceKm, lambda, beta } radians, of date +// moonPhase(time) -> { elongationDeg, phaseAngleDeg, illuminated, waxing } +// moonPosition(time, lat, lon) -> { elevation, azimuth } degrees, topocentric, no refraction +// +// Position is the low-precision series of the Astronomical Almanac (section D, "Low precision formulae for the Moon", T in Julian +// centuries from J2000.0): about 0.3 degrees in longitude and 0.2 in latitude, a few hundred km in distance, for 1950..2050. +// Phase is the elongation from the sun (sun.js) and the phase angle of Meeus, "Astronomical Algorithms", 2nd ed., eq. 48.3. + +import { daysSinceJ2000, equatorialToHorizontal, sunEquatorial } from './sun.js'; + +const RAD = Math.PI / 180; +const EARTH_RADIUS_KM = 6378.14; +const AU_KM = 149597870.7; + +const sinD = (deg) => Math.sin(deg * RAD); +const cosD = (deg) => Math.cos(deg * RAD); + +/** The moon's ecliptic longitude and latitude (radians), horizontal parallax (radians) and distance (km), of date. */ +function moonEcliptic(time) { + const T = daysSinceJ2000(time) / 36525; + const lambda = + 218.32 + + 481267.881 * T + + 6.29 * sinD(135.0 + 477198.87 * T) - + 1.27 * sinD(259.3 - 413335.36 * T) + + 0.66 * sinD(235.7 + 890534.22 * T) + + 0.21 * sinD(269.9 + 954397.74 * T) - + 0.19 * sinD(357.5 + 35999.05 * T) - + 0.11 * sinD(186.5 + 966404.03 * T); + const beta = + 5.13 * sinD(93.3 + 483202.02 * T) + + 0.28 * sinD(228.2 + 960400.89 * T) - + 0.28 * sinD(318.3 + 6003.15 * T) - + 0.17 * sinD(217.6 - 407332.21 * T); + const parallax = + 0.9508 + + 0.0518 * cosD(135.0 + 477198.87 * T) + + 0.0095 * cosD(259.3 - 413335.36 * T) + + 0.0078 * cosD(235.7 + 890534.22 * T) + + 0.0028 * cosD(269.9 + 954397.74 * T); + return { + lambda: lambda * RAD, + beta: beta * RAD, + parallax: parallax * RAD, + distanceKm: EARTH_RADIUS_KM / Math.sin(parallax * RAD), + }; +} + +/** Right ascension, declination (radians, of date), distance (km) and ecliptic coordinates (radians) of the moon at a UTC moment. */ +export function moonEquatorial(time) { + const { lambda, beta, distanceKm } = moonEcliptic(time); + const l = Math.cos(beta) * Math.cos(lambda); + const m = 0.9175 * Math.cos(beta) * Math.sin(lambda) - 0.3978 * Math.sin(beta); + const n = 0.3978 * Math.cos(beta) * Math.sin(lambda) + 0.9175 * Math.sin(beta); + return { ra: Math.atan2(m, l), dec: Math.asin(n), distanceKm, lambda, beta }; +} + +/** + * The phase at a UTC moment. `elongationDeg` is the geocentric angle sun-earth-moon side: 0 new, 90 first quarter, 180 full, 270 last quarter + * (by the longitude difference, so it runs the whole circle). `phaseAngleDeg` is the angle sun-moon-earth: 0 full, 180 new. `illuminated` is + * the lit fraction of the disc, (1 + cos i) / 2. + */ +export function moonPhase(time) { + const moon = moonEquatorial(time); + const sun = sunEquatorial(time); + const sunDistanceKm = AU_KM; + const cosPsi = Math.cos(moon.beta) * Math.cos(moon.lambda - sun.lambda); + const psi = Math.acos(Math.min(1, Math.max(-1, cosPsi))); + const i = Math.atan2(sunDistanceKm * Math.sin(psi), moon.distanceKm - sunDistanceKm * Math.cos(psi)); + const elongationDeg = ((((moon.lambda - sun.lambda) / RAD) % 360) + 360) % 360; + return { + elongationDeg, + phaseAngleDeg: i / RAD, + illuminated: (1 + Math.cos(i)) / 2, + waxing: elongationDeg < 180, + distanceKm: moon.distanceKm, + }; +} + +/** Elevation and azimuth of the moon in degrees at a UTC moment and place, topocentric (the parallax lowers it up to a degree), no refraction. Azimuth clockwise from north. */ +export function moonPosition(time, lat, lon) { + const m = moonEquatorial(time); + const { elevation, azimuth } = equatorialToHorizontal(m.ra, m.dec, time, lat, lon); + const parallaxDeg = Math.asin(EARTH_RADIUS_KM / m.distanceKm) / RAD; + return { elevation: elevation - parallaxDeg * cosD(elevation), azimuth }; +} diff --git a/src/sky/moon.test.ts b/src/sky/moon.test.ts new file mode 100644 index 00000000..f4607541 --- /dev/null +++ b/src/sky/moon.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from 'vitest'; +import { moonEquatorial, moonPhase, moonPosition } from './moon.js'; +import { sunPosition } from './sun.js'; + +const DEG = 180 / Math.PI; + +describe('moon position', () => { + it('matches Meeus, Astronomical Algorithms ex. 47.a (1992 April 12, 0h TD) within the series\' 0.3 degrees', () => { + // Meeus: ra 134.688470, dec +13.768368, distance 368409.7 km (full series). + const m = moonEquatorial(Date.UTC(1992, 3, 12, 0, 0, 0)); + expect(Math.abs(m.ra * DEG - 134.68847)).toBeLessThan(0.3); + expect(Math.abs(m.dec * DEG - 13.768368)).toBeLessThan(0.3); + expect(Math.abs(m.distanceKm - 368409.7)).toBeLessThan(1500); + }); + + it('is opposite the sun at full moon, with the parallax of a few tenths of a degree at most', () => { + // Total lunar eclipse of 2026-03-03, greatest eclipse 11:33 UTC: the moon sits opposite the sun. + const t = '2026-03-03T11:33:00Z'; + const moon = moonPosition(t, 48.19, 16.35); + const sun = sunPosition(t, 48.19, 16.35); + expect(Math.abs(moon.elevation + sun.elevation)).toBeLessThan(1.5); + const dAz = Math.abs(((moon.azimuth - sun.azimuth + 360) % 360) - 180); + expect(dAz).toBeLessThan(2); + }); +}); + +describe('moon phase', () => { + // US Naval Observatory phases of January 2000 and the lunar eclipse of March 2026 (UTC); the series is good to ~0.5 degree of + // elongation, which is an hour of the moon's 12.2 degrees a day relative to the sun, so these hold to a degree and a half. + const phases: [string, number][] = [ + ['2000-01-06T18:14:00Z', 0], + ['2000-01-14T13:34:00Z', 90], + ['2000-01-21T04:40:00Z', 180], + ['2000-01-28T07:57:00Z', 270], + ['2026-03-03T11:38:00Z', 180], + ]; + it.each(phases)('elongation at %s is %d degrees', (t, e) => { + const d = ((moonPhase(t).elongationDeg - e + 540) % 360) - 180; + expect(Math.abs(d)).toBeLessThan(1.5); + }); + + it('lit fraction: dark at new, half at the quarters, full at full; waxing between new and full', () => { + expect(moonPhase('2000-01-06T18:14:00Z').illuminated).toBeLessThan(0.01); + expect(moonPhase('2000-01-14T13:34:00Z').illuminated).toBeCloseTo(0.5, 1); + expect(moonPhase('2000-01-21T04:40:00Z').illuminated).toBeGreaterThan(0.99); + expect(moonPhase('2000-01-10T00:00:00Z').waxing).toBe(true); + expect(moonPhase('2000-01-25T00:00:00Z').waxing).toBe(false); + expect(moonPhase('2000-01-21T04:40:00Z').phaseAngleDeg).toBeLessThan(2); + }); +}); diff --git a/src/sky/skyTokens.js b/src/sky/skyTokens.js index 5152a4fb..13911a47 100644 --- a/src/sky/skyTokens.js +++ b/src/sky/skyTokens.js @@ -19,8 +19,8 @@ const luma = (c) => 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]; export const GRADIENT_STOPS = 7; export const AA = 4.5; // WCAG 2.x AA, normal text -// The lightest the Night sky draws behind the page (src/app/features/scene/skyState.ts, `skyBackdrop('night')`; a test in -// skyTheme.test.ts fails if the two drift). Midnight Sky's link also sits on bare sky, so it must clear AA against this. +// The Night sky's luminance the Midnight Sky link was fitted against (a derivation input, not a bound the scene is held to: +// the look is tuned by eye). The link is brightened in its own hue until it clears AA against this. export const NIGHT_SKY_LIGHTEST = 0.081642; // Where and when the theme is lit. Equinox, 45N on the prime meridian: noon sun at 45 degrees. diff --git a/src/sky/sun.js b/src/sky/sun.js index 3173eb4d..8936daa8 100644 --- a/src/sky/sun.js +++ b/src/sky/sun.js @@ -29,17 +29,32 @@ const mix = (a, b, t) => a + (b - a) * t; const toMs = (time) => (time instanceof Date ? time.getTime() : typeof time === 'string' ? Date.parse(time) : Number(time)); -/** Sun elevation and azimuth in degrees at a UTC moment and place. Azimuth runs clockwise from north. */ -export function sunPosition(time, lat, lon) { - const d = toMs(time) / 86400000 - 10957.5; // days since J2000.0 (2000-01-01 12:00 UTC) +/** Days since J2000.0 (2000-01-01 12:00 UTC) at a UTC moment. */ +export const daysSinceJ2000 = (time) => toMs(time) / 86400000 - 10957.5; + +/** Greenwich mean sidereal time in radians (unreduced) at `d` days since J2000.0. */ +export const gmstRad = (d) => (280.46061837 + 360.98564736629 * d) * RAD; + +/** The sun's right ascension and declination of date, in radians, and its ecliptic longitude `lambda`, at a UTC moment. */ +export function sunEquatorial(time) { + const d = daysSinceJ2000(time); const L = (280.46 + 0.9856474 * d) * RAD; // mean longitude const g = (357.528 + 0.9856003 * d) * RAD; // mean anomaly const lambda = L + (1.915 * Math.sin(g) + 0.02 * Math.sin(2 * g)) * RAD; // ecliptic longitude const eps = (23.439 - 0.0000004 * d) * RAD; // obliquity - const dec = Math.asin(Math.sin(eps) * Math.sin(lambda)); - const ra = Math.atan2(Math.cos(eps) * Math.sin(lambda), Math.cos(lambda)); - const gmst = (280.46061837 + 360.98564736629 * d) * RAD; - const hourAngle = gmst + lon * RAD - ra; + return { + dec: Math.asin(Math.sin(eps) * Math.sin(lambda)), + ra: Math.atan2(Math.cos(eps) * Math.sin(lambda), Math.cos(lambda)), + lambda, + }; +} + +/** + * Elevation and azimuth in degrees of a point of the sky at a UTC moment and place, from its right ascension and declination of date + * (radians): the one sidereal transform of the sun, the moon and the stars. Azimuth runs clockwise from north; no refraction. + */ +export function equatorialToHorizontal(ra, dec, time, lat, lon) { + const hourAngle = gmstRad(daysSinceJ2000(time)) + lon * RAD - ra; const phi = lat * RAD; const sinEl = Math.sin(phi) * Math.sin(dec) + Math.cos(phi) * Math.cos(dec) * Math.cos(hourAngle); // Hour angle is westward-positive, so atan2 gives azimuth from south, westward; +180 turns it into @@ -51,6 +66,12 @@ export function sunPosition(time, lat, lon) { }; } +/** Sun elevation and azimuth in degrees at a UTC moment and place. Azimuth runs clockwise from north. */ +export function sunPosition(time, lat, lon) { + const { ra, dec } = sunEquatorial(time); + return equatorialToHorizontal(ra, dec, time, lat, lon); +} + /** Sun elevation in degrees at a UTC moment and place. */ export const sunElevation = (time, lat, lon) => sunPosition(time, lat, lon).elevation; diff --git a/vite.config.js b/vite.config.js index 699c3148..f2d3e06c 100644 --- a/vite.config.js +++ b/vite.config.js @@ -51,6 +51,10 @@ const copyFiles = { src: 'public/dings', dest: 'public/', }, + { + src: 'public/ridge', + dest: 'public/', + }, ], };