diff --git a/public/ridge/index.json b/public/ridge/index.json index 98da9f42..8c3323ed 100644 --- a/public/ridge/index.json +++ b/public/ridge/index.json @@ -2,6 +2,6 @@ "schema": 1, "default": "vienna", "places": { - "vienna": "vienna-12e733dc9f09" + "vienna": "vienna-6815bb9dca99" } } diff --git a/public/ridge/vienna-12e733dc9f09/dawn-far.webp b/public/ridge/vienna-12e733dc9f09/dawn-far.webp deleted file mode 100644 index d14ba54d..00000000 Binary files a/public/ridge/vienna-12e733dc9f09/dawn-far.webp and /dev/null differ diff --git a/public/ridge/vienna-12e733dc9f09/dawn-mid.webp b/public/ridge/vienna-12e733dc9f09/dawn-mid.webp deleted file mode 100644 index f3381c72..00000000 Binary files a/public/ridge/vienna-12e733dc9f09/dawn-mid.webp and /dev/null differ diff --git a/public/ridge/vienna-12e733dc9f09/dawn-near.webp b/public/ridge/vienna-12e733dc9f09/dawn-near.webp deleted file mode 100644 index d68b754f..00000000 Binary files a/public/ridge/vienna-12e733dc9f09/dawn-near.webp and /dev/null differ diff --git a/public/ridge/vienna-12e733dc9f09/dusk-far.webp b/public/ridge/vienna-12e733dc9f09/dusk-far.webp deleted file mode 100644 index 98ba0759..00000000 Binary files a/public/ridge/vienna-12e733dc9f09/dusk-far.webp and /dev/null differ diff --git a/public/ridge/vienna-12e733dc9f09/dusk-mid.webp b/public/ridge/vienna-12e733dc9f09/dusk-mid.webp deleted file mode 100644 index e640f463..00000000 Binary files a/public/ridge/vienna-12e733dc9f09/dusk-mid.webp and /dev/null differ diff --git a/public/ridge/vienna-12e733dc9f09/dusk-near.webp b/public/ridge/vienna-12e733dc9f09/dusk-near.webp deleted file mode 100644 index 3a33ce93..00000000 Binary files a/public/ridge/vienna-12e733dc9f09/dusk-near.webp and /dev/null differ diff --git a/public/ridge/vienna-12e733dc9f09/golden-far.webp b/public/ridge/vienna-12e733dc9f09/golden-far.webp deleted file mode 100644 index 59383d37..00000000 Binary files a/public/ridge/vienna-12e733dc9f09/golden-far.webp and /dev/null differ diff --git a/public/ridge/vienna-12e733dc9f09/golden-mid.webp b/public/ridge/vienna-12e733dc9f09/golden-mid.webp deleted file mode 100644 index 1705fe1e..00000000 Binary files a/public/ridge/vienna-12e733dc9f09/golden-mid.webp and /dev/null differ diff --git a/public/ridge/vienna-12e733dc9f09/golden-near.webp b/public/ridge/vienna-12e733dc9f09/golden-near.webp deleted file mode 100644 index 7b05f5b5..00000000 Binary files a/public/ridge/vienna-12e733dc9f09/golden-near.webp and /dev/null differ diff --git a/public/ridge/vienna-12e733dc9f09/manifest.json b/public/ridge/vienna-12e733dc9f09/manifest.json deleted file mode 100644 index 9d0f24d3..00000000 --- a/public/ridge/vienna-12e733dc9f09/manifest.json +++ /dev/null @@ -1,232 +0,0 @@ -{ - "schema": 1, - "baker_version": 1, - "bake_id": "12e733dc9f09", - "place": { - "id": "vienna", - "name": "Vienna, looking SW to Rax/Schneeberg", - "lat": 48.1929826, - "lon": 16.3534237, - "altitude_km": 0.18330000000000002, - "tz_h": 2, - "tz_name": "CEST", - "date": "2026-09-23" - }, - "view": { - "look_az_deg": 214.0, - "plane_h": 600, - "px_per_deg_h": 17.77777777777778, - "px_per_deg_v": 177.77777777777777, - "horizon_row": 314.5166414048937, - "sky_row": 24.0, - "near_row": 396.0, - "window_deg": 72, - "plane_w": 1280 - }, - "frames": [ - { - "key": "dawn", - "sun": { - "az": 91.31344091054159, - "el": 1.9676060128650812 - }, - "hour_utc": 4.923611110972221, - "planes": { - "far": { - "file": "dawn-far.webp", - "bytes": 76030, - "w": 1280, - "h": 600 - }, - "mid": { - "file": "dawn-mid.webp", - "bytes": 53926, - "w": 1280, - "h": 600 - }, - "near": { - "file": "dawn-near.webp", - "bytes": 113422, - "w": 1280, - "h": 600 - } - }, - "bytes": 243378, - "luma": { - "min": 0.02173927318967578, - "max": 0.2161143719823614 - } - }, - { - "key": "morning", - "sun": { - "az": 122.50757257559601, - "el": 26.09311435610136 - }, - "hour_utc": 7.5, - "planes": { - "far": { - "file": "morning-far.webp", - "bytes": 77330, - "w": 1280, - "h": 600 - }, - "mid": { - "file": "morning-mid.webp", - "bytes": 58076, - "w": 1280, - "h": 600 - }, - "near": { - "file": "morning-near.webp", - "bytes": 120478, - "w": 1280, - "h": 600 - } - }, - "bytes": 255884, - "luma": { - "min": 0.023307705502610833, - "max": 0.5966843818121018 - } - }, - { - "key": "noon", - "sun": { - "az": 179.90578338676787, - "el": 42.09425207059211 - }, - "hour_utc": 10.778105086666667, - "planes": { - "far": { - "file": "noon-far.webp", - "bytes": 78634, - "w": 1280, - "h": 600 - }, - "mid": { - "file": "noon-mid.webp", - "bytes": 58684, - "w": 1280, - "h": 600 - }, - "near": { - "file": "noon-near.webp", - "bytes": 123036, - "w": 1280, - "h": 600 - } - }, - "bytes": 260354, - "luma": { - "min": 0.028024916825206435, - "max": 0.7110067687110413 - } - }, - { - "key": "golden", - "sun": { - "az": 263.5260325423649, - "el": 6.139314360766868 - }, - "hour_utc": 16.193611110972224, - "planes": { - "far": { - "file": "golden-far.webp", - "bytes": 76038, - "w": 1280, - "h": 600 - }, - "mid": { - "file": "golden-mid.webp", - "bytes": 54686, - "w": 1280, - "h": 600 - }, - "near": { - "file": "golden-near.webp", - "bytes": 114944, - "w": 1280, - "h": 600 - } - }, - "bytes": 245668, - "luma": { - "min": 0.02139437660612246, - "max": 0.2869579287555448 - } - }, - { - "key": "dusk", - "sun": { - "az": 273.0513939324655, - "el": -1.8289117519819837 - }, - "hour_utc": 17.04388888875, - "planes": { - "far": { - "file": "dusk-far.webp", - "bytes": 75552, - "w": 1280, - "h": 600 - }, - "mid": { - "file": "dusk-mid.webp", - "bytes": 52176, - "w": 1280, - "h": 600 - }, - "near": { - "file": "dusk-near.webp", - "bytes": 112176, - "w": 1280, - "h": 600 - } - }, - "bytes": 239904, - "luma": { - "min": 0.018028911802351475, - "max": 0.18804654725014905 - } - }, - { - "key": "night", - "sun": { - "az": 283.9869292652113, - "el": -11.998720821772542 - }, - "hour_utc": 18.004444444305555, - "planes": { - "far": { - "file": "night-far.webp", - "bytes": 74732, - "w": 1280, - "h": 600 - }, - "mid": { - "file": "night-mid.webp", - "bytes": 50192, - "w": 1280, - "h": 600 - }, - "near": { - "file": "night-near.webp", - "bytes": 110780, - "w": 1280, - "h": 600 - } - }, - "bytes": 235704, - "luma": { - "min": 0.012974147057371975, - "max": 0.14255636176898956 - } - } - ], - "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-12e733dc9f09/morning-far.webp b/public/ridge/vienna-12e733dc9f09/morning-far.webp deleted file mode 100644 index 2b6720f6..00000000 Binary files a/public/ridge/vienna-12e733dc9f09/morning-far.webp and /dev/null differ diff --git a/public/ridge/vienna-12e733dc9f09/morning-mid.webp b/public/ridge/vienna-12e733dc9f09/morning-mid.webp deleted file mode 100644 index ed167038..00000000 Binary files a/public/ridge/vienna-12e733dc9f09/morning-mid.webp and /dev/null differ diff --git a/public/ridge/vienna-12e733dc9f09/morning-near.webp b/public/ridge/vienna-12e733dc9f09/morning-near.webp deleted file mode 100644 index 2cb823b1..00000000 Binary files a/public/ridge/vienna-12e733dc9f09/morning-near.webp and /dev/null differ diff --git a/public/ridge/vienna-12e733dc9f09/night-far.webp b/public/ridge/vienna-12e733dc9f09/night-far.webp deleted file mode 100644 index 2e5db61a..00000000 Binary files a/public/ridge/vienna-12e733dc9f09/night-far.webp and /dev/null differ diff --git a/public/ridge/vienna-12e733dc9f09/night-mid.webp b/public/ridge/vienna-12e733dc9f09/night-mid.webp deleted file mode 100644 index 54fb1dbd..00000000 Binary files a/public/ridge/vienna-12e733dc9f09/night-mid.webp and /dev/null differ diff --git a/public/ridge/vienna-12e733dc9f09/night-near.webp b/public/ridge/vienna-12e733dc9f09/night-near.webp deleted file mode 100644 index 3850ec34..00000000 Binary files a/public/ridge/vienna-12e733dc9f09/night-near.webp and /dev/null differ diff --git a/public/ridge/vienna-12e733dc9f09/noon-far.webp b/public/ridge/vienna-12e733dc9f09/noon-far.webp deleted file mode 100644 index c9a0ac23..00000000 Binary files a/public/ridge/vienna-12e733dc9f09/noon-far.webp and /dev/null differ diff --git a/public/ridge/vienna-12e733dc9f09/noon-mid.webp b/public/ridge/vienna-12e733dc9f09/noon-mid.webp deleted file mode 100644 index 0ddc8a45..00000000 Binary files a/public/ridge/vienna-12e733dc9f09/noon-mid.webp and /dev/null differ diff --git a/public/ridge/vienna-12e733dc9f09/noon-near.webp b/public/ridge/vienna-12e733dc9f09/noon-near.webp deleted file mode 100644 index 03b7c041..00000000 Binary files a/public/ridge/vienna-12e733dc9f09/noon-near.webp and /dev/null differ diff --git a/public/ridge/vienna-6815bb9dca99/card-0-colour.webp b/public/ridge/vienna-6815bb9dca99/card-0-colour.webp new file mode 100644 index 00000000..133c6cd8 Binary files /dev/null and b/public/ridge/vienna-6815bb9dca99/card-0-colour.webp differ diff --git a/public/ridge/vienna-6815bb9dca99/card-0-geometry.webp b/public/ridge/vienna-6815bb9dca99/card-0-geometry.webp new file mode 100644 index 00000000..4e0c79f6 Binary files /dev/null and b/public/ridge/vienna-6815bb9dca99/card-0-geometry.webp differ diff --git a/public/ridge/vienna-6815bb9dca99/card-1-colour.webp b/public/ridge/vienna-6815bb9dca99/card-1-colour.webp new file mode 100644 index 00000000..21ea85ab Binary files /dev/null and b/public/ridge/vienna-6815bb9dca99/card-1-colour.webp differ diff --git a/public/ridge/vienna-6815bb9dca99/card-1-geometry.webp b/public/ridge/vienna-6815bb9dca99/card-1-geometry.webp new file mode 100644 index 00000000..06c99e06 Binary files /dev/null and b/public/ridge/vienna-6815bb9dca99/card-1-geometry.webp differ diff --git a/public/ridge/vienna-6815bb9dca99/card-2-colour.webp b/public/ridge/vienna-6815bb9dca99/card-2-colour.webp new file mode 100644 index 00000000..66d048e7 Binary files /dev/null and b/public/ridge/vienna-6815bb9dca99/card-2-colour.webp differ diff --git a/public/ridge/vienna-6815bb9dca99/card-2-geometry.webp b/public/ridge/vienna-6815bb9dca99/card-2-geometry.webp new file mode 100644 index 00000000..631e894b Binary files /dev/null and b/public/ridge/vienna-6815bb9dca99/card-2-geometry.webp differ diff --git a/public/ridge/vienna-6815bb9dca99/manifest.json b/public/ridge/vienna-6815bb9dca99/manifest.json new file mode 100644 index 00000000..935e5abd --- /dev/null +++ b/public/ridge/vienna-6815bb9dca99/manifest.json @@ -0,0 +1,100 @@ +{ + "schema": 2, + "baker_version": 2, + "bake_id": "6815bb9dca99", + "place": { + "id": "vienna", + "name": "Vienna, looking SW to Rax/Schneeberg", + "lat": 48.1929826, + "lon": 16.3534237, + "altitude_km": 0.18330000000000002, + "eye_m": 213.3 + }, + "view": { + "look_az_deg": 214.0, + "plane_h": 600, + "px_per_deg_h": 17.77777777777778, + "px_per_deg_v": 177.77777777777777, + "exaggeration": 10.0, + "horizon_row": 294.58455032829386, + "sky_row": 24.0, + "near_row": 396.0, + "window_deg": 72, + "plane_w": 1280 + }, + "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_m": 200.0, + "heading_max_deg": 23.0 + }, + "cards": [ + { + "top": 182, + "h": 418, + "near_m": null, + "far_m": 5392.093596252347, + "median_m": 1478.456787109375, + "distance_m": 1478.456787109375, + "scale": 1.1564386078720779, + "colour": { + "file": "card-0-colour.webp", + "bytes": 4598 + }, + "geometry": { + "file": "card-0-geometry.webp", + "bytes": 95716 + } + }, + { + "top": 24, + "h": 576, + "near_m": 5392.093596252347, + "far_m": 39877.08347165139, + "median_m": 11107.0283203125, + "distance_m": 11107.0283203125, + "scale": 1.0183368002838622, + "colour": { + "file": "card-1-colour.webp", + "bytes": 8396 + }, + "geometry": { + "file": "card-1-geometry.webp", + "bytes": 130870 + } + }, + { + "top": 40, + "h": 560, + "near_m": 39877.08347165139, + "far_m": null, + "median_m": 48378.26953125, + "distance_m": 48378.26953125, + "scale": 1.0041512491408657, + "colour": { + "file": "card-2-colour.webp", + "bytes": 9718 + }, + "geometry": { + "file": "card-2-geometry.webp", + "bytes": 118378 + } + } + ], + "w": 1280, + "h": 600, + "bytes": 367676, + "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/ridge-bake/README.md b/scripts/ridge-bake/README.md index c3c8f4e5..d74f4871 100644 --- a/scripts/ridge-bake/README.md +++ b/scripts/ridge-bake/README.md @@ -33,10 +33,11 @@ Files are `Copernicus_DSM_COG_10_dd_00_ddd_00_DEM.tif`; the list below 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 in the window sits at 4% of the frame height, the lowest at 66%, clamped to 1x to 10x vertical exaggeration. 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. -5. **Cards.** `cards` 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 alpha-over composite of the cards equals the opaque view; `check_cover` refuses a bake that differs by more than 0.02. -6. **Normals.** `normals` takes the along-ray slope and the across-ray slope at equal distance (neighbouring columns, same sample), both times the vertical exaggeration. +5. **Cards.** `cards` 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 has none: its rows there are the ground). The alpha-over composite of the cards equals the opaque view; `check_cover` refuses a bake that differs by more than 0.02. +6. **Camera.** `CAMERA_R_M` (+200 m, signed: + forward, - backward; `camera_r_m` in `places.json` per place) and `HEADING_MAX_DEG` (23) are the camera on a circle round the bake centre (ruling `ridge-camera-on-circle`). `pack` gives each card `distance_m` (the median distance of its solid pixels that are not wall; `median_m` is the same number) and `scale = distance_m / (distance_m - r)`, the card's pan rate per unit of heading and its static size. It refuses `|r|` at or above half the nearest card's distance, a card with no solid terrain apart from its wall, and (in `write_bake`) a camera that lifts the nearest card off the frame bottom (every backward `r`: the bake is not wider and taller yet) or shrinks a card below what a 16:9 viewport needs at rest. +7. **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`: `card--colour.webp` (lossy RGB albedo, lossless straight alpha) and `card--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`). The manifest lists the cards nearest first with their row band (`top`, `h`), median seam depths and files; the runtime paints the list last to first. `check_budget` refuses more than `MAX_CARDS` cards, more than 1.5 MB of card files, or more than 20 MB decoded (2 textures x width x band rows x 4 bytes per card); a cap is never raised to fit a bake. +Files per card `i`: `card--colour.webp` (lossy RGB albedo, lossless straight alpha) and `card--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). The manifest lists the cards nearest first with their row band (`top`, `h`), median seam depths, `distance_m`, `scale` and files, and the `camera` {`r_m`, `heading_max_deg`}; the runtime paints the list last to first. `check_budget` refuses more than `MAX_CARDS` cards, more than 1.5 MB of card files, or more than 20 MB decoded (2 textures x width x band rows x 4 bytes per card); a cap is never raised to fit a bake. ## Licence diff --git a/scripts/ridge-bake/export.py b/scripts/ridge-bake/export.py index 1ac70028..0ace0244 100644 --- a/scripts/ridge-bake/export.py +++ b/scripts/ridge-bake/export.py @@ -3,7 +3,7 @@ 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; it lights the cards itself (ruling ridge-cards-runtime-lit). The pure parts (budget, bake_id, manifest, index, schema check) +The runtime reads manifest.json (SCHEMA is its contract) and nothing else about the bake; the camera (ruling ridge-camera-on-circle) is the baker's, so per-card scale and the heading range ride the manifest; it lights the cards itself (ruling ridge-cards-runtime-lit). The pure parts (budget, bake_id, manifest, index, schema check) import no baker; bake_place imports ridge, which needs RIDGE_TILES and RIDGE_WORK (main sets them from --tiles / --work).""" import os, sys, json, math, shutil, hashlib, argparse, tempfile from pathlib import Path @@ -19,6 +19,10 @@ MAX_CARDS = 6 # per place; a full-frame card decodes to TOTAL_BYTES_MAX = 1_500_000 # every card file of a place together DECODE_BYTES_MAX = 20_000_000 # the cards decoded: sum over cards of 2 textures x w x band h x 4 bytes COVER_TOL = 0.02 # the composite of the cards may differ from the opaque view by this much of a pixel, nowhere more +CAMERA_R_M = 200.0 # ruling ridge-camera-on-circle: the camera sits on a circle of this radius round the bake centre, signed, + forward along its heading and - backward; places.json may set camera_r_m per place. The steward's calibration for feel, tuned in the art pass +HEADING_MAX_DEG = 23.0 # the drift's heading range each side of look_az: today's phone sweep, 409 card px (the runtime caps it by what a viewport can cover) +R_FRAC_MAX = 0.5 # |r| stays under this share of the nearest card's distance: the offset must stay well inside the nearest cylinder +REST_SCALE_MIN = 1 / 1.1 # a 16:9 viewport is width-bound and the runtime's plane is 1.1 viewport widths wide (view.ts windowFor, DRIFT_FRAC 0.05 a side): a card scaled below this leaves the viewport's edge bare at rest 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 @@ -39,8 +43,9 @@ SCHEMA = {'$schema': 'https://json-schema.org/draft/2020-12/schema', 'title': 'r view=_obj(look_az_deg=_num, window_deg={'const': WINDOW_DEG}, plane_w={'type': 'integer', 'maximum': PLANE_W_MAX}, plane_h=_int, px_per_deg_h=_num, px_per_deg_v=_num, exaggeration=_num, horizon_row=_num, sky_row=_num, near_row=_num), curvature=_obj(r_earth_m=_num, k_ref=_num), encoding=_obj(log_d_min=_num, log_d_max=_num, normal={'const': 'rt8'}), - cards={'type': 'array', 'minItems': 1, 'maxItems': MAX_CARDS, 'items': dict(_obj(top=_int, h=_int, near_m=_numnull, far_m=_numnull, median_m=_num, colour=_file, geometry=_file), - description='nearest first; the runtime paints the list last to first. top and h place the card back at its rows of the frame; near_m and far_m are the median seam depths, null at the ends.')}, + camera=_obj(r_m=_num, heading_max_deg=_num), + cards={'type': 'array', 'minItems': 1, 'maxItems': MAX_CARDS, 'items': dict(_obj(top=_int, h=_int, near_m=_numnull, far_m=_numnull, median_m=_num, distance_m=_num, scale=_num, colour=_file, geometry=_file), + description="nearest first; the runtime paints the list last to first. top and h place the card back at its rows of the frame; near_m and far_m are the median seam depths, null at the ends; median_m and distance_m are the median distance of the card's solid pixels that are not wall; scale = distance_m / (distance_m - camera.r_m) is the card's pan rate per unit of heading and its static size.")}, w=_int, h=_int, 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})}} @@ -70,9 +75,12 @@ def u8(a): return np.clip(np.rint(np.asarray(a) * 255.0), 0, 255).astype(np.uint 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): - """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.""" - b = (np.asarray(logd) - enc['log_d_min']) / (enc['log_d_max'] - enc['log_d_min']); return bytes(imagecodecs.webp_encode(np.dstack([u8((np.asarray(n_r) + 1) / 2), u8((np.asarray(n_t) + 1) / 2), u8(b)]), lossless=True)) +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. 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) @@ -96,6 +104,16 @@ def check_budget(card_bytes, w, bands): decoded = sum(2 * w * h * 4 for h in bands) if decoded > DECODE_BYTES_MAX: raise ValueError(f'the cards decode to {decoded} bytes, above {DECODE_BYTES_MAX}') +def card_scales(distances, r_m): + """scale_i = d_i / (d_i - r) for the cards' distances (m), nearest first: the card's pan rate per unit of heading and its static size seen from a camera r metres along its heading (ruling ridge-camera-on-circle; + forward, - backward). Refuses |r| >= R_FRAC_MAX x the nearest distance.""" + if abs(r_m) >= R_FRAC_MAX * min(distances): raise ValueError(f"the camera offset {r_m:g} m is not under {R_FRAC_MAX} x the nearest card's distance {min(distances):g} m") + return [d / (d - r_m) for d in distances] +def check_camera(scales, tops, bands, view): + """Refuse a camera whose scaled cards leave the frame uncovered: the nearest card, scaled about the horizon row, must still reach the frame bottom (a backward camera shrinks it away), and no card may be smaller than REST_SCALE_MIN (a 16:9 viewport's edge).""" + hr = view['horizon_row']; bottom = hr + (tops[0] + bands[0] - hr) * scales[0] + if bottom < view['plane_h'] - 1e-6: raise ValueError(f"the camera lifts the nearest card to row {bottom:.1f}, off the frame bottom (row {view['plane_h']})") + if min(scales) < REST_SCALE_MIN: raise ValueError(f'a card scaled {min(scales):.3f} cannot cover a 16:9 viewport at rest (below {REST_SCALE_MIN:.3f})') + def bake_id(cards): """First 12 hex of sha256 over the card files in index order, colour then geometry. cards: [(colour bytes, geometry bytes)].""" h = hashlib.sha256() @@ -103,8 +121,8 @@ def bake_id(cards): return h.hexdigest()[:12] def write_bake(out, place, view, meta, cards, opaque, default=None): - """Write out/-/ (card WebPs + manifest.json), rewrite out/index.json, delete the place's previous dir. cards: [dict(top, colour bytes, geometry bytes, near_m, far_m, median_m)], nearest first; opaque (h, w) is - the opaque view's coverage. Refuses before writing a bake whose files decode to different sizes, leave the frame or the view's plane_h, break the budget or composite away from the opaque view. meta: dict(curvature, encoding). Returns the directory.""" + """Write out/-/ (card WebPs + manifest.json), rewrite out/index.json, delete the place's previous dir. cards: [dict(top, colour bytes, geometry bytes, near_m, far_m, median_m, distance_m, scale)], nearest first; opaque (h, w) is + the opaque view's coverage. Refuses before writing a bake whose files decode to different sizes, leave the frame or the view's plane_h, break the budget or composite away from the opaque view. meta: dict(curvature, encoding, camera dict(r_m, heading_max_deg)). Returns the directory.""" dec = [(decode(c['colour']), decode(c['geometry'])) for c in cards]; shapes = {a.shape[:2] for pair in dec for a in pair}; bands = [a.shape[0] for a, _ in dec] if any(c.shape[:2] != g.shape[:2] for c, g in dec): raise ValueError('a card colour and geometry are not one size') if len({a.shape[1] for pair in dec for a in pair}) != 1: raise ValueError(f'the cards are not one width: {sorted(shapes)}') @@ -112,10 +130,10 @@ def write_bake(out, place, view, meta, cards, opaque, default=None): if any(band < 1 or c['top'] < 0 or c['top'] + band > h for c, band in zip(cards, bands)): raise ValueError(f'a card leaves the {h} rows of the frame') if opaque.shape != (h, w): raise ValueError(f'the opaque view is {opaque.shape}, the frame {(h, w)}') sizes = [len(c['colour']) + len(c['geometry']) for c in cards]; check_budget(sizes, w, bands) - check_cover([(c['top'], col[..., 3] / 255.0) for c, (col, _) in zip(cards, dec)], opaque) + check_cover([(c['top'], col[..., 3] / 255.0) for c, (col, _) in zip(cards, dec)], opaque); check_camera([c['scale'] for c in cards], [c['top'] for c in cards], bands, view) bid = bake_id([(c['colour'], c['geometry']) for c in cards]); name = f"{place['id']}-{bid}"; out = Path(out); dest = out / name - manifest = dict(schema=2, baker_version=BAKER_VERSION, bake_id=bid, place=place, view=dict(view, window_deg=WINDOW_DEG, plane_w=w), curvature=meta['curvature'], encoding=dict(meta['encoding'], normal='rt8'), - cards=[dict(top=c['top'], h=band, near_m=c['near_m'], far_m=c['far_m'], median_m=c['median_m'], colour=dict(file=f'card-{i}-colour.webp', bytes=len(c['colour'])), geometry=dict(file=f'card-{i}-geometry.webp', bytes=len(c['geometry']))) + manifest = dict(schema=2, baker_version=BAKER_VERSION, bake_id=bid, place=place, view=dict(view, window_deg=WINDOW_DEG, plane_w=w), curvature=meta['curvature'], encoding=dict(meta['encoding'], normal='rt8'), camera=dict(r_m=meta['camera']['r_m'], heading_max_deg=meta['camera']['heading_max_deg']), + cards=[dict(top=c['top'], h=band, near_m=c['near_m'], far_m=c['far_m'], median_m=c['median_m'], distance_m=c['distance_m'], scale=c['scale'], colour=dict(file=f'card-{i}-colour.webp', bytes=len(c['colour'])), geometry=dict(file=f'card-{i}-geometry.webp', bytes=len(c['geometry']))) for i, (c, band) in enumerate(zip(cards, bands))], w=w, h=h, bytes=sum(sizes), attribution=ATTRIBUTION) validate(manifest, SCHEMA['$defs']['manifest']); out.mkdir(parents=True, exist_ok=True); tmp = Path(tempfile.mkdtemp(dir=out, prefix='.bake-')) for i, c in enumerate(cards): (tmp / f'card-{i}-colour.webp').write_bytes(c['colour']); (tmp / f'card-{i}-geometry.webp').write_bytes(c['geometry']) @@ -137,22 +155,30 @@ def bake_place(pid): nrm = tuple(ridge.win(x) for x in ridge.normals(d, h)); aw, hw = ridge.win(a), ridge.win(h); cov = ridge.coverage(d, aw); sm = ridge.seams(cov, [k * 1000.0 for k in p['card_split_km']], d) place = dict(id=p['id'], name=p['name'], lat=p['lat'], lon=p['lon'], altitude_km=p['ground_m'] / 1000.0, eye_m=p['eye_m']) 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]))) + meta = dict(curvature=dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF), encoding=dict(log_d_min=math.log(d[0]), log_d_max=math.log(d[-1])), camera=dict(r_m=float(p.get('camera_r_m', CAMERA_R_M)), heading_max_deg=HEADING_MAX_DEG)) return dict(place=place, view=view, meta=meta, cards=ridge.cards(d, aw, hw, sm, nrm), splits_km=list(p['card_split_km']), seams=sm, cov=cov, opaque=ridge.opaque(aw), edges=ridge.log_edges(d)) def pack(bake): - """The cards of a bake as bytes plus their manifest facts: median seam depths either side, median distance of the card's solid pixels.""" - enc = bake['meta']['encoding']; sm = bake['seams']; out = []; sp = bake['splits_km'] - for i, c in enumerate(bake['cards']): + """The cards of a bake as bytes plus their manifest facts: median seam depths either side, the median distance of the card's solid pixels that are not wall (median_m = distance_m), and scale = distance_m / (distance_m - camera r). Refuses a card + with no solid terrain apart from its wall rows, and a camera offset the cards cannot take (card_scales).""" + enc = bake['meta']['encoding']; sm = bake['seams']; out = []; sp = bake['splits_km']; cs = bake['cards'] + for i, c in enumerate(cs): if c['alpha'].shape[0] == 0: raise ValueError(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") - for i, c in enumerate(bake['cards']): - solid = c['alpha'] >= 0.5; out.append(dict(top=c['top'], colour=encode_colour(c['albedo'], c['alpha']), geometry=encode_geometry(c['n_r'], c['n_t'], c['logd'], enc), - 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, median_m=float(np.exp(np.median(c['logd'][solid]))) if solid.any() else 0.0)) + dist = [] + for i, c in enumerate(cs): + ground = (c['alpha'] >= 0.5) & ~c['wall'] + if not ground.any(): raise ValueError(f'card {i} holds no solid terrain apart from its wall rows') + dist.append(float(np.exp(np.median(c['logd'][ground])))) + scales = card_scales(dist, bake['meta']['camera']['r_m']) + for i, c in enumerate(cs): + out.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']), + 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, median_m=dist[i], distance_m=dist[i], scale=scales[i])) return out 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).""" - up = np.sqrt(np.clip(1 - c['n_r'] ** 2 - c['n_t'] ** 2, 0, 1)); L = np.array(SHEET_LIGHT) / np.linalg.norm(SHEET_LIGHT); nl = np.clip(c['n_r'] * L[0] + c['n_t'] * L[1] + up * L[2], 0, 1) + """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), stacked: the composite, every card alone, and the depth image (log-distance bins, far at the top, every seam drawn). All lit by SHEET_LIGHT over the flat SHEET_SKY; reads the arrays the encoder writes.""" diff --git a/scripts/ridge-bake/ridge-bake.schema.json b/scripts/ridge-bake/ridge-bake.schema.json index fbf47731..b58a6c69 100644 --- a/scripts/ridge-bake/ridge-bake.schema.json +++ b/scripts/ridge-bake/ridge-bake.schema.json @@ -12,6 +12,7 @@ "view", "curvature", "encoding", + "camera", "cards", "w", "h", @@ -146,6 +147,22 @@ } } }, + "camera": { + "type": "object", + "required": [ + "r_m", + "heading_max_deg" + ], + "additionalProperties": false, + "properties": { + "r_m": { + "type": "number" + }, + "heading_max_deg": { + "type": "number" + } + } + }, "cards": { "type": "array", "minItems": 1, @@ -158,6 +175,8 @@ "near_m", "far_m", "median_m", + "distance_m", + "scale", "colour", "geometry" ], @@ -184,6 +203,12 @@ "median_m": { "type": "number" }, + "distance_m": { + "type": "number" + }, + "scale": { + "type": "number" + }, "colour": { "type": "object", "required": [ @@ -217,7 +242,7 @@ } } }, - "description": "nearest first; the runtime paints the list last to first. top and h place the card back at its rows of the frame; near_m and far_m are the median seam depths, null at the ends." + "description": "nearest first; the runtime paints the list last to first. top and h place the card back at its rows of the frame; near_m and far_m are the median seam depths, null at the ends; median_m and distance_m are the median distance of the card's solid pixels that are not wall; scale = distance_m / (distance_m - camera.r_m) is the card's pan rate per unit of heading and its static size." } }, "w": { diff --git a/scripts/ridge-bake/ridge.py b/scripts/ridge-bake/ridge.py index 62a7a256..80d38e4c 100644 --- a/scripts/ridge-bake/ridge.py +++ b/scripts/ridge-bake/ridge.py @@ -239,11 +239,12 @@ def cards(d, a, h, seams, nrm=None): 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. - nrm is normals(d, h) of the same columns (default: computed from h as given, so pass it for a window cut from the ring). Each card: dict(top, alpha (h,n), albedo (h,n,3), n_r, n_t, logd (ln metres) (h,n)).""" + nrm is normals(d, h) of the same columns (default: computed from h as given, so pass it for a window cut from the ring). Rows of a card i > 0 below the angle of its first sample (hit and idx == 0) are the extruded wall of the ridge the card starts at: 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 has no wall: its rows below the first sample are the ground). Each card: dict(top, alpha (h,n), albedo (h,n,3), n_r, n_t, logd (ln metres) (h,n), wall (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 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 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)) # coverage, far fade, then (logd, h, n_r, n_t, n_u) + 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) # coverage, far fade, then (logd, h, n_r, n_t, n_u); wall rows 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]) @@ -254,12 +255,13 @@ def cards(d, a, h, seams, nrm=None): 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) + if i: Wl[i, :, x] = hit & (idx == 0) # rows below the card's first sample: the extruded wall (card 0's are the ground) 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))); continue + 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))); 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], g[4] / nz).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))) + 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)).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())) return out diff --git a/scripts/ridge-bake/tests/mutate.py b/scripts/ridge-bake/tests/mutate.py index 12169b84..70b889fb 100644 --- a/scripts/ridge-bake/tests/mutate.py +++ b/scripts/ridge-bake/tests/mutate.py @@ -16,7 +16,7 @@ MUTANTS = { # name -> (text in ridge.py or export.py, replacement) 'check_cover accepts any composite': ("if bad.any(): y, x", "if False: y, x"), 'check_budget ignores the cropped bands (decoded as full frames)': ("decoded = sum(2 * w * h * 4 for h in bands)", "decoded = 0"), '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': ("dstack([u8((np.asarray(n_r) + 1) / 2), u8((np.asarray(n_t) + 1) / 2), u8(b)])", "dstack([u8((np.asarray(n_t) + 1) / 2), u8((np.asarray(n_r) + 1) / 2), u8(b)])"), + '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])"), @@ -26,6 +26,19 @@ MUTANTS = { # name -> (text in ridge.py or export.py, replacement) '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)': ("if i: Wl[i, :, x] = hit & (idx == 0)", "if i: Wl[i, :, x] = False"), + 'wall: card 0 is flagged too (its ground rows become wall)': ("if i: Wl[i, :, x] = hit & (idx == 0)", "Wl[i, :, x] = hit & (idx == 0)"), + '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']"), + 'camera: the sign of r is flipped in the scale': ("return [d / (d - r_m) for d in distances]", "return [d / (d + r_m) for d in distances]"), + 'camera: the scale is clamped (a function of r that is not the formula)': ("return [d / (d - r_m) for d in distances]", "return [min(d / (d - r_m), 1.2) for d in distances]"), + 'camera: the card distance includes wall rows': ("ground = (c['alpha'] >= 0.5) & ~c['wall']", "ground = (c['alpha'] >= 0.5)"), + 'camera: the offset bound is ignored': ("if abs(r_m) >= R_FRAC_MAX * min(distances): raise", "if False: raise"), + 'camera: the frame-bottom coverage check is removed': ("if bottom < view['plane_h'] - 1e-6: raise", "if False: raise"), + 'camera: the 16:9 rest coverage check is removed': ("if min(scales) < REST_SCALE_MIN: raise", "if False: raise"), + 'camera: the preset camera_r_m is ignored': ("r_m=float(p.get('camera_r_m', CAMERA_R_M))", "r_m=float(CAMERA_R_M)"), + 'camera: the manifest writes the default heading range, not the bake\'s': ("heading_max_deg=meta['camera']['heading_max_deg']),", "heading_max_deg=HEADING_MAX_DEG),"), 'export: an empty card is not refused': ("if c['alpha'].shape[0] == 0: raise", "if False: raise"), '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), ", ""), diff --git a/scripts/ridge-bake/tests/test_ridge.py b/scripts/ridge-bake/tests/test_ridge.py index d52e2af2..8a323cf5 100644 --- a/scripts/ridge-bake/tests/test_ridge.py +++ b/scripts/ridge-bake/tests/test_ridge.py @@ -51,12 +51,16 @@ def _bake(hfun, splits_km, sigma=0.0): nrm = tuple(ridge.win(x) for x in ridge.normals(D, h)); aw, hw = ridge.win(a), ridge.win(h); cov = ridge.coverage(D, aw); sm = ridge.seams(cov, [k * 1000.0 for k in splits_km], D) place = dict(id='synthetic', name='Synthetic', lat=48.0, lon=16.0, altitude_km=0.05, eye_m=EYE) 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]))) + meta = dict(curvature=dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF), encoding=dict(log_d_min=math.log(D[0]), log_d_max=math.log(D[-1])), camera=dict(r_m=export.CAMERA_R_M, heading_max_deg=17.0)) return dict(place=place, view=view, meta=meta, cards=ridge.cards(D, aw, hw, sm, nrm, ), splits_km=list(splits_km), seams=sm, cov=cov, opaque=ridge.opaque(aw), edges=ridge.log_edges(D), a=aw, h=hw, v=v) def _canvas(card, key='alpha'): out = np.zeros((H, WIN) + 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)) +NEARHILL = terrain(block(0, 359.99, 0, 4000, 150), block(0, 359.99, 38000, 40000, 2000)) # ground above the eye from the first sample on: every row of card 0 lies below its first sample +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_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).""" @@ -153,8 +157,10 @@ def test_vienna_k1_k2_k3(): def test_bake_place_manifest_fields_on_vienna(): """bake_place on the real Vienna preset: 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; write_bake of its packed cards validates, index default 'vienna', and no temp dir is left.""" saved = ridge.P + load = ridge.load_preset; ridge.load_preset = lambda pid, *a: dict(load(pid, *a), camera_r_m=123.0) # a preset's camera_r_m is the bake's camera try: b = export.bake_place('vienna'); P = ridge.P; rowang = ridge.rowang; pxv = ridge.PXDEG_V - finally: ridge.P = saved + finally: ridge.P = saved; ridge.load_preset = load + assert b['meta']['camera'] == dict(r_m=123.0, heading_max_deg=export.HEADING_MAX_DEG), b['meta']['camera'] pl, view = b['place'], b['view']; 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 len(b['cards']) == 3 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 d = tempfile.mkdtemp() @@ -165,7 +171,7 @@ def test_bake_place_manifest_fields_on_vienna(): # ---------------------------------------------------------------------------------------- export: manifest v2, budget, cover def _packed(b=None): - b = b or _bake(THREE, [6, 40]); return b, export.pack(b) + b = b or _bake(WIDE3, [20, 55]); return b, export.pack(b) def _refuses(out, b, packed, why, **kw): args = dict(place=b['place'], view=b['view'], meta=b['meta'], cards=packed, opaque=b['opaque']); args.update(kw) try: export.write_bake(out, **args) @@ -176,9 +182,10 @@ def test_manifest_v2_writer(): the old dir, the committed schema is current, and the Copernicus attribution is the four pinned strings.""" d = tempfile.mkdtemp() try: - b, pk = _packed(); b2, pk2 = _packed(_bake(THREE, [6, 40])); assert [(c['colour'], c['geometry']) for c in pk] == [(c['colour'], c['geometry']) for c in pk2], 'two independent bakes gave different bytes' + b, pk = _packed(); b2, pk2 = _packed(_bake(WIDE3, [20, 55])); assert [(c['colour'], c['geometry']) for c in pk] == [(c['colour'], c['geometry']) for c in pk2], 'two independent bakes gave different bytes' a = export.write_bake(d + '/a', b['place'], b['view'], b['meta'], pk, b['opaque']); assert a.name == 'synthetic-' + export.bake_id([(c['colour'], c['geometry']) for c in pk]); assert sorted(os.listdir(d + '/a')) == sorted(['index.json', a.name]) m = json.load(open(a / 'manifest.json')); export.validate(m, export.SCHEMA['$defs']['manifest']); assert m['schema'] == 2 and m['baker_version'] == export.BAKER_VERSION and len(m['cards']) == 3 and m['w'] == WIN and m['h'] == H + assert m['camera'] == dict(r_m=export.CAMERA_R_M, heading_max_deg=17.0) and all(c['scale'] == c['distance_m'] / (c['distance_m'] - export.CAMERA_R_M) and c['distance_m'] == c['median_m'] for c in m['cards']), m['camera'] assert m['cards'][0]['near_m'] is None and m['cards'][-1]['far_m'] is None and m['cards'][0]['far_m'] == m['cards'][1]['near_m'] and m['cards'][0]['median_m'] < m['cards'][1]['median_m'] < m['cards'][2]['median_m'] for c in m['cards']: for kind in ('colour', 'geometry'): f = a / c[kind]['file']; assert f.stat().st_size == c[kind]['bytes'] and export.decode(f.read_bytes()).shape[:2] == (c['h'], WIN), c @@ -212,7 +219,7 @@ def test_cover_and_size_refusals_write_nothing(): finally: shutil.rmtree(d) def _flat_card(top, h, w=WIN, seed=0, noise=False): 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), near_m=None, far_m=None, median_m=1.0) + 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), near_m=None, far_m=None, median_m=1.0, distance_m=1.0, scale=1.0) def test_card_cap_refusals(): """A preset with 6 splits, or splits not increasing, is refused by load_preset before any march; write_bake refuses 4 full-frame 1280x600 cards (24.6 MB decoded) and writes nothing; 6 cards whose bands fit the budget are written; the card count and bytes are capped.""" d = tempfile.mkdtemp() @@ -227,7 +234,7 @@ def test_card_cap_refusals(): except ValueError: pass else: assert False, 'a preset without card_split_km was defaulted' json.dump(dict(presets=[dict(id='x', card_split_km=[1, 2, 3, 4, 5])]), open(os.path.join(d, 'r.json'), 'w')); assert ridge.load_preset('x', os.path.join(d, 'r.json'))['card_split_km'] == [1, 2, 3, 4, 5] - place = dict(id='synthetic', name='S', lat=0.0, lon=0.0, altitude_km=0.0, eye_m=1.0); meta = dict(curvature=dict(r_earth_m=1.0, k_ref=0.1), encoding=dict(log_d_min=0.0, log_d_max=1.0)); 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) + place = dict(id='synthetic', name='S', lat=0.0, lon=0.0, altitude_km=0.0, eye_m=1.0); meta = dict(curvature=dict(r_earth_m=1.0, k_ref=0.1), encoding=dict(log_d_min=0.0, log_d_max=1.0), camera=dict(r_m=0.0, heading_max_deg=1.0)); view = dict(look_az_deg=0.0, plane_h=H, px_per_deg_h=1.0, px_per_deg_v=1.0, exaggeration=1.0, horizon_row=1.0, sky_row=1.0, near_row=1.0) full = np.ones((H, WIN)) _refuses(d + '/four', dict(place=place, view=view, meta=meta, opaque=full), [_flat_card(0, H) for _ in range(4)], 'four full-frame cards (24.6 MB decoded) were written') ok = [_flat_card(0, H)] + [_flat_card(0, 150, seed=i) for i in range(1, 6)]; dest = export.write_bake(d + '/six', place, view, meta, ok, full); assert len(json.load(open(dest / 'manifest.json'))['cards']) == 6 @@ -255,7 +262,7 @@ def test_cards_are_cropped_to_their_band(): def test_an_empty_card_is_refused_before_writing_naming_the_split(): """A card with no rows (its splits leave it no terrain) stops pack with a message that names the splits, instead of dying inside the codec.""" - b = _bake(THREE, [6, 40]); b['cards'][1] = dict(top=0, alpha=np.zeros((0, WIN), np.float32), albedo=np.zeros((0, WIN, 3), np.float32), n_r=np.zeros((0, WIN), np.float32), n_t=np.zeros((0, WIN), np.float32), logd=np.zeros((0, WIN), np.float32)) + b = _bake(THREE, [6, 40]); b['cards'][1] = dict(top=0, alpha=np.zeros((0, WIN), np.float32), albedo=np.zeros((0, WIN, 3), np.float32), n_r=np.zeros((0, WIN), np.float32), n_t=np.zeros((0, WIN), np.float32), logd=np.zeros((0, WIN), np.float32), wall=np.zeros((0, WIN), bool)) try: export.pack(b) except ValueError as e: assert 'card 1 is empty' in str(e) and '6 km' in str(e) and '40 km' in str(e), str(e) else: assert False, 'an empty card was packed' @@ -274,10 +281,10 @@ def test_written_cards_decode_to_the_cards_in_memory(): try: dest = export.write_bake(d, b['place'], b['view'], b['meta'], export.pack(b), b['opaque']); m = json.load(open(dest / 'manifest.json')); enc = m['encoding']; span = enc['log_d_max'] - enc['log_d_min']; partial_seen = 0 for c, rec in zip(b['cards'], m['cards']): - col = export.decode((dest / rec['colour']['file']).read_bytes()); geo = export.decode((dest / rec['geometry']['file']).read_bytes()); al = c['alpha']; solid = al > 0; part = (al > 0.05) & (al < 0.95); partial_seen += int(part.sum()) + col = export.decode((dest / rec['colour']['file']).read_bytes()); geo = export.decode((dest / rec['geometry']['file']).read_bytes()); al = c['alpha']; wall = c['wall']; solid = (al > 0) & ~wall; part = (al > 0.05) & (al < 0.95) & ~wall; partial_seen += int(part.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.02 and np.percentile(e[solid], 99) < 0.08, ('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[..., 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' @@ -285,6 +292,65 @@ def test_written_cards_decode_to_the_cards_in_memory(): assert partial_seen > 0, 'the fixture has no partial alpha' finally: shutil.rmtree(d) +# ---------------------------------------------------------------------------------------- wall rows and the camera +def _first_sample_angle(b, i): + """Per column, the angle of the first sample card i (> 0) reads: the first sample at or beyond its near seam, less the cross-fade half-width.""" + k0 = np.array([np.searchsorted(D, b['seams'][i - 1][x] * math.exp(-ridge.XF)) for x in range(WIN)]); return k0, b['a'][k0, np.arange(WIN)] +def test_wall_rows_flagged(): + """Card i > 0 flags as wall exactly the rows below the angle of its first sample (the extruded face of the ridge it starts at), card 0 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])): + b = make(); assert not b['cards'][0]['wall'].any(), 'card 0 has a wall'; lo = ridge.rowang - 0.5 / ridge.PXDEG_V; seen = 0 + for i, c in enumerate(b['cards']): + if i == 0: continue + 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'], b['meta']['encoding'], 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]) - D[k0[x]]) < 1e-3 * 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]))[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' + b = _bake(NEARHILL, [20]); c0 = b['cards'][0]; lo = ridge.rowang - 0.5 / ridge.PXDEG_V; below = (lo[:, None] < b['a'][0][None, :])[c0['top']:c0['top'] + c0['alpha'].shape[0]] + assert below.sum() > 1000 and not c0['wall'].any(), ('card 0 has no wall, though rows lie below its first sample', int(below.sum())) +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]) +def test_camera_contract(): + """scale_i = d_i / (d_i - r) for r = +200 and r = -100 (a function of r, not a constant or a clamp); a card's distance excludes its wall rows; |r| at half the nearest distance is refused; an r that lifts the nearest card off the frame bottom (backward) is + refused and writes nothing; a card shrunk below what a 16:9 viewport needs is refused; one card works.""" + ds = [1000.0, 12000.0, 40000.0] + for r in (200.0, -100.0, 0.0): assert export.card_scales(ds, r) == [d / (d - r) for d in ds], r + assert export.card_scales(ds, 200.0)[0] > 1.2 and export.card_scales(ds, -100.0)[0] < 0.92 and export.card_scales(ds, 0.0) == [1.0, 1.0, 1.0] + for bad in (500.0, -500.0, 800.0): + try: export.card_scales(ds, bad) + except ValueError: pass + else: assert False, ('an offset of', bad, 'was accepted') + export.card_scales(ds, 499.0); export.card_scales(ds, -499.0) + b = _bake(WIDE3, [20, 55]); c1 = b['cards'][1]; solid = c1['alpha'] >= 0.5; c1['wall'] = np.zeros_like(c1['wall']); c1['wall'][:c1['alpha'].shape[0] * 3 // 4] = True; c1['logd'] = np.where(c1['wall'], c1['logd'] + 3.0, c1['logd']) # three quarters of the card is wall, far off the rest + want = float(np.exp(np.median(c1['logd'][solid & ~c1['wall']]))); with_wall = float(np.exp(np.median(c1['logd'][solid]))); assert abs(with_wall - want) > 0.05 * want, ('the fixture cannot tell the median with walls from the one without', with_wall, want) + pk = export.pack(b); assert abs(pk[1]['distance_m'] - want) < 1e-6 * want and pk[1]['median_m'] == pk[1]['distance_m'], ('the distance counted wall rows', pk[1]['distance_m'], want) + assert [p['scale'] for p in pk] == [p['distance_m'] / (p['distance_m'] - export.CAMERA_R_M) for p in pk] + d = tempfile.mkdtemp() + try: + back = dict(b['meta'], camera=dict(r_m=-100.0, heading_max_deg=23.0)); pkb = export.pack(dict(b, meta=back)); assert all(p['scale'] < 1 for p in pkb) + _refuses(d + '/back', b, pkb, 'a backward camera that lifts the nearest card off the frame bottom was written', meta=back) + try: export.pack(dict(b, meta=dict(b['meta'], camera=dict(r_m=0.5 * pk[0]['distance_m'], heading_max_deg=23.0)))) + except ValueError: pass + else: assert False, 'an offset of half the nearest distance was packed' + view = b['view']; tops = [c['top'] for c in b['cards']]; bands = [c['alpha'].shape[0] for c in b['cards']]; export.check_camera([1.0, 1.0, 1.0], tops, bands, view) + try: export.check_camera([1.0, 1.0, 0.8], tops, bands, view) + except ValueError as e: assert '16:9' in str(e), str(e) + else: assert False, 'a card too small for a 16:9 viewport at rest was accepted' + one, pk1 = _packed(_bake(WALLED, [])); assert len(pk1) == 1 and pk1[0]['scale'] == pk1[0]['distance_m'] / (pk1[0]['distance_m'] - export.CAMERA_R_M); dest = export.write_bake(d + '/one', one['place'], one['view'], one['meta'], pk1, one['opaque']) + assert len(json.load(open(dest / 'manifest.json'))['cards']) == 1 + finally: shutil.rmtree(d) + # ---------------------------------------------------------------------------------------- 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.""" diff --git a/src/app/features/scene/README.md b/src/app/features/scene/README.md index 5413bc27..1c6c5ad6 100644 --- a/src/app/features/scene/README.md +++ b/src/app/features/scene/README.md @@ -1,14 +1,14 @@ # 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?, sky? })` returns `{ login, dispose }` or +- `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) on the host canvas at the viewport's size in canvas pixels, then the stars baked into it, a twinkle overlay canvas for the swinging ones - (`ridge/stars.ts`), the baked ridge planes (below) and, when it rains, tiled rain streaks slid down on the compositor (`ridge/rain.ts`). - With no planes (the load failed) the scene shows sky, stars and weather only. No script runs per frame except the twinkle, at most every 50 ms. + (`ridge/stars.ts`), the lit ridge cards (below) and, when it rains, tiled rain streaks slid down on the compositor (`ridge/rain.ts`). + With no cards (the load failed) the scene shows sky, stars and weather only. No script runs per frame except the twinkle, at most every 50 ms. The host canvas and its parent must be positioned and 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. @@ -18,17 +18,23 @@ means "keep the CSS ground". Everything below this section describes the opt-in and shows `n / median / p95` in a corner readout. - `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 planes: `ridge/manifest.ts` `loadManifest` reads `${BASE_URL}public/ridge/index.json` (config `backgroundScene.place` picks the entry, - unknown or absent: the index default), then the place's `manifest.json` (v1, written by `scripts/ridge-bake/export.py`; it is the one JSON - the backdrop reads). `ridge/frameChoice.ts` picks the two baked frames the sky's sun lies between and a blend weight; `ridge/Backdrop.ts` - decodes only those. `index.ts` `prepare()` loads manifest and planes with the scene chunk, so `createRidgeScene({ backdrop })` stays - synchronous, and a rebuild keeps the old scene up until the new one's planes have loaded, then swaps. The rig is one div of three plane groups (far, mid, near; DOM order is paint order; no z-index, no fixed position, nothing - outside the scene's parent), each drifting on `Element.animate` (transform only, 150 s loop, paused when the tab is hidden, motion is - reduced or the scene is still); a still draws the planes into the host canvas. Two frames are a true crossfade (`frameChoice.ts` - `crossfade`: a at 1 - w plus b at w, summed in an isolated group, `plus-lighter` in the rig and `lighter` in an offscreen for the still), because - the planes are haze as alpha and b laid over a would double the haze. A failure anywhere (404, bad manifest, an image that - will not decode) 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 planes 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/`. +- Ridge cards: `ridge/manifest.ts` `loadManifest` reads `${BASE_URL}public/ridge/index.json` (config `backgroundScene.place` picks the entry, + unknown or absent: the index default), then the place's `manifest.json` (schema 2, written by `scripts/ridge-bake/export.py`; it is the one JSON + the backdrop reads): K G-buffer cards, nearest first, each 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). `index.ts` `prepare()` loads the manifest and, with the scene chunk, + `ridge/Backdrop.ts` `loadBackdrop`: every card's two files fetched and decoded straight (no premultiply, no colour management), then + `ridge/lightCards.ts` lights each card once in WebGL2 for the sky of this build (sun and ambient from the atmosphere, 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, and releases + the context. A sky change is a rebuild, so it lights again; nothing is lit per frame, and the host canvas is only ever asked for 2d. + `createRidgeScene({ backdrop })` stays synchronous, and a rebuild keeps the old scene up until the new one's cards are lit, then swaps. The rig + is one div of K card elements (farthest first; DOM order is paint order; no z-index, no fixed position, nothing outside the scene's parent), + each placed at its rows of the plane and moved by `view.ts` `cardMotion`: the camera turns through the baker's heading range (capped so every card still covers + the viewport) and card i pans `scale_i` x heading and is drawn `scale_i` times its bake, about the horizon centre, as a camera pushed forward on a circle + round the bake centre sees it (ruling ridge-camera-on-circle); the scales come from the manifest. It drifts on `Element.animate` (transform only, 150 s loop, + paused when the tab is hidden, motion is reduced or the scene is still); a still draws the same cards at heading 0 into the host canvas. A failure + anywhere (404, a manifest that is not schema 2, a card that will not 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. diff --git a/src/app/features/scene/index.test.ts b/src/app/features/scene/index.test.ts index f257d3a7..d9557e24 100644 --- a/src/app/features/scene/index.test.ts +++ b/src/app/features/scene/index.test.ts @@ -7,16 +7,18 @@ import { ridgeSkyFor } from './skyForState'; import { forgetManifests } from './ridge/manifest'; import { wireIndex, wireManifest } from './ridge/manifest.fixture'; import { FALLBACK_VIEW } from './ridge/view'; -import { frameChoice } from './ridge/frameChoice'; import { sunAt } from './ridge/sunAt'; import { ridgeWeather } from './ridge/weather'; import { parseWeatherFile, WEATHER_ATTRIBUTION, weatherFromFile } from './ridge/weatherFeed'; -const { createRidgeScene, createScene } = vi.hoisted(() => ({ +const { createRidgeScene, createScene, loadBackdrop } = vi.hoisted(() => ({ createRidgeScene: vi.fn(), createScene: vi.fn(), + loadBackdrop: 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 loader it can hold, fail and count. +vi.mock('./ridge/Backdrop', () => ({ loadBackdrop })); 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 @@ -49,6 +51,35 @@ const microtasks = (n: number) => (p) => p.then(() => undefined), Promise.resolve() ); +/** A loader for `loadBackdrop` that waits on `ctl.hold` (queueing its settle in `ctl.pending`), then resolves a backdrop or, with `ctl.fail` as it stood when asked, null. `ctl.calls` is the sky each call was lit for. */ +const loader = () => { + const ctl = { + pending: [] as Array<() => void>, + hold: false, + fail: false, + calls: [] as any[], + }; + loadBackdrop.mockImplementation( + (manifest: unknown, physical: unknown) => + new Promise((resolve) => { + const fails = ctl.fail; // the outcome belongs to the request, whenever it settles + const settle = () => { + ctl.calls.push(physical); + resolve(fails ? null : { manifest, cards: [] }); + }; + if (ctl.hold) ctl.pending.push(settle); + else settle(); + }) + ); + 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('')}`; @@ -59,6 +90,7 @@ beforeEach(() => { setSkyState('auto'); createRidgeScene.mockReset(); createScene.mockReset(); + loadBackdrop.mockReset(); }); afterEach(() => { setSkyClock(); @@ -71,7 +103,9 @@ 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', FALLBACK_VIEW).top)); + expect(hex(createRidgeScene.mock.calls[0][0].sky.top)).toBe( + hex(ridgeSkyFor('night', FALLBACK_VIEW).top) + ); scene?.dispose(); }); @@ -90,7 +124,9 @@ describe('startBackgroundScene follows the sky state', () => { setSkyState('night'); createRidgeScene.mockReturnValue(fakeScene()); const scene = await startBackgroundScene(config, caps, { canvas }); - expect(hex(createRidgeScene.mock.calls[0][0].sky.top)).toBe(hex(ridgeSkyFor('night', FALLBACK_VIEW).top)); + expect(hex(createRidgeScene.mock.calls[0][0].sky.top)).toBe( + hex(ridgeSkyFor('night', FALLBACK_VIEW).top) + ); scene?.dispose(); }); @@ -102,7 +138,9 @@ describe('startBackgroundScene follows the sky state', () => { setSkyState('day'); await flush(); expect(first.dispose).toHaveBeenCalledOnce(); - expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe(hex(ridgeSkyFor('day', FALLBACK_VIEW).top)); + expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe( + hex(ridgeSkyFor('day', FALLBACK_VIEW).top) + ); scene?.dispose(); expect(second.dispose).toHaveBeenCalledOnce(); }); @@ -115,7 +153,9 @@ describe('startBackgroundScene follows the sky state', () => { const scene = await started; await flush(); expect(createRidgeScene).toHaveBeenCalledTimes(2); - expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe(hex(ridgeSkyFor('day', FALLBACK_VIEW).top)); + expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe( + hex(ridgeSkyFor('day', FALLBACK_VIEW).top) + ); expect(a.dispose).toHaveBeenCalledOnce(); scene?.dispose(); expect(b.dispose).toHaveBeenCalledOnce(); @@ -218,7 +258,9 @@ describe('startBackgroundScene follows the sky state', () => { 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', FALLBACK_VIEW).top)); + expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe( + hex(ridgeSkyFor('dusk', FALLBACK_VIEW).top) + ); scene?.dispose(); }); @@ -311,44 +353,25 @@ describe('the ridge planes', () => { ) ); }; - const images = (reject = false) => { - const loaded: string[] = []; - vi.stubGlobal( - 'Image', - class { - src = ''; - decoding = ''; - cloneNode = () => this; - decode = async () => { - if (reject) throw new Error('bad image'); - loaded.push(this.src); - }; - } - ); - return loaded; - }; beforeEach(() => forgetManifests()); - it('hands the scene the planes of the frame the sky was baked for, over the manifest view', async () => { + 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 loaded = images(); + 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); - // Midnight in Vienna: the night frame, three planes. - expect(loaded.sort()).toEqual([ - '/public/ridge/vienna-abc123abc123/night-far.webp', - '/public/ridge/vienna-abc123abc123/night-mid.webp', - '/public/ridge/vienna-abc123abc123/night-near.webp', - ]); + 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('config place picks the index entry; an unknown id falls back to the default', async () => { served(); - images(); + 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'); @@ -375,13 +398,13 @@ describe('the ridge planes', () => { 'fetch', vi.fn(async () => ({ ok: false, status: 404, json: async () => ({}) })) ); - images(); + loader(); await skyOnly(); }); }); -describe('the ridge planes failing', () => { - it('a rejecting image gives the same sky-only scene, and a rebuild does not report again', async () => { +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) => ({ @@ -390,14 +413,7 @@ describe('the ridge planes failing', () => { json: async () => (url.endsWith('index.json') ? wireIndex : wireManifest()), })) ); - vi.stubGlobal( - 'Image', - class { - decode = async () => { - throw new Error('bad image'); - }; - } - ); + loader().ctl.fail = true; forgetManifests(); createRidgeScene.mockReturnValue(fakeScene()); const onPlanesFail = vi.fn(); @@ -413,7 +429,7 @@ describe('the ridge planes failing', () => { }); }); -describe('the ridge planes and the live scene', () => { +describe('the ridge cards and the live scene', () => { const serve = (manifest: Record = wireManifest()) => vi.stubGlobal( 'fetch', @@ -423,48 +439,11 @@ describe('the ridge planes and the live scene', () => { json: async () => (url.endsWith('index.json') ? wireIndex : manifest), })) ); - /** Image stub whose decode waits on `gate` (when given) and then resolves or rejects as `outcome` says now. */ - const decoder = () => { - const ctl = { - pending: [] as Array<() => void>, - hold: false, - fail: false, - urls: [] as string[], - }; - vi.stubGlobal( - 'Image', - class { - src = ''; - decoding = ''; - cloneNode = () => this; - decode = () => { - const fails = ctl.fail; // the outcome belongs to the request, whenever it settles - return new Promise((resolve, reject) => { - const settle = () => { - ctl.urls.push(this.src); - if (fails) reject(new Error('bad image')); - else resolve(); - }; - if (ctl.hold) ctl.pending.push(settle); - else settle(); - }); - }; - } - ); - return { - ctl, - release: async () => { - ctl.hold = false; - ctl.pending.splice(0).forEach((s) => s()); - await flush(); - }, - }; - }; beforeEach(() => forgetManifests()); - it('says nothing about planes when they load', async () => { + it('says nothing about cards when they load', async () => { serve(); - decoder(); + loader(); createRidgeScene.mockReturnValue(fakeScene()); const onPlanesFail = vi.fn(); const onPlanesOk = vi.fn(); @@ -478,27 +457,41 @@ describe('the ridge planes and the live scene', () => { scene?.dispose(); }); - it('chooses frames by the sun over the manifest place, not the fallback place', async () => { - const w = wireManifest() as any; - // A day where it is night by the clock, in the south, has the noon sun high and to the north; at Vienna it is low in the south: a different frame. - serve({ ...w, place: { ...w.place, lat: -33, lon: -163.65, tz_h: -11 } }); - decoder(); - setSkyState('day'); + it('lights the cards again for the new sky on a sky-change rebuild, never otherwise', async () => { + serve(); + const { ctl } = loader(); createRidgeScene.mockReturnValue(fakeScene()); - (await startBackgroundScene(config, caps, { canvas }))?.dispose(); - const opts = createRidgeScene.mock.calls[0][0]; - const { manifest } = opts.backdrop; - const own = frameChoice(manifest.frames, opts.sky.physical.sun); - const fallbackSun = ridgeSkyFor('day', FALLBACK_VIEW).physical!.sun; - const theirs = frameChoice(manifest.frames, fallbackSun); - expect(own.a.key).not.toBe(theirs.a.key); - expect(opts.backdrop.choice.a.key).toBe(own.a.key); - expect(opts.backdrop.choice.b?.key ?? null).toBe(own.b?.key ?? null); + const scene = await startBackgroundScene(config, caps, { canvas }); + expect(ctl.calls.map((s) => s.state)).toEqual(['night']); + setSkyState('night'); // the sky already drawn: no rebuild, no lighting + await flush(); + expect(ctl.calls).toHaveLength(1); + setSkyState('day'); + await flush(); + expect(ctl.calls.map((s) => s.state)).toEqual(['night', 'day']); + 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('a lighting pass that throws (no WebGL2) is the sky alone, one onPlanesFail and never onCompileFail', async () => { + serve(); + loadBackdrop.mockRejectedValue(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 state over a rebaked place rebuilds", async () => { serve(); - decoder(); + loader(); const [a, b] = [fakeScene(), fakeScene()]; createRidgeScene.mockReturnValueOnce(a).mockReturnValueOnce(b); const w = wireManifest() as any; @@ -536,23 +529,31 @@ describe('the ridge planes and the live scene', () => { ok: true, status: 200, json: async () => - url.endsWith('weather.json') ? wx : url.endsWith('index.json') ? wireIndex : { ...w, place }, + url.endsWith('weather.json') + ? wx + : url.endsWith('index.json') + ? wireIndex + : { ...w, place }, })) ); - decoder(); + loader(); setSkyClock(() => now); createRidgeScene.mockReturnValue(fakeScene()); (await startBackgroundScene(config, caps, { canvas }))?.dispose(); const file = parseWeatherFile(wx)!; const at = (p: { lat: number; lon: number }) => - weatherFromFile(file, sunAt({ id: 'x', altitudeKm: 0, ...p }, new Date(Date.parse(wx.observed_at) - 5 * 60_000)).elevation); + weatherFromFile( + file, + sunAt({ id: 'x', altitudeKm: 0, ...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 } = decoder(); + const { ctl } = loader(); ctl.fail = true; createRidgeScene.mockReturnValue(fakeScene()); const scene = await startBackgroundScene(config, caps, { canvas }); @@ -564,7 +565,7 @@ describe('the ridge planes and the live scene', () => { it('a rebuild keeps the old scene until the new planes have loaded, then swaps', async () => { serve(); - const d = decoder(); + const d = loader(); const first = fakeScene(); const second = fakeScene(); createRidgeScene.mockReturnValueOnce(first).mockReturnValueOnce(second); @@ -590,7 +591,7 @@ describe('the ridge planes and the live scene', () => { it('a build that fails after the scene is disposed makes nothing and says nothing', async () => { serve(); - const d = decoder(); + const d = loader(); createRidgeScene.mockReturnValue(fakeScene()); const onPlanesFail = vi.fn(); const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail }); @@ -606,7 +607,7 @@ describe('the ridge planes and the live scene', () => { it('a superseded build that fails does not speak for the live scene, which has planes', async () => { serve(); - const d = decoder(); + const d = loader(); createRidgeScene.mockReturnValue(fakeScene()); const onPlanesFail = vi.fn(); const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail }); @@ -617,7 +618,7 @@ describe('the ridge planes and the live scene', () => { d.ctl.fail = false; setSkyState('dusk'); // the live one: its decodes will succeed await flush(); - const stale = d.ctl.pending.splice(0, 6); + 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 @@ -628,9 +629,12 @@ describe('the ridge planes and the live scene', () => { it('a superseded build that finishes after the newer one touches nothing of the live scene', async () => { serve(); - const d = decoder(); + const d = loader(); const [first, second, third] = [fakeScene(), fakeScene(), fakeScene()]; - createRidgeScene.mockReturnValueOnce(first).mockReturnValueOnce(second).mockReturnValueOnce(third); + createRidgeScene + .mockReturnValueOnce(first) + .mockReturnValueOnce(second) + .mockReturnValueOnce(third); const onActive = vi.fn(); const scene = await startBackgroundScene(config, caps, { canvas, onActive }); d.ctl.hold = true; @@ -661,7 +665,7 @@ describe('the ridge planes and the live scene', () => { it('a build that finishes after dispose makes nothing, shows nothing and disposes nothing twice', async () => { serve(); - const d = decoder(); + const d = loader(); const first = fakeScene(); createRidgeScene.mockReturnValueOnce(first).mockReturnValueOnce(fakeScene()); const onActive = vi.fn(); @@ -678,7 +682,7 @@ describe('the ridge planes and the live scene', () => { it('a rebuild that makes no scene says nothing about planes and leaves the host inactive', async () => { serve(); - const d = decoder(); + const d = loader(); createRidgeScene.mockReturnValueOnce(fakeScene()).mockReturnValueOnce(null); const onPlanesFail = vi.fn(); const onInactive = vi.fn(); @@ -693,7 +697,7 @@ describe('the ridge planes and the live scene', () => { it('tells the host when the live scene loses its planes and when it gets them back', async () => { serve(); - const d = decoder(); + const d = loader(); d.ctl.fail = true; createRidgeScene.mockReturnValue(fakeScene()); const onPlanesFail = vi.fn(); diff --git a/src/app/features/scene/index.ts b/src/app/features/scene/index.ts index 3fe68a95..794a9597 100644 --- a/src/app/features/scene/index.ts +++ b/src/app/features/scene/index.ts @@ -8,7 +8,6 @@ import type { Backdrop } from './ridge/Backdrop'; import { loadManifest } from './ridge/manifest'; import type { RidgeManifest } from './ridge/manifest'; import { FALLBACK_VIEW } from './ridge/view'; -import { frameChoice } from './ridge/frameChoice'; export type { Scene, SceneStats } from './Scene'; export type { SceneStyle, SceneTier } from './tier'; @@ -20,7 +19,7 @@ export type StartOptions = Omit void; /** A rebuild made a scene again: the host lets it show. */ onActive?: () => void; - /** The live scene is the sky alone because the baked ridge planes did not load (no manifest, a missing image). The host may fill the ground. Told when the live scene changes to that state, never for a build that did not win. */ + /** 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; @@ -77,7 +76,8 @@ async function prepare( const { createRidgeScene } = await import('./ridge/Ridge'); const { manifest, fail } = await manifestOf(config); await loadWeather(weatherUrl(), (manifest?.view ?? FALLBACK_VIEW).place); - // The planes load with the scene chunk and the weather: createRidgeScene stays synchronous. Any failure is the sky alone. + // The cards load with the scene chunk and the weather, and are lit here for this sky (once per build: a sky change comes through a rebuild, never per + // frame), so createRidgeScene stays synchronous. Any failure, a missing WebGL2 included, is the sky alone. let backdrop: Backdrop | null = null; let sky: SkyColours | undefined; let planesFail: Error | null = fail; @@ -85,13 +85,12 @@ async function prepare( try { const manifestSky = ridgeSkyFor(state, manifest.view); sky = manifestSky; - const choice = frameChoice( - manifest.frames, - (manifestSky.physical as NonNullable).sun - ); const { loadBackdrop } = await import('./ridge/Backdrop'); - backdrop = await loadBackdrop(manifest, choice); - if (!backdrop) throw new Error('ridge planes did not load'); + backdrop = await loadBackdrop( + manifest, + manifestSky.physical as NonNullable + ); + if (!backdrop) throw new Error('ridge cards did not load'); } catch (e) { backdrop = null; sky = undefined; diff --git a/src/app/features/scene/ridge/Backdrop.test.ts b/src/app/features/scene/ridge/Backdrop.test.ts index 8c88d46f..bd030b85 100644 --- a/src/app/features/scene/ridge/Backdrop.test.ts +++ b/src/app/features/scene/ridge/Backdrop.test.ts @@ -1,44 +1,90 @@ -import { describe, expect, it, vi } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; import { loadBackdrop } from './Backdrop'; -import { frameChoice } from './frameChoice'; +import type { LitCard } from './lightCards'; import { parseManifest } from './manifest'; import { wireManifest } from './manifest.fixture'; +import type { PhysicalSky } from './physicalSky'; +const sky = {} as PhysicalSky; const manifest = parseManifest(wireManifest(), '/d/'); -const img = (src: string) => ({ src } as unknown as HTMLImageElement); + +const stubDecoder = () => { + const made: { url: string; opts: unknown; closed: boolean }[] = []; + vi.stubGlobal( + 'createImageBitmap', + vi.fn(async (blob: Blob & { url: string }, opts: unknown) => { + if (blob.url.endsWith('card-2-geometry.webp') && fail.on) throw new Error('bad card'); + const bmp = { url: blob.url, opts, closed: false, close: () => (bmp.closed = true) }; + made.push(bmp); + return bmp; + }) + ); + return made; +}; +const fail = { on: false }; +const blobFor = async (url: string) => ({ url } as unknown as Blob); +const lit = (m: typeof manifest): LitCard[] => + m.cards.map((c) => ({ canvas: {} as HTMLCanvasElement, top: c.top, h: c.h, scale: c.scale })); + +afterEach(() => { + fail.on = false; + vi.unstubAllGlobals(); +}); describe('loadBackdrop', () => { - it('loads the planes of the needed frames only, by manifest directory', async () => { - const load = vi.fn(async (u: string) => img(u)); - const one = await loadBackdrop( - manifest, - frameChoice(manifest.frames, { elevation: 60, azimuth: 180 }), - load + it('fetches and decodes both files of every card straight, lights once, and returns the cards nearest first', async () => { + const made = stubDecoder(); + const light = vi.fn((m: typeof manifest) => lit(m)); + const bd = await loadBackdrop(manifest, sky, { fetchBlob: blobFor, light }); + expect(bd?.cards.map((c) => c.scale)).toEqual([1.2, 1.0167, 1.005]); + expect(bd?.manifest).toBe(manifest); + expect(made.map((b) => b.url).sort()).toEqual( + [0, 1, 2].flatMap((i) => [`/d/card-${i}-colour.webp`, `/d/card-${i}-geometry.webp`]).sort() ); - expect(load.mock.calls.map((c) => c[0]).sort()).toEqual([ - '/d/noon-far.webp', - '/d/noon-mid.webp', - '/d/noon-near.webp', - ]); - expect(one?.b).toBeNull(); - load.mockClear(); - const two = await loadBackdrop( - manifest, - frameChoice(manifest.frames, { elevation: 10, azimuth: 130 }), - load + made.forEach((b) => + expect(b.opts).toEqual({ premultiplyAlpha: 'none', colorSpaceConversion: 'none' }) ); - expect(load).toHaveBeenCalledTimes(6); - expect(two?.b?.far.src).toBe('/d/morning-far.webp'); - expect(two?.a.near.src).toBe('/d/dawn-near.webp'); + expect(light).toHaveBeenCalledOnce(); + // Handed over in manifest order, each card its own pair. + const given = light.mock.calls[0] as unknown as [ + unknown, + { colour: { url: string }; geometry: { url: string } }[], + unknown + ]; + expect(given[1].map((p) => [p.colour.url, p.geometry.url])).toEqual( + [0, 1, 2].map((i) => [`/d/card-${i}-colour.webp`, `/d/card-${i}-geometry.webp`]) + ); + expect(given[2]).toBe(sky); }); - it('is null, and does not throw, when any image rejects', async () => { - const load = vi.fn(async (u: string) => { - if (u.includes('mid')) throw new Error('decode'); - return img(u); - }); - await expect( - loadBackdrop(manifest, frameChoice(manifest.frames, { elevation: 60, azimuth: 180 }), load) - ).resolves.toBeNull(); + it('closes the decoded bitmaps once they are lit', async () => { + const made = stubDecoder(); + await loadBackdrop(manifest, sky, { fetchBlob: blobFor, light: lit }); + expect(made).toHaveLength(6); + expect(made.every((b) => b.closed)).toBe(true); + }); + + it('is null when any one card will not decode, lights nothing and closes what it decoded', async () => { + const made = stubDecoder(); + fail.on = true; + const light = vi.fn(lit); + expect(await loadBackdrop(manifest, sky, { fetchBlob: blobFor, light })).toBeNull(); + expect(light).not.toHaveBeenCalled(); + expect(made.length).toBeGreaterThan(0); + expect(made.every((b) => b.closed)).toBe(true); + }); + + it('is null when a file is missing, and when the lighting pass throws', async () => { + const made = stubDecoder(); + const gone = async (url: string) => { + if (url.endsWith('card-1-colour.webp')) throw new Error('ridge: 404'); + return blobFor(url); + }; + expect(await loadBackdrop(manifest, sky, { fetchBlob: gone, light: lit })).toBeNull(); + const boom = () => { + throw new Error('no WebGL2'); + }; + expect(await loadBackdrop(manifest, sky, { fetchBlob: blobFor, light: boom })).toBeNull(); + expect(made.every((b) => b.closed)).toBe(true); }); }); diff --git a/src/app/features/scene/ridge/Backdrop.ts b/src/app/features/scene/ridge/Backdrop.ts index f1360980..5e2eca3d 100644 --- a/src/app/features/scene/ridge/Backdrop.ts +++ b/src/app/features/scene/ridge/Backdrop.ts @@ -1,44 +1,55 @@ -// The decoded planes the scene composes: only the frames the choice needs. Failure is a value (null), never a throw. -import type { FrameChoice } from './frameChoice'; -import type { Frame, PlaneName, RidgeManifest } from './manifest'; -import { PLANE_NAMES } from './manifest'; - -export type Planes = Record; +// The ridge cards the scene composes, lit: every card's two files fetched and decoded exactly as the baker wrote them, then lit once for the sky +// (`lightCards.ts`). Failure is a value (null), never a throw. +import type { RidgeManifest } from './manifest'; +import type { PhysicalSky } from './physicalSky'; +import { lightCards } from './lightCards'; +import type { CardBitmaps, LitCard } from './lightCards'; export interface Backdrop { manifest: RidgeManifest; - choice: FrameChoice; - /** Decoded planes of frame a, and of frame b when the choice has one. */ - a: Planes; - b: Planes | null; + /** Nearest first, as the manifest lists them. */ + cards: LitCard[]; } -export type ImageLoader = (url: string) => Promise; +export interface BackdropDeps { + fetchBlob: (url: string) => Promise; + light: (manifest: RidgeManifest, bitmaps: CardBitmaps[], sky: PhysicalSky) => LitCard[]; +} -/** The browser's decoder: an that has decoded, so the first paint does not wait on it. */ -export const loadImage: ImageLoader = async (url) => { - const img = new Image(); - img.decoding = 'async'; - img.src = url; - await img.decode(); - return img; +const fetchBlob = async (url: string): Promise => { + const res = await fetch(url); + if (!res.ok) throw new Error(`ridge: ${url} answered ${res.status}`); + return res.blob(); }; +/** Straight alpha and the file's own values: the colour card's alpha is coverage and the geometry card's channels are data, so neither may be premultiplied or colour-managed. */ +const decode = (blob: Blob): Promise => + createImageBitmap(blob, { premultiplyAlpha: 'none', colorSpaceConversion: 'none' }); + export async function loadBackdrop( manifest: RidgeManifest, - choice: FrameChoice, - load: ImageLoader = loadImage + sky: PhysicalSky, + deps: Partial = {} ): Promise { - const planes = async (f: Frame): Promise => { - const [far, mid, near] = await Promise.all( - PLANE_NAMES.map((n) => load(`${manifest.dir}${f.planes[n]}`)) - ); - return { far, mid, near }; - }; + const get = deps.fetchBlob ?? fetchBlob; + const light = deps.light ?? lightCards; + const open: ImageBitmap[] = []; try { - const [a, b] = await Promise.all([planes(choice.a), choice.b ? planes(choice.b) : null]); - return { manifest, choice, a, b }; + const files = manifest.cards.flatMap((c) => [c.colour, c.geometry]); + const settled = await Promise.allSettled( + files.map(async (f) => decode(await get(`${manifest.dir}${f}`))) + ); + settled.forEach((s) => s.status === 'fulfilled' && open.push(s.value)); + const failed = settled.find((s) => s.status === 'rejected'); + if (failed) throw (failed as PromiseRejectedResult).reason; + const bitmaps = manifest.cards.map((_, i) => ({ + colour: open[2 * i], + geometry: open[2 * i + 1], + })); + return { manifest, cards: light(manifest, bitmaps, sky) }; } catch { return null; + } finally { + open.forEach((b) => b.close?.()); } } diff --git a/src/app/features/scene/ridge/Ridge.test.ts b/src/app/features/scene/ridge/Ridge.test.ts index b916f59e..646fab95 100644 --- a/src/app/features/scene/ridge/Ridge.test.ts +++ b/src/app/features/scene/ridge/Ridge.test.ts @@ -6,11 +6,10 @@ import type { SkyColours } from './skyColour'; import { makeStars } from './stars'; import { makePhysicalSky, paintSky as paintPhysicalSky } from './physicalSky'; import { startBackgroundScene } from '../index'; -import { frameChoice } from './frameChoice'; import { parseManifest } from './manifest'; import { ELSEWHERE_VIEW, wireManifest } from './manifest.fixture'; import type { Backdrop } from './Backdrop'; -import { FALLBACK_VIEW, windowFor } from './view'; +import { cardMotion, FALLBACK_VIEW, windowFor } from './view'; describe('noise', () => { it('is deterministic and in [0, 1)', () => { @@ -147,7 +146,16 @@ function ctx() { 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() {}, createImageData: (w: number, h: number) => ({ @@ -178,7 +186,9 @@ function ctx() { else draws.push('fill'); }, drawImage(...a: unknown[]) { - images.push(Object.assign(a, { alpha: c.globalAlpha, op: c.globalCompositeOperation })); + images.push( + Object.assign(a, { alpha: c.globalAlpha, op: c.globalCompositeOperation, t: c.t, k: c.k }) + ); }, globalAlpha: 1, globalCompositeOperation: 'source-over', @@ -525,25 +535,16 @@ describe('rain in the scene', () => { }); }); -describe('the ridge planes in the scene', () => { - const manifest = parseManifest(wireManifest(), '/d/'); - const fakeImg = (src: string) => { - const el = fakeEl('img'); - el.src = src; - el.cloneNode = () => fakeImg(src); - return el as unknown as HTMLImageElement; - }; - const planes = (k: string) => ({ - far: fakeImg(`${k}-far`), - mid: fakeImg(`${k}-mid`), - near: fakeImg(`${k}-near`), +describe('the ridge cards in the scene', () => { + const manifest = parseManifest(wireManifest(), '/d/'); // three cards, scales 1.2, 1.0167, 1.005, nearest first + const litCards = (): Backdrop => ({ + manifest, + cards: manifest.cards.map((c, k) => { + const canvas = fakeEl('canvas'); + canvas.id = `card-${k}`; + return { canvas: canvas as unknown as HTMLCanvasElement, top: c.top, h: c.h, scale: c.scale }; + }), }); - const backdropAt = (elevation: number, azimuth: number): Backdrop => { - const choice = frameChoice(manifest.frames, { elevation, azimuth }); - return { manifest, choice, a: planes(choice.a.key), b: choice.b ? planes(choice.b.key) : null }; - }; - const NOON = backdropAt(60, 180); - const BLEND = backdropAt(10, 130); const night: SkyColours = { ...DAY, top: [10, 14, 40], @@ -553,10 +554,12 @@ describe('the ridge planes in the scene', () => { }; 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 motion400 = cardMotion(manifest, win); it('stacks the rig after the twinkle canvas and before the rain, with no z-index and no fixed position', () => { const { parent, canvas } = host(); - const s = createRidgeScene({ canvas, tier: 'full', sky: night, backdrop: NOON })!; + const s = createRidgeScene({ canvas, tier: 'full', sky: night, backdrop: litCards() })!; const kinds = parent.children.map((c: any) => c.tag); expect(kinds).toEqual(['canvas', 'canvas', 'div', 'div', 'div']); expect(parent.children[2].children).toHaveLength(3); @@ -568,23 +571,36 @@ describe('the ridge planes in the scene', () => { expect(parent.children).toEqual([canvas]); }); - it('is three groups, far to near, each placed by windowFor and drifting by its depth of driftPx', () => { + it('is one element per card, farthest first, each at its rows of the plane and its origin on the horizon centre', () => { const { parent, canvas } = host(); - const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: NOON })!; + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!; const rig = rigOf(parent); - const win = windowFor(manifest.view, 400, 800); - expect(rig.children).toHaveLength(3); - rig.children.forEach((g: any, k: number) => { - expect(g.style.width).toBe(`${win.plane.w}px`); - expect(g.style.height).toBe(`${win.plane.h}px`); - expect(g.style.bottom).toBe('0px'); - expect(g.style.left).toBe(`${(400 - win.plane.w) / 2}px`); - expect(g.children.map((i: any) => i.src)).toEqual([`noon-${['far', 'mid', 'near'][k]}`]); - const { keyframes, options } = g.anims[0]; - const reach = win.driftPx * [0.35, 0.7, 1][k]; + expect(rig.children.map((c: any) => c.id)).toEqual(['card-2', 'card-1', 'card-0']); + const planeTop = 800 - win.plane.bottom - win.plane.h; + rig.children.forEach((el: any, j: number) => { + const card = manifest.cards[2 - j]; + expect(el.style.left).toBe(`${(400 - win.plane.w) / 2}px`); + expect(el.style.width).toBe(`${win.plane.w}px`); + expect(el.style.top).toBe(`${planeTop + card.top * win.plane.scale}px`); + expect(el.style.height).toBe(`${card.h * win.plane.scale}px`); + expect(el.style.transformOrigin).toBe( + `${win.plane.w / 2}px ${(manifest.view.horizonRow - card.top) * win.plane.scale}px` + ); + }); + s.dispose(); + }); + + it('pans card i by scale_i x heading and scales it by scale_i, to and fro on the compositor', () => { + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!; + rigOf(parent).children.forEach((el: any, j: number) => { + const k = 2 - j; + const { scale, reachPx } = motion400.cards[k]; + const { keyframes, options } = el.anims[0]; + expect(scale).toBe(manifest.cards[k].scale); expect(keyframes).toEqual([ - { transform: `translate3d(${-reach}px,0,0)` }, - { transform: `translate3d(${reach}px,0,0)` }, + { transform: `translate3d(${-reachPx}px,0,0) scale(${scale})` }, + { transform: `translate3d(${reachPx}px,0,0) scale(${scale})` }, ]); expect(options).toMatchObject({ duration: 75000, @@ -593,50 +609,23 @@ describe('the ridge planes in the scene', () => { easing: 'ease-in-out', }); }); - s.dispose(); - }); - - it('crossfades a into b: a at 1 - w, b added at w, in a group of its own', () => { - const { parent, canvas } = host(); - const BLEND3 = backdropAt(4, 130); // w = 0.2, not the symmetric half - const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: BLEND3 })!; - const { w } = BLEND3.choice; - expect(w).toBeCloseTo(0.2, 6); - const g = rigOf(parent).children[1]; - expect(g.style.isolation).toBe('isolate'); - expect( - g.children.map((i: any) => [i.src, i.style.opacity, i.style.mixBlendMode ?? null]) - ).toEqual([ - ['dawn-mid', String(1 - w), null], - ['morning-mid', String(w), 'plus-lighter'], - ]); - s.dispose(); - }); - - it('a lone frame is drawn at full opacity with no blend mode', () => { - const { parent, canvas } = host(); - const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: NOON })!; - const g = rigOf(parent).children[1]; - expect( - g.children.map((i: any) => [i.src, i.style.opacity, i.style.mixBlendMode ?? null]) - ).toEqual([['noon-mid', '1', null]]); + // The nearer the card, the further it travels. + const reach = (j: number) => motion400.cards[2 - j].reachPx; + expect(reach(2)).toBeGreaterThan(reach(1)); + expect(reach(1)).toBeGreaterThan(reach(0)); s.dispose(); }); it('adds no rAF or timer callback of its own: the drift is Element.animate, the stars alone loop', () => { const { canvas } = host(); - const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: NOON })!; - expect(rafQueue).toHaveLength(1); // the frame sampler, as without planes + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!; + expect(rafQueue).toHaveLength(1); // the frame sampler, as without cards s.dispose(); - const bare = host(); - const b = createRidgeScene({ canvas: bare.canvas, tier: 'full', sky: DAY })!; - expect(rafQueue).toHaveLength(1); - b.dispose(); }); it('pauses the drift under reduced motion, in a hidden tab, and plays it again', () => { const { parent, canvas } = host(); - const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: NOON })!; + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!; const anims = rigOf(parent).children.map((g: any) => g.anims[0]); anims.forEach((a: any) => expect(a.play).toHaveBeenCalled()); anims.forEach((a: any) => a.pause.mockClear()); @@ -654,57 +643,36 @@ describe('the ridge planes in the scene', () => { anims.forEach((a: any) => expect(a.cancel).toHaveBeenCalled()); }); - it("a still sums each blended plane in an offscreen (a at 1 - w, then b lighter at w) and draws it at windowFor's placement", () => { + it("a still draws every card, farthest first, scaled by its own scale about the rig's origin, at heading 0", () => { const { parent, canvas } = host(); - const BLEND3 = backdropAt(4, 130); - createRidgeScene({ canvas, tier: 'still', sky: DAY, backdrop: BLEND3 }); - const { w } = BLEND3.choice; - const win = windowFor(manifest.view, 400, 800); - const planesDrawn = images.filter((a) => (a[0] as any).src) as any[]; - expect(planesDrawn.map((a) => [a[0].src, a.alpha, a.op])).toEqual( - ['far', 'mid', 'near'].flatMap((n) => [ - [`dawn-${n}`, 1 - w, 'source-over'], - [`morning-${n}`, w, 'lighter'], - ]) - ); - // Each sum then meets the host canvas once, plainly, at the plane's placement. - const summed = images.filter((a) => !(a[0] as any).src && (a[0] as any).width) as any[]; - expect(summed).toHaveLength(3); - summed.forEach((a) => { + 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(['card-2', 'card-1', 'card-0']); + const dpr = 2; + const s = win.plane.scale * dpr; + const x0 = (800 - win.plane.w * dpr) / 2; + const planeTop = 1600 - win.plane.h * dpr; + const origin = [x0 + (win.plane.w * dpr) / 2, planeTop + manifest.view.horizonRow * s]; + drawn.forEach((a, j) => { + const card = manifest.cards[2 - j]; + expect(a.k).toBe(card.scale); + expect(a.t).toEqual(origin); expect([a[1], a[2], a[3], a[4]]).toEqual([ - (800 - win.plane.w * 2) / 2, - 1600 - win.plane.h * 2, - win.plane.w * 2, - win.plane.h * 2, + x0 - origin[0], + planeTop + card.top * s - origin[1], + win.plane.w * dpr, + card.h * s, ]); expect([a.alpha, a.op]).toEqual([1, 'source-over']); - expect([a[0].width, a[0].height]).toEqual([win.plane.w * 2, win.plane.h * 2]); }); expect(parent.children).toEqual([canvas]); }); - it('a lone frame in a still goes straight to the host canvas at full alpha', () => { - const { canvas } = host(); - createRidgeScene({ canvas, tier: 'still', sky: DAY, backdrop: NOON }); - const win = windowFor(manifest.view, 400, 800); - const planesDrawn = images.filter((a) => (a[0] as any).src) as any[]; - expect(planesDrawn.map((a) => [a[0].src, a.alpha, a.op])).toEqual( - ['far', 'mid', 'near'].map((n) => [`noon-${n}`, 1, 'source-over']) - ); - const [, x, y, dw, dh] = planesDrawn[0]; - expect([x, y, dw, dh]).toEqual([ - (800 - win.plane.w * 2) / 2, - 1600 - win.plane.h * 2, - win.plane.w * 2, - win.plane.h * 2, - ]); - }); - - it('settles to a still with the planes painted when the frame rate is poor', () => { + it('settles to a still with the cards painted when the frame rate is poor', () => { const { parent, canvas } = host(); - createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: NOON }); + createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() }); runFrames(100, 400); - expect(images.filter((a) => (a[0] as any).src)).toHaveLength(3); + expect(images.filter((a) => (a[0] as any).id)).toHaveLength(3); expect(parent.children).toEqual([canvas]); }); @@ -712,7 +680,27 @@ describe('the ridge planes in the scene', () => { const { parent, canvas } = host(); createRidgeScene({ canvas, tier: 'full', sky: DAY }); expect(parent.children).toEqual([canvas]); - expect(images.filter((a) => (a[0] as any).src)).toHaveLength(0); + 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 cards 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(); }); }); diff --git a/src/app/features/scene/ridge/Ridge.ts b/src/app/features/scene/ridge/Ridge.ts index 89eb4442..5cbc0cfd 100644 --- a/src/app/features/scene/ridge/Ridge.ts +++ b/src/app/features/scene/ridge/Ridge.ts @@ -3,12 +3,10 @@ import { overlayRequested } from '../debugOverlays'; import { FrameSampler, FrameStats } from './probe'; import { skyColours, SkyColours, Srgb } from './skyColour'; import { paintSky as paintPhysicalSky } from './physicalSky'; -import { windowFor } from './view'; -import { crossfade } from './frameChoice'; +import { cardMotion, windowFor } from './view'; import { activeAt, drawStars, drawTwinkle as paintTwinkle, makeStars, Star } from './stars'; import { drawRainTile, RAIN_TILES } from './rain'; -import type { Backdrop, Planes } from './Backdrop'; -import { PLANE_NAMES } from './manifest'; +import type { Backdrop } from './Backdrop'; export type RidgeOptions = Pick & { /** Show the rAF median/p95 readout. Default: the page URL has `?probe=1`, where `debug` allows it. */ @@ -19,7 +17,7 @@ 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; - /** The baked ridge planes, already decoded; none is the sky-only scene (`view.ts` FALLBACK_VIEW). */ + /** The baked ridge cards, already lit for `sky` (`Backdrop.ts`); none is the sky-only scene (`view.ts` FALLBACK_VIEW). */ backdrop?: Backdrop; }; @@ -97,7 +95,7 @@ const clock = (): number => (typeof performance !== 'undefined' ? performance.no interface Built { /** The twinkling stars' own canvas, over the sky; absent in a day sky and in 'still'. */ twinkle?: HTMLCanvasElement; - /** The ridge planes' rig, over the twinkle canvas and under the rain; absent in 'still' (the planes are drawn into the host canvas). */ + /** The ridge cards' rig, over the twinkle canvas and under the rain; absent in 'still' (the cards are drawn into the host canvas). */ rig?: { el: HTMLElement; anims: (Animation | undefined)[] }; /** The rain's tiles and their falling, present only when the weather rains (`rain.ts`). */ rain?: { els: HTMLElement[]; anims: (Animation | undefined)[] }; @@ -106,13 +104,13 @@ interface Built { /** 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; -/** Far, mid and near slide this share of the drift room (`windowFor` driftPx); one leg of the back-and-forth takes DRIFT_LEG_S, so the loop is 150 s. Authored, tunable by eye. */ -const DRIFT_DEPTH = [0.35, 0.7, 1] as const; +/** One leg of the back-and-forth drift, a turn of the heading from one end of its range to the other, takes DRIFT_LEG_S, so the loop is 150 s. Authored, tunable by eye. */ const DRIFT_LEG_S = 75; /** * The ridge scene: same contract as `createScene` ({ login, dispose }, null for "keep the CSS - * ground"), no WebGL. It draws the sky, the stars, the baked ridge planes when given a `backdrop` (none: the sky alone) and the rain. The host canvas holds the baked sky; it and + * 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 { @@ -210,12 +208,14 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { }; /** - * The ridge over the sky: one div holding a group per plane (far, mid, near: DOM order is paint order, stacking is by order alone), each the frame's - * image and, when the choice blends two frames, the second over it at the blend weight. A group slides sideways on the compositor by - * `driftPx` times its depth; the baker's pixels are never touched. + * The ridge over the sky: one element per lit card, farthest first (DOM order is paint order, stacking is by order alone), placed at the card's rows + * of the plane and scaled about the horizon's centre by the baker's `scale` (`view.ts` `cardMotion` owns every offset and scale). The camera + * turns through its heading range and back on the compositor: card i pans `scale` x heading, so a nearer card leads the far range. */ const startRig = (bd: Backdrop, w: number, h: number): NonNullable => { - const win = windowFor(bd.manifest.view, w, h); + const { view } = bd.manifest; + const win = windowFor(view, w, h); + const motion = cardMotion(bd.manifest, win); const el = document.createElement('div'); el.setAttribute('aria-hidden', 'true'); Object.assign(el.style, { @@ -228,41 +228,26 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { pointerEvents: 'none', }); const anims: (Animation | undefined)[] = []; - PLANE_NAMES.forEach((name, k) => { - const group = document.createElement('div'); - Object.assign(group.style, { + const planeTop = h - win.plane.bottom - win.plane.h; + for (let k = bd.cards.length - 1; k >= 0; k -= 1) { + const card = bd.cards[k]; + const { scale, reachPx } = motion.cards[k]; + const node = card.canvas; + Object.assign(node.style, { position: 'absolute', left: `${(w - win.plane.w) / 2}px`, - bottom: `${win.plane.bottom}px`, + top: `${planeTop + card.top * win.plane.scale}px`, width: `${win.plane.w}px`, - height: `${win.plane.h}px`, + height: `${card.h * win.plane.scale}px`, + transformOrigin: `${win.plane.w / 2}px ${(view.horizonRow - card.top) * win.plane.scale}px`, willChange: 'transform', }); - const layer = (planes: Planes, opacity: number, blend?: string) => { - const img = planes[name].cloneNode() as HTMLImageElement; - Object.assign(img.style, { - position: 'absolute', - left: '0', - top: '0', - width: '100%', - height: '100%', - opacity: String(opacity), - }); - if (blend) img.style.mixBlendMode = blend; - group.appendChild(img); - }; - // One rule (`crossfade`): a at 1 - w, b added to it at w; the group is its own isolated backdrop, so the sum meets the sky once. - const fade = crossfade(bd.choice); - group.style.isolation = 'isolate'; - layer(bd.a, fade.a); - if (bd.b) layer(bd.b, fade.b, 'plus-lighter'); - el.appendChild(group); - const reach = win.driftPx * DRIFT_DEPTH[k]; + el.appendChild(node); anims.push( - group.animate?.( + node.animate?.( [ - { transform: `translate3d(${-reach}px,0,0)` }, - { transform: `translate3d(${reach}px,0,0)` }, + { transform: `translate3d(${-reachPx}px,0,0) scale(${scale})` }, + { transform: `translate3d(${reachPx}px,0,0) scale(${scale})` }, ], { duration: DRIFT_LEG_S * 1000, @@ -272,43 +257,32 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { } ) ); - }); + } parent.appendChild(el); return { el, anims }; }; - /** Paint the ridge planes into the host canvas, a and b crossfaded, far to near: the still scene's one image. */ - const paintPlanes = (bd: Backdrop) => { + /** Paint the lit cards into the host canvas, farthest first, each at its scale about the same origin as the rig, at heading 0: 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 } = viewSize(); - const win = windowFor(bd.manifest.view, w, h); + const win = windowFor(view, w, h); + const s = win.plane.scale * scale; const dw = win.plane.w * scale; - const dh = win.plane.h * scale; - const x = (canvas.width - dw) / 2; - const y = canvas.height - dh - win.plane.bottom * scale; - const fade = crossfade(bd.choice); - // A blend is summed in an offscreen of its own, as the rig sums it in an isolated group: 'lighter' on the host canvas would add to the sky. - const sum = bd.b ? document.createElement('canvas') : null; - if (sum) { - sum.width = dw; - sum.height = dh; + const x0 = (canvas.width - dw) / 2; + const planeTop = canvas.height - (win.plane.h + win.plane.bottom) * scale; + const ox = x0 + dw / 2; + const oy = planeTop + view.horizonRow * s; + for (let k = bd.cards.length - 1; k >= 0; k -= 1) { + const card = bd.cards[k]; + ctx.save(); + ctx.translate(ox, oy); + ctx.scale(card.scale, card.scale); + ctx.drawImage(card.canvas, x0 - ox, planeTop + card.top * s - oy, dw, card.h * s); + ctx.restore(); } - const sctx = sum ? context2d(sum) : null; - PLANE_NAMES.forEach((name) => { - if (!bd.b || !sum || !sctx) { - ctx.drawImage(bd.a[name], x, y, dw, dh); - return; - } - sctx.clearRect(0, 0, dw, dh); - sctx.globalCompositeOperation = 'source-over'; - sctx.globalAlpha = fade.a; - sctx.drawImage(bd.a[name], 0, 0, dw, dh); - sctx.globalCompositeOperation = 'lighter'; - sctx.globalAlpha = fade.b; - sctx.drawImage(bd.b[name], 0, 0, dw, dh); - ctx.drawImage(sum, x, y, dw, dh); - }); }; /** Paint the sky, the stars and the rain. Returns false when a 2D context is missing or there is no area yet. */ @@ -397,7 +371,7 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { teardown(); cancelAnimationFrame(raf); raf = 0; - if (opts.backdrop) paintPlanes(opts.backdrop); + if (opts.backdrop) paintCards(opts.backdrop); report(true); }; 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/frameChoice.test.ts b/src/app/features/scene/ridge/frameChoice.test.ts deleted file mode 100644 index 82b9f1a9..00000000 --- a/src/app/features/scene/ridge/frameChoice.test.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { BLEND_EDGE, crossfade, frameChoice } from './frameChoice'; -import { parseManifest } from './manifest'; -import { wireManifest } from './manifest.fixture'; - -const { frames } = parseManifest(wireManifest(), '/d/'); -const at = (elevation: number, azimuth: number) => frameChoice(frames, { elevation, azimuth }); -const keys = (c: ReturnType) => [c.a.key, c.b?.key ?? null]; - -describe('frameChoice', () => { - it('blends continuously with elevation inside a half', () => { - const ws = [3, 6, 9, 12, 15, 18].map((el) => at(el, 130).w); - ws.forEach((w, i) => i && expect(w).toBeGreaterThan(ws[i - 1])); - }); - - it('weights by the elevation between the bracketing keys, a at the lower', () => { - // Morning half: night -12, dawn 0, morning 20, noon 60. Sun 10 deg is half way from dawn to morning. - const c = at(10, 130); - expect(keys(c)).toEqual(['dawn', 'morning']); - expect(c.w).toBeCloseTo(0.5, 6); - }); - - it('uses the afternoon keys after the noon azimuth and the morning keys before', () => { - expect(keys(at(10, 130))).toEqual(['dawn', 'morning']); - expect(keys(at(-1, 250))).toEqual(['dusk', 'golden']); - expect(at(-1, 250).w).toBeCloseTo(1.5 / 8.5, 6); - }); - - it('noon is the same single frame from both halves', () => { - expect(keys(at(60, 170))).toEqual(['noon', null]); - expect(keys(at(60, 190))).toEqual(['noon', null]); - expect(keys(at(75, 190))).toEqual(['noon', null]); - }); - - it('is the night key alone at or below its elevation, in either half', () => { - expect(keys(at(-12, 10))).toEqual(['night', null]); - expect(keys(at(-40, 300))).toEqual(['night', null]); - }); - - it('blends night into dawn before sunrise and dusk into night after sunset', () => { - expect(keys(at(-6, 90))).toEqual(['night', 'dawn']); - expect(keys(at(-6, 270))).toEqual(['night', 'dusk']); - }); - - it('collapses a blend within 2% of either end to one frame, and w stays in 0..1', () => { - expect(keys(at(0.2, 130))).toEqual(['dawn', null]); // w = 0.01 - expect(keys(at(19.8, 130))).toEqual(['morning', null]); // w = 0.99 - const els = Array.from({ length: 325 }, (_, i) => -30 + i * 0.37); - els.forEach((el) => - [0, 100, 179, 181, 270].forEach((az) => { - const c = at(el, az); - expect(c.w).toBeGreaterThanOrEqual(0); - expect(c.w).toBeLessThanOrEqual(1); - expect(c.b === null).toBe(c.w === 0); - }) - ); - }); - - it("splits the halves at the noon frame's azimuth, wherever the bake put it", () => { - const w = wireManifest() as any; - const shifted = parseManifest( - { - ...w, - frames: w.frames.map((f: any) => - f.key === 'noon' ? { ...f, sun: { ...f.sun, az: 170 } } : f - ), - }, - '/d/' - ); - const pick = (az: number) => frameChoice(shifted.frames, { elevation: 10, azimuth: az }); - expect([pick(169).a.key, pick(169).b?.key]).toEqual(['dawn', 'morning']); - expect([pick(171).a.key, pick(171).b?.key]).toEqual(['golden', 'noon']); - }); - - it('collapses exactly at BLEND_EDGE and no further: a blend of 3% still has two frames', () => { - expect(BLEND_EDGE).toBe(0.02); - // Morning half dawn 0 .. morning 20: w = el / 20. - expect(keys(at(0.6, 130))).toEqual(['dawn', 'morning']); // w = 0.03 - expect(keys(at(19.4, 130))).toEqual(['dawn', 'morning']); // w = 0.97 - expect(keys(at(0.2, 130))).toEqual(['dawn', null]); // w = 0.01 - expect(keys(at(19.8, 130))).toEqual(['morning', null]); // w = 0.99 - }); -}); - -describe('crossfade: the one rule of a blend', () => { - // A baked plane is haze as alpha: no pixel opaque, the same alpha in every frame. Frames as (premultiplied) colour and alpha. - const planeA = { c: 0.2, alpha: 0.6 }; - const planeB = { c: 0.5, alpha: 0.6 }; - const sum = (c: ReturnType) => { - const f = crossfade(c); - const b = c.b ? planeB : { c: 0, alpha: 0 }; - return { c: planeA.c * f.a + b.c * f.b, alpha: planeA.alpha * f.a + b.alpha * f.b }; - }; - - it('is a lerp of the two frames: colour and haze alike, never denser than either', () => { - [0.03, 0.2, 0.5, 0.8, 0.97].forEach((w) => { - const c = { a: frames[0], b: frames[1], w }; - const got = sum(c); - expect(got.c).toBeCloseTo(planeA.c * (1 - w) + planeB.c * w, 12); - expect(got.alpha).toBeCloseTo(0.6, 12); // equal alphas stay equal: the haze is not doubled - expect(got.alpha).toBeLessThanOrEqual(Math.max(planeA.alpha, planeB.alpha) + 1e-12); - }); - }); - - it('has no jump where the choice collapses: the blend either side of an edge is within the edge of the lone frame', () => { - const gap = Math.abs(planeA.c - planeB.c); - const high = sum({ a: frames[0], b: frames[1], w: 1 - BLEND_EDGE }); - const low = sum({ a: frames[0], b: frames[1], w: BLEND_EDGE }); - expect(Math.abs(high.c - planeB.c)).toBeLessThanOrEqual(BLEND_EDGE * gap + 1e-12); // collapse shows b alone - expect(Math.abs(low.c - planeA.c)).toBeLessThanOrEqual(BLEND_EDGE * gap + 1e-12); // collapse shows a alone - expect(high.alpha).toBeCloseTo(planeB.alpha, 12); - }); - - it('a lone frame is full weight alone', () => { - expect(crossfade({ a: frames[0], b: null, w: 0 })).toEqual({ a: 1, b: 0 }); - }); -}); diff --git a/src/app/features/scene/ridge/frameChoice.ts b/src/app/features/scene/ridge/frameChoice.ts deleted file mode 100644 index 1bede129..00000000 --- a/src/app/features/scene/ridge/frameChoice.ts +++ /dev/null @@ -1,55 +0,0 @@ -// Which baked frames the live sun lies between, and how far. Pure. The frames are ordered by the sun elevation they were baked for, a -// morning half rising from the night key through dawn and morning to noon, an afternoon half falling from noon through golden and dusk -// to night; the two halves share noon and the night key. The half is the live sun's side of the noon frame's azimuth. -import type { Frame, FrameKey } from './manifest'; - -export interface FrameChoice { - /** The frame shown alone when b is null, else weighted 1 - w. */ - a: Frame; - /** The frame crossfaded in at `w`, or null when one frame stands alone. */ - b: Frame | null; - /** Weight of b in 0..1; 0 when b is null. */ - w: number; -} - -/** Blends this close to either frame are not worth a second image. */ -export const BLEND_EDGE = 0.02; - -/** - * The one rule of a blend, for the rig and the still alike: a true crossfade, a at 1 - w plus b at w, summed (premultiplied) in a group of - * their own. The baked planes carry haze as alpha (no pixel is opaque), so b laid over a at opacity w would double the haze mid-blend - * and jump when the choice collapses to b alone; the sum is a lerp of the two frames and never denser than either. - */ -export function crossfade(choice: FrameChoice): { a: number; b: number } { - return choice.b ? { a: 1 - choice.w, b: choice.w } : { a: 1, b: 0 }; -} - -const MORNING: readonly FrameKey[] = ['night', 'dawn', 'morning', 'noon']; -const AFTERNOON: readonly FrameKey[] = ['night', 'dusk', 'golden', 'noon']; - -export function frameChoice( - frames: readonly Frame[], - sun: { elevation: number; azimuth: number } -): FrameChoice { - const by = (k: FrameKey): Frame => { - const f = frames.find((x) => x.key === k); - if (!f) throw new Error(`frameChoice: no ${k} frame`); - return f; - }; - const noon = by('noon'); - const half = (sun.azimuth < noon.sun.az ? MORNING : AFTERNOON).map(by); - // Ascending in elevation along the half, whatever the bake's numbers: sort so a hand-made manifest cannot invert the order. - half.sort((p, q) => p.sun.el - q.sun.el); - const lowest = half[0]; - const highest = half[half.length - 1]; - if (sun.elevation <= lowest.sun.el) return { a: lowest, b: null, w: 0 }; - if (sun.elevation >= highest.sun.el) return { a: highest, b: null, w: 0 }; - let i = 0; - while (half[i + 1].sun.el < sun.elevation) i += 1; - const lo = half[i]; - const hi = half[i + 1]; - const w = (sun.elevation - lo.sun.el) / (hi.sun.el - lo.sun.el); - if (w < BLEND_EDGE) return { a: lo, b: null, w: 0 }; - if (w > 1 - BLEND_EDGE) return { a: hi, b: null, w: 0 }; - return { a: lo, b: hi, w }; -} diff --git a/src/app/features/scene/ridge/frameLuma.test.ts b/src/app/features/scene/ridge/frameLuma.test.ts deleted file mode 100644 index 271c55c8..00000000 --- a/src/app/features/scene/ridge/frameLuma.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { inkContrast, themeInk } from './frameLuma'; -import { luminance } from '../../../../sky/skyTokens.js'; - -describe('inkContrast', () => { - it('reads the ink from the themes: dark Noonday ink by day and dusk, light Midnight ink at night', () => { - expect(themeInk('day')).toBe('#342d25'); - expect(themeInk('dusk')).toBe('#342d25'); - expect(themeInk('night')).toBe('#aeccff'); - }); - - it('gives the known ratios on a white and on a black ridge', () => { - const dark = luminance('#342d25'); - const light = luminance('#aeccff'); - const day = inkContrast({ min: 1, max: 1 }, 'day'); - expect(day.atMax).toBeCloseTo(1.05 / (dark + 0.05), 10); - expect(day.atMax).toBeCloseTo(13.6, 0); - const night = inkContrast({ min: 0, max: 0 }, 'night'); - expect(night.atMin).toBeCloseTo((light + 0.05) / 0.05, 10); - expect(night.atMin).toBeCloseTo(12.9, 0); - }); - - it('the worst contrast is where the range comes closest to the ink', () => { - const ink = luminance('#342d25'); - const across = inkContrast({ min: 0, max: 1 }, 'day'); - expect(across.worst).toBe(1); - expect(inkContrast({ min: ink + 0.2, max: 0.9 }, 'day').worst).toBeCloseTo( - (ink + 0.2 + 0.05) / (ink + 0.05), - 10 - ); - }); -}); diff --git a/src/app/features/scene/ridge/frameLuma.ts b/src/app/features/scene/ridge/frameLuma.ts deleted file mode 100644 index 77ec241d..00000000 --- a/src/app/features/scene/ridge/frameLuma.ts +++ /dev/null @@ -1,33 +0,0 @@ -// What a baked frame's recorded luma (manifest `frames[].luma`, WCAG linear relative luminance of the composited planes where they are -// solid enough, export.py) means for the text over it: the contrast of the state's theme ink against the ridge's own extremes, no scrim. -// Data for ridge-ad-legibility, which sizes the scrim from it and owns the 4.5:1 pass/fail; nothing here gates. -import { baked } from '../../../../sky/baked'; -import { luminance } from '../../../../sky/skyTokens.js'; -import type { FixedSkyState } from '../skyState'; - -export interface FrameLuma { - min: number; - max: number; -} - -/** The theme text ink skyState.ts's `FixedSkyState` bands derive: Noonday Sky's for day and dusk, Midnight Sky's for night. */ -export const themeInk = (state: FixedSkyState): string => - (state === 'night' ? baked.midnight : baked.noonday).tokens.Surface.OnContainer; - -const ratio = (a: number, b: number): number => (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05); - -/** - * WCAG contrast of the state's ink over a plain backdrop of the ridge's darkest and of its lightest luminance, and `worst`: the lowest - * contrast over every luminance between them (the ink's own luminance clamped into the range, where the two are closest). - */ -export function inkContrast( - luma: FrameLuma, - state: FixedSkyState -): { atMin: number; atMax: number; worst: number } { - const ink = luminance(themeInk(state)); - return { - atMin: ratio(ink, luma.min), - atMax: ratio(ink, luma.max), - worst: ratio(ink, Math.min(luma.max, Math.max(luma.min, ink))), - }; -} 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..289245a8 --- /dev/null +++ b/src/app/features/scene/ridge/lightCards.test.ts @@ -0,0 +1,157 @@ +import { describe, expect, it, vi } from 'vitest'; +import { + decodeNormal, + FRAGMENT, + lightingOf, + skyLut, + SKY_LUT, + SUN_CUTOFF_DEG, + sunColumns, + sunInColumn, + WALL_RT2, +} from './lightCards'; +import { parseManifest } from './manifest'; +import { wireManifest } from './manifest.fixture'; +import type { PhysicalSky } from './physicalSky'; +import { ACES_FIT, ACES_IN, ACES_OUT } 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]; + +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 window, from its own azimuth', () => { + const view = manifest.view; + const cols = sunColumns(view, { azimuth: 214, elevation: 20 }); + expect(cols).toHaveLength(view.planeW * 4); + const at = (x: number) => Array.from(cols.slice(x * 4, x * 4 + 3)); + const mid = at(view.planeW / 2); + expect(mid[0]).toBeCloseTo(Math.cos(20 * RAD), 3); // the middle column looks near the sun's azimuth + expect(at(0)[1]).toBeGreaterThan(0.1); // the left edge has the sun to its right + expect(at(view.planeW - 1)[1]).toBeLessThan(-0.1); + }); +}); + +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, lift: 0.01 } }, + 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.lift]).toEqual([12, 0.01]); + expect(l.ambient).toEqual([0.1, 0.2, 0.3]); + 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.sunTransmittance[0]).toBeCloseTo(0.9 * Math.sin(30 * RAD), 12); + expect(l.sunTransmittance[2]).toBeCloseTo(0.7 * Math.sin(30 * RAD), 12); + expect(lightingOf(manifest, sky(SUN_CUTOFF_DEG - 1)).sunTransmittance).toEqual([0, 0, 0]); + expect( + lightingOf(manifest, sky(SUN_CUTOFF_DEG + 0.5)).sunTransmittance[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), + 9 + ); + expect(texel(0, SKY_LUT.h - 1)[0]).toBe(0); + // The sun lies at 214 degrees, the middle of the window: the cosine from the sun is 1 there and falls to the sides. + const mid = texel(SKY_LUT.w / 2, above)[1]; + expect(mid).toBeGreaterThan(0.999); + expect(texel(0, above)[1]).toBeLessThan(mid); + }); +}); + +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])})`); + }); +}); diff --git a/src/app/features/scene/ridge/lightCards.ts b/src/app/features/scene/ridge/lightCards.ts new file mode 100644 index 00000000..844a07a8 --- /dev/null +++ b/src/app/features/scene/ridge/lightCards.ts @@ -0,0 +1,372 @@ +// The one lighting pass of the ridge cards (ruling ridge-cards-runtime-lit): each baked G-buffer card (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, and copied into a 2D canvas of the card's size. After the last card the context is released: there is no per-frame WebGL, and the +// host canvas stays 2D (`Ridge.ts`). A sky change rebuilds the scene and lights again; 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, black lift, 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 { ACES_FIT, ACES_IN, ACES_OUT } from './toneMap'; +import type { View } from './view'; + +export interface CardBitmaps { + colour: ImageBitmap; + geometry: ImageBitmap; +} + +/** A lit card: its pixels, premultiplied by the card's alpha, at the card's own size, and where the card sits in the plane. */ +export interface LitCard { + canvas: HTMLCanvasElement; + top: number; + h: number; + scale: number; +} + +// Constants of the look, named for the art pass (ratatoskr:follow_up:ridge-art-quality-rework). None of them is a rule of the machine. +/** A real normal has r2 + t2 at most 0.998 (probe on the Vienna bake); the wall code is 2. */ +export const WALL_RT2 = 1.02; +/** A neighbour farther by more than this many nats of distance draws occluding ink on this pixel. */ +export const OCCLUDE_LOGD = 0.35; +/** A normal turning past this cosine between two non-wall pixels draws crease ink. */ +export const CREASE_COS = 0.85; +/** How much each ink keeps of the radiance it falls on (1 = no ink). */ +export const INK_KEEP = { edge: 0.45, occlude: 0.55, crease: 0.8 } as const; +/** The lookup of the sky's radiance for the haze: azimuth columns by plane rows, filtered in the shader. */ +export const SKY_LUT = { w: 64, h: 64 } as const; +/** Below this sun elevation (degrees) no direct sun reaches the ground (the atmosphere's own cut-off, `earthAtmosphere.ts` irradiance). */ +export const SUN_CUTOFF_DEG = -1; + +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 azimuth of plane column `x` of `w` (the card is the whole baked window wide). */ +export const columnAzimuth = (view: View, x: number, w: number): number => + view.lookAzDeg + ((x + 0.5) / w - 0.5) * view.windowDeg; + +/** 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 { + planeW: number; + planeH: number; + logDMin: number; + logDSpan: number; + /** Per km of horizontal path, per channel. */ + extinction: Vec3; + /** The sun's transmittance to the ground, per channel; zero with the sun below the atmosphere's cut-off. */ + sunTransmittance: Vec3; + ambient: Vec3; + exposure: number; + lift: number; +} + +export function lightingOf(manifest: RidgeManifest, sky: PhysicalSky): Lighting { + const trans = [0, 0, 0]; + const sinEl = Math.sin(sky.sun.elevation * RAD); + sky.atm.transmittanceToSpace(Math.max(sinEl, 0), trans); + const lit = sky.sun.elevation > SUN_CUTOFF_DEG; + return { + planeW: manifest.view.planeW, + planeH: manifest.view.planeH, + logDMin: manifest.encoding.logDMin, + logDSpan: manifest.encoding.logDMax - manifest.encoding.logDMin, + extinction: extinctionAt(sky.atm.observerKm, sky.atm.mieScale), + sunTransmittance: lit ? [trans[0], trans[1], trans[2]] : [0, 0, 0], + ambient: sky.atm.irradiance.ambient, + exposure: sky.fit.display.exposure, + lift: sky.fit.display.lift, + }; +} + +/** The sun in every column's frame, RGBA32F texels (a, b, c, 0), one row of `planeW`. */ +export function sunColumns(view: View, sun: { azimuth: number; elevation: number }): Float32Array { + const out = new Float32Array(view.planeW * 4); + for (let x = 0; x < view.planeW; x += 1) { + const [r, t, u] = sunInColumn(sun, columnAzimuth(view, x, view.planeW)); + 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 window'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 = columnAzimuth(view, ((i + 0.5) / w) * view.planeW - 0.5, view.planeW); + sky.atm.radiance(Math.sin(elDeg * RAD), Math.cos((az - sky.sun.azimuth) * 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 vec2 uPlane; +uniform vec2 uLogD; +uniform vec3 uExt; +uniform vec3 uTSun; +uniform vec3 uAmbient; +uniform vec2 uDisplay; +out vec4 outColor; + +const float PI = 3.14159265358979; +const float WALL_RT2 = ${glsl(WALL_RT2)}; +const float OCCLUDE_LOGD = ${glsl(OCCLUDE_LOGD)}; +const float CREASE_COS = ${glsl(CREASE_COS)}; +const vec3 INK_KEEP = vec3(${glsl(INK_KEEP.edge)}, ${glsl(INK_KEEP.occlude)}, ${glsl( + INK_KEEP.crease +)}); +${[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])}); + +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); +} + +vec3 skyAt(vec2 uv) { + vec2 f = uv * vec2(uSkySize) - 0.5; + vec2 b = floor(f); + vec2 t = f - b; + ivec2 lo = clamp(ivec2(b), ivec2(0), uSkySize - 1); + ivec2 hi = clamp(ivec2(b) + 1, ivec2(0), uSkySize - 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); +} + +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); + + vec3 s = texelFetch(uSun, ivec2(p.x, 0), 0).xyz; + vec3 radiance = toLinear(c.rgb) * (uTSun * max(dot(g.n, s), 0.0) + uAmbient) / PI; + vec3 T = exp(-uExt * (exp(g.logD) / 1000.0)); + vec2 uv = vec2((float(p.x) + 0.5) / uPlane.x, (float(uTop + p.y) + 0.5) / uPlane.y); + radiance = radiance * T + skyAt(uv) * (1.0 - T); + + 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, INK_KEEP.x); + else if (an >= 0.5 && gn.logD - g.logD > OCCLUDE_LOGD) keep = min(keep, INK_KEEP.y); + else if (an >= 0.5 && !g.wall && !gn.wall && dot(g.n, gn.n) < CREASE_COS) keep = min(keep, INK_KEEP.z); + } + radiance *= keep; + + vec3 lin = aces(radiance * uDisplay.x); + vec3 rgb = toSrgb(uDisplay.y + (1.0 - uDisplay.y) * lin); + 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; +} + +/** + * Light the cards of `manifest` for `sky`, nearest first, as the manifest lists them. Throws without WebGL2 or when the shader will not link; + * the caller (`loadBackdrop`) turns any throw into the sky alone. Closes the bitmaps, and releases the context after the last card. + */ +export function lightCards( + manifest: RidgeManifest, + bitmaps: CardBitmaps[], + sky: PhysicalSky +): LitCard[] { + 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'); + try { + const lit = lightingOf(manifest, sky); + 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.uniform2f(u('uPlane'), lit.planeW, lit.planeH); + gl.uniform2f(u('uLogD'), lit.logDMin, lit.logDSpan); + gl.uniform3f(u('uExt'), ...lit.extinction); + gl.uniform3f(u('uTSun'), ...lit.sunTransmittance); + gl.uniform3f(u('uAmbient'), ...lit.ambient); + gl.uniform2f(u('uDisplay'), lit.exposure, lit.lift); + gl.uniform2i(u('uSkySize'), SKY_LUT.w, SKY_LUT.h); + const sunTex = floatTexture(gl, 2, lit.planeW, 1, sunColumns(manifest.view, sky.sun)); + const skyTex = floatTexture( + gl, + 3, + SKY_LUT.w, + SKY_LUT.h, + skyLut(sky, manifest.view, SKY_LUT.w, SKY_LUT.h) + ); + const out = manifest.cards.map((card, i): LitCard => { + const { colour, geometry } = bitmaps[i]; + 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'), card.top); + 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 = colour.width; + canvas.height = colour.height; + const ctx = canvas.getContext('2d'); + if (!ctx) throw new Error('ridge: no 2D context for a lit card'); + ctx.drawImage(glCanvas, 0, 0); + gl.deleteTexture(colourTex); + gl.deleteTexture(geoTex); + colour.close(); + geometry.close(); + return { canvas, top: card.top, h: card.h, scale: card.scale }; + }); + gl.deleteTexture(sunTex); + gl.deleteTexture(skyTex); + return out; + } finally { + gl.getExtension('WEBGL_lose_context')?.loseContext(); + } +} diff --git a/src/app/features/scene/ridge/manifest.fixture.ts b/src/app/features/scene/ridge/manifest.fixture.ts index bdfebebb..74a55cb0 100644 --- a/src/app/features/scene/ridge/manifest.fixture.ts +++ b/src/app/features/scene/ridge/manifest.fixture.ts @@ -1,19 +1,16 @@ -// A hand-written manifest v1 and index v1 (wire form, as export.py writes them): the runtime's tests need no real bake and no decoder. -import { FRAME_KEYS } from './manifest'; +// A hand-written manifest v2 and index v1 (wire form, as export.py writes them): the runtime's tests need no real bake and no decoder. import type { View } from './view'; -const SUN: Record = { - dawn: [100, 0], - morning: [130, 20], - noon: [180, 60], - golden: [240, 6], - dusk: [262, -2.5], - night: [0, -12], -}; +/** Card scales of the fixture, nearest first, as the baker derives them for a camera 200 m forward (distances 1.2 km, 12 km, 40 km). */ +const SCALES = [1.2, 1.0167, 1.005] as const; -export const wireManifest = (over: Record = {}): Record => ({ - schema: 1, - baker_version: 1, +/** A v2 manifest of `k` cards (1 to 6), nearest first, each a band of the 600-row plane. */ +export const wireManifest = ( + over: Record = {}, + k = 3 +): Record => ({ + schema: 2, + baker_version: 2, bake_id: 'abc123abc123', place: { id: 'vienna', @@ -21,9 +18,7 @@ export const wireManifest = (over: Record = {}): Record = {}): Record ({ - key, - sun: { az: SUN[key][0], el: SUN[key][1] }, - hour_utc: 0, - planes: Object.fromEntries( - ['far', 'mid', 'near'].map((n) => [ - n, - { file: `${key}-${n}.webp`, bytes: 1, w: 1280, h: 600 }, - ]) - ), - bytes: 3, - luma: { min: 0.1, max: 0.5 }, + curvature: { r_earth_m: 6371000, k_ref: 0.13 }, + encoding: { log_d_min: 4.6, log_d_max: 11.5, normal: 'rt8' }, + camera: { r_m: 200, heading_max_deg: 23 }, + cards: Array.from({ length: k }, (_, i) => ({ + top: 100 * i, + h: 600 - 100 * i, + near_m: i ? 1000 * i : null, + far_m: i < k - 1 ? 1000 * (i + 1) : null, + median_m: 1000 * (i + 1), + distance_m: 1000 * (i + 1), + scale: SCALES[i] ?? 1.001, + colour: { file: `card-${i}-colour.webp`, bytes: 1 }, + geometry: { file: `card-${i}-geometry.webp`, bytes: 1 }, })), + w: 1280, + h: 600, + bytes: 2 * k, attribution: { credit_line: 'credit', licence: 'licence', @@ -72,5 +72,6 @@ export const ELSEWHERE_VIEW: View = { planeW: 1600, planeH: 700, pxPerDegH: 1600 / 90, + pxPerDegV: 100, horizonRow: 250, }; diff --git a/src/app/features/scene/ridge/manifest.test.ts b/src/app/features/scene/ridge/manifest.test.ts index 21444abc..8af79c55 100644 --- a/src/app/features/scene/ridge/manifest.test.ts +++ b/src/app/features/scene/ridge/manifest.test.ts @@ -3,7 +3,7 @@ import { forgetManifests, loadManifest, parseManifest } from './manifest'; import { wireIndex, wireManifest } from './manifest.fixture'; describe('parseManifest', () => { - it('reads a v1 manifest into the View the sky and planes share', () => { + it('reads a v2 manifest into the View the sky and cards share, and K cards nearest first', () => { const m = parseManifest(wireManifest(), '/public/ridge/v/'); expect(m.dir).toBe('/public/ridge/v/'); expect(m.view).toMatchObject({ @@ -11,36 +11,85 @@ describe('parseManifest', () => { windowDeg: 72, planeW: 1280, planeH: 600, - pxPerDegH: 1280 / 72, // not px_per_deg_v (17.7): a real bake's two differ 10x + pxPerDegH: 1280 / 72, + pxPerDegV: 177.8, // not px_per_deg_h: a real bake's two differ 10x horizonRow: 314.5, }); expect(m.view.place).toEqual({ id: 'vienna', lat: 48.19, lon: 16.35, altitudeKm: 0.183 }); - expect(m.frames.map((f) => f.key)).toEqual([ - 'dawn', - 'morning', - 'noon', - 'golden', - 'dusk', - 'night', - ]); - expect(m.frames[2]).toMatchObject({ - sun: { az: 180, el: 60 }, - planes: { far: 'noon-far.webp', near: 'noon-near.webp' }, + expect(m.encoding).toEqual({ logDMin: 4.6, logDMax: 11.5 }); + expect(m.camera).toEqual({ headingMaxDeg: 23 }); + expect(m.cards.map((c) => c.scale)).toEqual([1.2, 1.0167, 1.005]); + expect(m.cards[1]).toEqual({ + top: 100, + h: 500, + scale: 1.0167, + colour: 'card-1-colour.webp', + geometry: 'card-1-geometry.webp', }); expect(m.attribution.creditLine).toBe('credit'); }); - it('rejects a missing field, a wrong schema, a plane wider than 4096 and fewer than 6 frames', () => { + it.each([1, 2, 3, 4, 5, 6])('parses a bake of %i cards', (k) => { + expect(parseManifest(wireManifest({}, k), '/').cards).toHaveLength(k); + }); + + it('keeps only what the runtime reads: no distances, no camera offset', () => { + const m = parseManifest(wireManifest(), '/') as unknown as Record; + expect(JSON.stringify(m)).not.toMatch(/median|near_m|far_m|distance|rM|r_m/); + }); + + it('refuses schema 1, no cards, seven cards, a card past the plane, a scale that is not above 0, a missing camera', () => { + const w = wireManifest() as any; + expect(() => parseManifest({ ...w, schema: 1 }, '/')).toThrow(/schema/); + expect(() => parseManifest({ ...w, cards: [] }, '/')).toThrow(/cards/); + expect(() => parseManifest(wireManifest({}, 7), '/')).toThrow(/cards/); + const card = w.cards[0]; + const withCard = (c: unknown) => ({ ...w, cards: [c] }); + expect(() => parseManifest(withCard({ ...card, top: 300, h: 301 }), '/')).toThrow(/rows/); + expect(() => parseManifest(withCard({ ...card, top: -1 }), '/')).toThrow(/rows/); + expect(() => parseManifest(withCard({ ...card, scale: 0 }), '/')).toThrow(/scale/); + expect(() => parseManifest(withCard({ ...card, scale: -1 }), '/')).toThrow(/scale/); + expect(() => parseManifest(withCard({ ...card, scale: Infinity }), '/')).toThrow(/scale/); + expect(() => parseManifest({ ...w, camera: undefined }, '/')).toThrow(/camera/); + expect(() => parseManifest({ ...w, camera: { heading_max_deg: 0 } }, '/')).toThrow(/heading/); + }); + + it('rejects a missing field, a plane wider than 4096, 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, schema: 2 }, '/')).toThrow(/schema/); expect(() => parseManifest({ ...w, view: { ...w.view, plane_w: 4097 } }, '/')).toThrow(/4096/); - expect(() => parseManifest({ ...w, frames: w.frames.slice(1) }, '/')).toThrow(/frames/); 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('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: { heading_max_deg: 'SECRET-VALUE-42' } }, + { ...w, cards: [{ ...w.cards[0], scale: 'SECRET-VALUE-42' }] }, + ]) { + const msg = refusal(bad); + expect(msg).not.toBe(''); + expect(msg).not.toContain('SECRET-VALUE-42'); + } + }); }); const serve = (files: Record) => { diff --git a/src/app/features/scene/ridge/manifest.ts b/src/app/features/scene/ridge/manifest.ts index a3d0e33e..e2ec9087 100644 --- a/src/app/features/scene/ridge/manifest.ts +++ b/src/app/features/scene/ridge/manifest.ts @@ -1,20 +1,21 @@ // 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 planes share. +// camelCase and its `view` is the View (`view.ts`) the sky and the cards share. Schema 2: K G-buffer cards, nearest first. import type { View } from './view'; -export const FRAME_KEYS = ['dawn', 'morning', 'noon', 'golden', 'dusk', 'night'] as const; -export type FrameKey = typeof FRAME_KEYS[number]; -export const PLANE_NAMES = ['far', 'mid', 'near'] as const; -export type PlaneName = typeof PLANE_NAMES[number]; export const PLANE_W_MAX = 4096; +/** As export.py MAX_CARDS: the decode budget holds this many. */ +export const MAX_CARDS = 6; -export interface Frame { - key: FrameKey; - /** The sun this frame was lit by: degrees. */ - sun: { az: number; el: number }; - /** File names inside the manifest's directory. */ - planes: Record; +/** One G-buffer card: its rows of the plane, how large it sits against the bake, and its two files (names inside the manifest's directory). */ +export interface CardEntry { + /** First row of the card in the plane, and its height in rows. */ + top: number; + h: number; + /** The card's pan rate per unit of heading and its static size, as the baker derived them from the camera and the card's distance (ruling ridge-camera-on-circle). */ + scale: number; + colour: string; + geometry: string; } export interface RidgeManifest { @@ -24,8 +25,12 @@ export interface RidgeManifest { /** Display name of the place. */ name: string; view: View; - /** In `FRAME_KEYS` order. */ - frames: Frame[]; + /** How the geometry card'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 widest heading either side of the look azimuth the baked cards allow, degrees. */ + camera: { headingMaxDeg: number }; + /** Nearest first. */ + cards: CardEntry[]; attribution: { creditLine: string; licence: string; demSource: string; url: string }; } @@ -57,31 +62,39 @@ export function parseIndex(raw: unknown): RidgeIndex { return { default: str(r.default, 'index.default'), places: out }; } -/** `dir` is the URL of the directory the manifest was read from; the planes are read relative to it. */ +/** `dir` is the URL of the directory the manifest was read from; the cards are read relative to it. */ export function parseManifest(raw: unknown, dir: string): RidgeManifest { const r = rec(raw, 'manifest'); - if (r.schema !== 1) fail('schema', 'must be 1'); + if (r.schema !== 2) fail('schema', 'must be 2'); const p = rec(r.place, 'place'); const v = rec(r.view, 'view'); const planeW = num(v.plane_w, 'view.plane_w'); if (planeW > PLANE_W_MAX) fail('view.plane_w', `above ${PLANE_W_MAX}`); - if (!Array.isArray(r.frames) || r.frames.length < FRAME_KEYS.length) - fail('frames', `fewer than ${FRAME_KEYS.length}`); - const frames = FRAME_KEYS.map((key) => { - const f = (r.frames as unknown[]) - .map((x, i) => rec(x, `frames[${i}]`)) - .find((x) => x.key === key); - if (!f) return fail('frames', `no ${key} frame`); - const sun = rec(f.sun, `frames.${key}.sun`); - const planes = rec(f.planes, `frames.${key}.planes`); - const file = (n: PlaneName) => - str(rec(planes[n], `frames.${key}.planes.${n}`).file, `frames.${key}.planes.${n}.file`); + const planeH = num(v.plane_h, 'view.plane_h'); + if (!Array.isArray(r.cards) || r.cards.length < 1) fail('cards', 'none'); + if ((r.cards as unknown[]).length > MAX_CARDS) fail('cards', `more than ${MAX_CARDS}`); + const cards = (r.cards as unknown[]).map((x, i): CardEntry => { + const c = rec(x, `cards[${i}]`); + const top = num(c.top, `cards[${i}].top`); + const h = num(c.h, `cards[${i}].h`); + if (top < 0 || h < 1 || top + h > planeH) fail(`cards[${i}]`, 'outside the plane rows'); + const scale = num(c.scale, `cards[${i}].scale`); + if (!(scale > 0)) fail(`cards[${i}].scale`, 'not above 0'); return { - key, - sun: { az: num(sun.az, `frames.${key}.sun.az`), el: num(sun.el, `frames.${key}.sun.el`) }, - planes: { far: file('far'), mid: file('mid'), near: file('near') }, + top, + h, + scale, + colour: str(rec(c.colour, `cards[${i}].colour`).file, `cards[${i}].colour.file`), + geometry: str(rec(c.geometry, `cards[${i}].geometry`).file, `cards[${i}].geometry.file`), }; }); + 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 headingMaxDeg = num(rec(r.camera, 'camera').heading_max_deg, 'camera.heading_max_deg'); + if (!(headingMaxDeg > 0)) fail('camera.heading_max_deg', 'not above 0'); const a = rec(r.attribution, 'attribution'); const id = str(p.id, 'place.id'); return { @@ -98,11 +111,14 @@ export function parseManifest(raw: unknown, dir: string): RidgeManifest { lookAzDeg: num(v.look_az_deg, 'view.look_az_deg'), windowDeg: num(v.window_deg, 'view.window_deg'), planeW, - planeH: num(v.plane_h, 'view.plane_h'), + 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: num(v.horizon_row, 'view.horizon_row'), }, - frames, + encoding: { logDMin, logDMax }, + camera: { headingMaxDeg }, + cards, attribution: { creditLine: str(a.credit_line, 'attribution.credit_line'), licence: str(a.licence, 'attribution.licence'), diff --git a/src/app/features/scene/ridge/ridgeAssets.test.ts b/src/app/features/scene/ridge/ridgeAssets.test.ts index 96b899b0..aaec06ee 100644 --- a/src/app/features/scene/ridge/ridgeAssets.test.ts +++ b/src/app/features/scene/ridge/ridgeAssets.test.ts @@ -1,54 +1,50 @@ // The committed baked set under public/ridge: what the baker wrote is what ships, within the budget the baker itself refuses on -// (export.py PAIR_BYTES_MAX, DECODE_BYTES_MAX). Reads with node fs. The gate reads each plane'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 manifest's w and h, -// which the decode budget is computed from; and the bake id is re-derived from the plane bytes, as the baker derives it, so any -// corruption of a plane, same length or not, fails. No pixel decoder is in the tree; the baker's own check decodes pixels. +// (export.py MAX_CARDS, TOTAL_BYTES_MAX, DECODE_BYTES_MAX). Reads with node fs. The gate reads each card 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 card's +// width and band height, which the decode budget is computed from; and the bake id is re-derived from the card bytes as the baker derives it, +// so any corruption of a card, same length or not, fails. No pixel decoder is in the tree; the baker's own check decodes pixels. import { createHash } from 'node:crypto'; import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'; -import { join } from 'node:path'; +import { join, sep } from 'node:path'; import { describe, expect, it } from 'vitest'; -import { FRAME_KEYS, PLANE_NAMES, parseIndex, parseManifest } from './manifest'; +import { MAX_CARDS, parseIndex, parseManifest } from './manifest'; -/** The same two constants as scripts/ridge-bake/export.py: two adjacent frames, fetched and decoded. */ -export const PAIR_BYTES_MAX = 800_000; +/** The same constants as scripts/ridge-bake/export.py: every card file of a place, and the cards decoded (2 textures x w x band rows x 4 bytes each). */ +export const TOTAL_BYTES_MAX = 1_500_000; export const DECODE_BYTES_MAX = 20_000_000; -interface WirePlane { +interface WireFile { file: string; bytes: number; - w: number; - h: number; } -interface WireFrame { - key: string; - planes: Record; - luma: { min: number; max: number }; +interface WireCard { + top: number; + h: number; + scale: number; + colour: WireFile; + geometry: WireFile; } export interface WireManifest { bake_id: string; - frames: WireFrame[]; + w: number; + cards: WireCard[]; + camera?: { heading_max_deg?: number }; } -const planes = (f: WireFrame): WirePlane[] => PLANE_NAMES.map((n) => f.planes[n]); +const files = (c: WireCard): WireFile[] => [c.colour, c.geometry]; -/** Why a manifest breaks the size gate, or undefined. Frames are taken in FRAME_KEYS order; the pairs are neighbours, and night meets dawn. */ +/** Why a manifest breaks the size gate, or undefined: too many cards, too many bytes, or too many decoded bytes. */ export function sizeGate(m: WireManifest): string | undefined { - const byKey = FRAME_KEYS.map((k) => m.frames.find((f) => f.key === k) as WireFrame); - for (let i = 0; i < byKey.length; i += 1) { - const pair = [byKey[i], byKey[(i + 1) % byKey.length]]; - const ps = pair.flatMap(planes); - const fetched = ps.reduce((a, p) => a + p.bytes, 0); - const decoded = ps.reduce((a, p) => a + p.w * p.h * 4, 0); - if (fetched > PAIR_BYTES_MAX) return `${pair[0].key}+${pair[1].key} fetches ${fetched}`; - if (decoded > DECODE_BYTES_MAX) return `${pair[0].key}+${pair[1].key} decodes ${decoded}`; - } - return undefined; + if (m.cards.length > MAX_CARDS) return `${m.cards.length} cards, above ${MAX_CARDS}`; + const bytes = m.cards.flatMap(files).reduce((a, f) => a + f.bytes, 0); + if (bytes > TOTAL_BYTES_MAX) return `the cards are ${bytes} bytes, above ${TOTAL_BYTES_MAX}`; + const decoded = m.cards.reduce((a, c) => a + 2 * m.w * c.h * 4, 0); + return decoded > DECODE_BYTES_MAX + ? `the cards decode to ${decoded} bytes, above ${DECODE_BYTES_MAX}` + : undefined; } -/** - * Why a buffer is not a well-formed WebP of `w` x `h`, or undefined. Checks the RIFF envelope (its size is the file's), that the chunks tile - * the file exactly, and the dimensions the container and the bitstream header each state. - */ +/** 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); @@ -89,10 +85,16 @@ export function webpFault(b: Uint8Array, w: number, h: number): string | undefin return bad ? `states ${bad}, the manifest ${w}x${h}` : undefined; } -/** The baker's bake id (export.py `bake_id`): first 12 hex of sha256 over the plane bytes, frames in FRAME_KEYS order, planes far, mid, near. */ -export function bakeIdOf(planeBytes: (frame: string, plane: string) => Uint8Array): string { +/** The baker's bake id (export.py `bake_id`): first 12 hex of sha256 over the card files in index order, colour then geometry. */ +export function bakeIdOf( + cardBytes: (card: number, kind: 'colour' | 'geometry') => Uint8Array, + n: number +): string { const h = createHash('sha256'); - FRAME_KEYS.forEach((k) => PLANE_NAMES.forEach((n) => h.update(planeBytes(k, n)))); + for (let i = 0; i < n; i += 1) { + h.update(cardBytes(i, 'colour')); + h.update(cardBytes(i, 'geometry')); + } return h.digest('hex').slice(0, 12); } @@ -109,121 +111,132 @@ describe('the committed ridge assets', () => { dirs.forEach(([id, dir]) => { describe(`${id} (${dir})`, () => { - const raw = readJson(join(ROOT, dir, 'manifest.json')) as WireManifest; + const raw = readJson(join(ROOT, dir, 'manifest.json')) as WireManifest & { schema: number }; + const read = (f: WireFile) => readFileSync(join(ROOT, dir, f.file)); - it('parses, and its directory ends in its bake id', () => { + it('is schema 2, parses, and its directory ends in its bake id', () => { + expect(raw.schema).toBe(2); expect(() => parseManifest(raw, `${dir}/`)).not.toThrow(); expect(dir.endsWith(`-${raw.bake_id}`)).toBe(true); }); - it('has every plane file, at the length the manifest states', () => { - raw.frames.flatMap(planes).forEach((p) => { - expect(statSync(join(ROOT, dir, p.file)).size, p.file).toBe(p.bytes); + it('has every card file, at the length the manifest states', () => { + raw.cards.flatMap(files).forEach((f) => { + expect(statSync(join(ROOT, dir, f.file)).size, f.file).toBe(f.bytes); }); }); - it('decodes every plane as the WebP of the size the manifest states', () => { - raw.frames.flatMap(planes).forEach((p) => { - expect( - webpFault(readFileSync(join(ROOT, dir, p.file)), p.w, p.h), - p.file - ).toBeUndefined(); - }); + it('decodes every card file as the WebP of the width and band height the manifest states', () => { + raw.cards.forEach((c) => + files(c).forEach((f) => { + expect(webpFault(read(f), raw.w, c.h), f.file).toBeUndefined(); + }) + ); }); it('holds the bytes its bake id was made from', () => { - const bytes = (frame: string, plane: string) => - readFileSync( - join( - ROOT, - dir, - (raw.frames.find((f) => f.key === frame) as WireFrame).planes[plane].file - ) - ); - expect(bakeIdOf(bytes)).toBe(raw.bake_id); + const bytes = (i: number, kind: 'colour' | 'geometry') => read(raw.cards[i][kind]); + expect(bakeIdOf(bytes, raw.cards.length)).toBe(raw.bake_id); }); - it('keeps every adjacent pair of frames inside the fetch and decode budget', () => { + it('keeps the place inside the card, byte and decode budget', () => { expect(sizeGate(raw)).toBeUndefined(); }); - it('records a finite luma for every frame', () => { - expect(raw.frames).toHaveLength(FRAME_KEYS.length); - raw.frames.forEach((f) => { - expect(Number.isFinite(f.luma.min) && Number.isFinite(f.luma.max), f.key).toBe(true); - expect(f.luma.min, f.key).toBeLessThanOrEqual(f.luma.max); - }); + it('carries its camera and a scale for every card', () => { + expect(Number.isFinite(raw.camera?.heading_max_deg)).toBe(true); + raw.cards.forEach((c) => expect(Number.isFinite(c.scale) && c.scale > 0).toBe(true)); }); }); }); + it('shows Vienna from a camera pushed forward: no card is smaller than its bake', () => { + const vienna = index.places.vienna; + expect(vienna).toBeDefined(); + const m = readJson(join(ROOT, vienna, 'manifest.json')) as WireManifest; + m.cards.forEach((c) => expect(c.scale).toBeGreaterThanOrEqual(1)); + }); + 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).frames - .flatMap(planes) - .forEach((p) => named.add(`${dir}/${p.file}`)); + (readJson(join(ROOT, dir, 'manifest.json')) as WireManifest).cards + .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)); + .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 plane gates refuse a plane that is not what the manifest says', () => { - const real = readFileSync(join(ROOT, Object.values(index.places)[0], 'noon-mid.webp')); - const manifest = readJson( - join(ROOT, Object.values(index.places)[0], 'manifest.json') - ) as WireManifest; - const { w, h } = manifest.frames[2].planes.mid; - const id = (b: Uint8Array) => bakeIdOf(() => b); +describe('the card gates refuse a card 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 real = readFileSync(join(ROOT, dir, manifest.cards[1].geometry.file)); + const { h } = manifest.cards[1]; + const w = manifest.w; + const id = (b: Uint8Array) => bakeIdOf(() => b, 1); - it('accepts the real plane at its size', () => { + it('accepts the real card at its size', () => { expect(webpFault(real, w, h)).toBeUndefined(); }); - it("refuses a manifest that lies about the plane's size, and a file cut short or padded", () => { + it("refuses a manifest that lies about the card's size, and a file cut short or padded", () => { expect(webpFault(real, w, h + 1)).toMatch(/states/); expect(webpFault(real.subarray(0, real.length - 1), w, h)).toBeDefined(); expect(webpFault(Buffer.concat([real, Buffer.from([0])]), w, h)).toBeDefined(); }); - it('refuses a frame header whose dimensions are changed, and bytes that are not a WebP', () => { - const vp8 = Buffer.from(real); - const at = vp8.indexOf('VP8 ') + 8 + 6; - vp8[at] ^= 0x01; - expect(webpFault(vp8, w, h)).toMatch(/states/); + 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 plane with the same length and 8 bytes overwritten', () => { + it('re-derives a different bake id from a card 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(id(bad)).not.toBe(id(real)); }); + it('derives the id from colour then geometry, in card order', () => { + const a = Buffer.from('a-colour'); + const b = Buffer.from('b-geometry'); + const order = (c: number, k: 'colour' | 'geometry') => (c === 0 && k === 'colour' ? a : b); + const swapped = (c: number, k: 'colour' | 'geometry') => (c === 0 && k === 'colour' ? b : a); + const want = createHash('sha256').update(a).update(b).update(b).update(b); + expect(bakeIdOf(order, 2)).toBe(want.digest('hex').slice(0, 12)); + expect(bakeIdOf(swapped, 2)).not.toBe(bakeIdOf(order, 2)); + }); }); describe('sizeGate', () => { - const plane = (bytes: number): WirePlane => ({ file: 'x.webp', bytes, w: 1280, h: 600 }); - const frame = (key: string, bytes: number): WireFrame => ({ - key, - planes: { far: plane(bytes), mid: plane(bytes), near: plane(bytes) }, - luma: { min: 0, max: 1 }, + const card = (bytes: number, h: number): WireCard => ({ + top: 0, + h, + scale: 1, + colour: { file: 'c.webp', bytes }, + geometry: { file: 'g.webp', bytes }, }); - const set = (bytes: number): WireManifest => ({ + const set = (n: number, bytes: number, h: number): WireManifest => ({ bake_id: 'x', - frames: FRAME_KEYS.map((k) => frame(k, bytes)), + w: 1280, + cards: Array.from({ length: n }, () => card(bytes, h)), }); - it('passes a pair at the budget and fails a 900 KB pair', () => { - expect(sizeGate(set(133_333))).toBeUndefined(); - expect(sizeGate(set(150_000))).toMatch(/fetches 900000/); + it('passes a place at the byte budget and fails one a byte over', () => { + expect(sizeGate(set(3, 250_000, 100))).toBeUndefined(); + expect(sizeGate(set(3, 250_001, 100))).toMatch(/1500006 bytes/); }); - it('fails a pair that decodes past the budget', () => { - const m = set(1); - m.frames[2].planes.far = { file: 'x.webp', bytes: 1, w: 4096, h: 1000 }; - expect(sizeGate(m)).toMatch(/decodes/); + it('fails a seventh card, and cards that decode past the budget', () => { + expect(sizeGate(set(6, 1, 150))).toBeUndefined(); + expect(sizeGate(set(7, 1, 150))).toMatch(/7 cards/); + expect(sizeGate(set(2, 1, 600))).toBeUndefined(); + expect(sizeGate(set(4, 1, 600))).toMatch(/decode/); }); }); diff --git a/src/app/features/scene/ridge/toneMap.ts b/src/app/features/scene/ridge/toneMap.ts index 90f9fbc4..d8a07cb6 100644 --- a/src/app/features/scene/ridge/toneMap.ts +++ b/src/app/features/scene/ridge/toneMap.ts @@ -10,18 +10,20 @@ import type { FixedSkyState } from '../skyState'; 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 +34,14 @@ 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]) + ); } /** The 8-bit sRGB of linear radiance, exposed and tone-mapped. */ diff --git a/src/app/features/scene/ridge/view.test.ts b/src/app/features/scene/ridge/view.test.ts index 08fd5552..a78b6da2 100644 --- a/src/app/features/scene/ridge/view.test.ts +++ b/src/app/features/scene/ridge/view.test.ts @@ -1,6 +1,8 @@ import { describe, expect, it } from 'vitest'; import { sunOnScreen } from './skyDome'; -import { DRIFT_FRAC, FALLBACK_VIEW, windowFor } from './view'; +import { cardMotion, DRIFT_FRAC, FALLBACK_VIEW, windowFor } from './view'; +import { parseManifest } from './manifest'; +import { wireManifest } from './manifest.fixture'; import type { View } from './view'; const VIEWPORTS: [number, number][] = [ @@ -10,23 +12,32 @@ const VIEWPORTS: [number, number][] = [ ]; describe('windowFor', () => { - it.each(VIEWPORTS)('%i x %i: the planes cover the viewport, the camera sees only baked sky, the horizon is the plane\'s', (w, h) => { - const v = FALLBACK_VIEW; - const win = windowFor(v, w, h); - expect(win.driftPx).toBeGreaterThanOrEqual(0); - expect(win.plane.w - 2 * win.driftPx).toBeCloseTo(w, 6); - expect(win.plane.h).toBeLessThanOrEqual(h * 4); // sanity: scale is not runaway - // Angle seen never exceeds the baked window minus the drift margin on both sides. - expect(win.camera.hfovDeg).toBeLessThanOrEqual(v.windowDeg / (1 + 2 * DRIFT_FRAC) + 1e-9); - // The plane is anchored to the bottom; its horizon row lands at the camera's horizon fraction of the viewport. - 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 - }); + it.each(VIEWPORTS)( + "%i x %i: the planes cover the viewport, the camera sees only baked sky, the horizon is the plane's", + (w, h) => { + const v = FALLBACK_VIEW; + const win = windowFor(v, w, h); + expect(win.driftPx).toBeGreaterThanOrEqual(0); + expect(win.plane.w - 2 * win.driftPx).toBeCloseTo(w, 6); + expect(win.plane.h).toBeLessThanOrEqual(h * 4); // sanity: scale is not runaway + // Angle seen never exceeds the baked window minus the drift margin on both sides. + expect(win.camera.hfovDeg).toBeLessThanOrEqual(v.windowDeg / (1 + 2 * DRIFT_FRAC) + 1e-9); + // The plane is anchored to the bottom; its horizon row lands at the camera's horizon fraction of the viewport. + 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 + } + ); it('is shaped by the View alone: another window, plane and horizon give another camera', () => { - const wide: View = { ...FALLBACK_VIEW, lookAzDeg: 10, windowDeg: 144, planeW: 2560, horizonRow: 200 }; + const wide: View = { + ...FALLBACK_VIEW, + lookAzDeg: 10, + windowDeg: 144, + planeW: 2560, + horizonRow: 200, + }; const a = windowFor(FALLBACK_VIEW, 1920, 1080).camera; const b = windowFor(wide, 1920, 1080).camera; expect(b.azimuthDeg).toBe(10); @@ -58,3 +69,54 @@ describe('windowFor', () => { expect(windowFor(FALLBACK_VIEW, 1280, 720).camera.azimuthDeg).toBe(FALLBACK_VIEW.lookAzDeg); }); }); + +describe('cardMotion', () => { + const manifest = parseManifest(wireManifest(), '/d/'); // scales 1.2, 1.0167, 1.005; heading range 23 deg; 1280 px plane, 17.78 px per degree + const motion = (w: number, h: number) => cardMotion(manifest, windowFor(manifest.view, w, h)); + + it('turns the whole baked range on a phone and is capped by coverage on a wide screen', () => { + expect(motion(390, 844).headingDeg).toBe(23); + expect(motion(1920, 1080).headingDeg).toBeCloseTo(3.4, 1); + expect(motion(768, 1024).headingDeg).toBeLessThan(23); + expect(motion(768, 1024).headingDeg).toBeGreaterThan(motion(1920, 1080).headingDeg); + }); + + it.each([ + [390, 844], + [768, 1024], + [1920, 1080], + [3440, 1440], + ])( + '%i x %i: every card still covers the viewport at the end of the drift, and the cap is exact for the card that gives out first', + (w, h) => { + const win = windowFor(manifest.view, w, h); + const { headingDeg } = cardMotion(manifest, win); + const half = w / 2 / win.plane.scale; + const slack = manifest.cards.map( + (c) => manifest.view.planeW / 2 - half / c.scale - headingDeg * manifest.view.pxPerDegH + ); + slack.forEach((s) => expect(s).toBeGreaterThanOrEqual(-1e-6)); + if (headingDeg < manifest.camera.headingMaxDeg) expect(Math.min(...slack)).toBeCloseTo(0, 6); + } + ); + + it('pans card i by scale_i x heading and keeps the scales the manifest gave', () => { + const win = windowFor(manifest.view, 390, 844); + const m = cardMotion(manifest, win); + expect(m.cards.map((c) => c.scale)).toEqual([1.2, 1.0167, 1.005]); + m.cards.forEach((c) => + expect(c.reachPx).toBeCloseTo(c.scale * 23 * manifest.view.pxPerDegH * win.plane.scale, 6) + ); + // The nearer a card, the faster it pans. + expect(m.cards[0].reachPx).toBeGreaterThan(m.cards[1].reachPx); + expect(m.cards[1].reachPx).toBeGreaterThan(m.cards[2].reachPx); + }); + + it('a wider baker range moves a phone further, a narrower one less', () => { + const win = windowFor(manifest.view, 390, 844); + const at = (deg: number) => cardMotion({ ...manifest, camera: { headingMaxDeg: deg } }, win); + expect(at(10).headingDeg).toBe(10); + expect(at(40).headingDeg).toBeLessThan(40); // the phone's coverage gives out first + expect(at(10).cards[0].reachPx).toBeLessThan(at(20).cards[0].reachPx); + }); +}); diff --git a/src/app/features/scene/ridge/view.ts b/src/app/features/scene/ridge/view.ts index fef44b36..4042cdd7 100644 --- a/src/app/features/scene/ridge/view.ts +++ b/src/app/features/scene/ridge/view.ts @@ -1,5 +1,5 @@ -// The one View: where the sky's camera stands and looks, and where the ridge planes sit against it. A baked place's manifest -// (`view` and `place`, manifest v1) is a View; a sky with no planes uses FALLBACK_VIEW. `windowFor` is the single owner of the +// 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 v2) 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. Nothing else // chooses a field of view, a horizon row or an azimuth. @@ -20,6 +20,8 @@ export interface ManifestView { planeW: 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; } @@ -41,7 +43,7 @@ export interface Camera { horizonAt: number; } -/** The sky of a scene with no planes (a failed load): Vienna facing south-west, with the numbers of the six-key Vienna bake. */ +/** The sky of a scene with no planes (a failed load): Vienna facing south-west, with the numbers of the Vienna bake. */ export const FALLBACK_VIEW: View = { place: { id: 'vienna', lat: 48.1929826, lon: 16.3534237, altitudeKm: 0.183 }, lookAzDeg: 214, @@ -49,6 +51,7 @@ export const FALLBACK_VIEW: View = { planeW: 1280, planeH: 600, pxPerDegH: 1280 / 72, + pxPerDegV: 177.8, horizonRow: 314.5, }; @@ -81,3 +84,38 @@ export function windowFor(view: View, viewportW: number, viewportH: number): Win driftPx: (scale * view.planeW - viewportW) / 2, }; } + +/** What `cardMotion` reads of a manifest: the cards' scales, the baker's heading range and the View. */ +interface CardRig { + view: View; + camera: { headingMaxDeg: number }; + cards: readonly { scale: number }[]; +} + +export interface CardMotion { + /** The heading either side of the look azimuth the drift turns through, degrees. */ + headingDeg: number; + /** Per card, in manifest order (nearest first): the static scale the baker derived and how far it pans, in viewport px, at the end of the drift. */ + cards: { scale: number; reachPx: number }[]; +} + +/** + * Where each card goes on a viewport: the single owner of pan reach and heading range (ruling ridge-camera-on-circle). The heading is the baker's + * `headingMaxDeg` unless a card could no longer cover the viewport at it, so it is capped by the card that would uncover first: card i is `scale` times + * wider on screen, and shown at heading delta d it needs `half viewport / scale + d x pxPerDegH` of its half width. Card i pans `scale` x heading x + * `pxPerDegH` plane pixels, at the plane's scale. One scale per card on both axes; nothing is reprojected inside a card (ruling ridge-cards-per-card-slide). + */ +export function cardMotion(m: CardRig, win: Window): CardMotion { + const half = (win.plane.w - 2 * win.driftPx) / (2 * win.plane.scale); // half the viewport, in plane px + const cap = Math.min( + ...m.cards.map((c) => (m.view.planeW / 2 - half / c.scale) / m.view.pxPerDegH) + ); + const headingDeg = Math.max(0, Math.min(m.camera.headingMaxDeg, cap)); + return { + headingDeg, + cards: m.cards.map((c) => ({ + scale: c.scale, + reachPx: c.scale * headingDeg * m.view.pxPerDegH * win.plane.scale, + })), + }; +} diff --git a/src/app/features/scene/tier.ts b/src/app/features/scene/tier.ts index a7e9ad4a..0f1c96be 100644 --- a/src/app/features/scene/tier.ts +++ b/src/app/features/scene/tier.ts @@ -16,7 +16,7 @@ export interface Capabilities { } /** - * 'ridge': baked parallax ridges, no WebGL (default). 'raymarch': the sphere-traced world with its tree and + * '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';