ridge-bake: planes export (relight_planes, export.py, manifest schema)

relight_planes splits the opaque relight into three straight-alpha planes
by the affine-haze trick; the premultiplied colour is made exact over the
reference haze per channel (a scalar alpha alone drifts 34/255 on the far
plane, because the haze share differs per channel).  export.py bakes a
place, writes WebP planes, manifest.json and index.json under a budget.

Tests: the straight-alpha test compared a hazy body with a few solid ink
pixels (fixture, not code); the rebake fixture replaced a plane with one
that had no solid pixel; an everywhere-opaque plane decodes as RGB, now
read back as RGBA.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Nibu 2026-11-14 01:03:57 +00:00
commit 52c1fb674c
4 changed files with 629 additions and 2 deletions

View file

@ -0,0 +1,171 @@
"""Ridge backdrop export: bake a place with ridge.py and write its three WebP planes per sun key, a manifest and the index.
python3 -I scripts/ridge-bake/export.py <place-id> --tiles DIR --out public/ridge/ [--work DIR] [--sheet contact.png]
python3 -I scripts/ridge-bake/export.py --write-schema (rewrites ridge-bake.schema.json from SCHEMA below)
The runtime reads manifest.json (SCHEMA is its contract) and nothing else about the bake. The 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 datetime import datetime, timezone, timedelta
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import numpy as np, imagecodecs
import sun
BAKER_VERSION = 1
KEYS = ('dawn', 'morning', 'noon', 'golden', 'dusk', 'night')
PLANES = ('far', 'mid', 'near')
NIGHT_EL = -12.0 # the night frame: sun this far below the horizon
WINDOW_DEG = 72
PLANE_W = 1280 # every plane is the whole 72 deg window
PLANE_W_MAX = 4096
PAIR_BYTES_MAX = 800_000 # two adjacent frames (the runtime's worst case) together; the same number is a CI constant in cut-ridge-ad-gates
DECODE_BYTES_MAX = 20_000_000 # the six planes of a frame pair decoded (2 x 3 x w x h x 4 bytes = 18.4 MB at the full window)
WEBP_QUALITY = 80
SOLID = 250 # alpha (0..255) that counts as a solid pixel for the luma probe
SHEET_SKY = (0.80, 0.86, 0.94) # the flat sky of the contact sheet
ATTRIBUTION = dict(
credit_line='Contains modified Copernicus data: DEM © DLR e.V. 2010-2014 and © Airbus Defence and Space GmbH 2014-2018 provided under COPERNICUS by the European Union and ESA; all rights reserved.',
licence='Copernicus DEM licence: free, full and open access, with the credit line shown',
dem_source='Copernicus DEM GLO-30 (30 m)',
url='https://spacedata.copernicus.eu/collections/copernicus-digital-elevation-model')
# ------------------------------------------------------------------------------------ schema (the one dict the schema file and the validator both come from)
_num, _int, _str = {'type': 'number'}, {'type': 'integer'}, {'type': 'string'}
def _obj(**props): return {'type': 'object', 'required': list(props), 'additionalProperties': False, 'properties': props}
_plane = _obj(file=_str, bytes=_int, w=_int, h=_int)
SCHEMA = {'$schema': 'https://json-schema.org/draft/2020-12/schema', 'title': 'ridge-bake manifest v1 and index v1', '$defs': {
'manifest': _obj(schema={'const': 1}, baker_version=_int, bake_id=_str,
place=_obj(id=_str, name=_str, lat=_num, lon=_num, altitude_km=_num, tz_h=_num, tz_name=_str, date=_str),
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, horizon_row=_num, sky_row=_num, near_row=_num),
frames={'type': 'array', 'minItems': len(KEYS), 'maxItems': len(KEYS), 'items': _obj(key={'enum': list(KEYS)}, sun=_obj(az=_num, el=_num), hour_utc=_num, planes=_obj(**{k: _plane for k in PLANES}), bytes=_int, luma=_obj(min=_num, max=_num))},
attribution=_obj(credit_line=_str, licence=_str, dem_source=_str, url=_str)),
'index': _obj(schema={'const': 1}, default=_str, places={'type': 'object', 'additionalProperties': _str})}}
def validate(x, s, path='$'):
"""The subset of JSON Schema SCHEMA uses; raises ValueError naming the path."""
if '$ref' in s: return validate(x, SCHEMA['$defs'][s['$ref'].split('/')[-1]], path)
ty = s.get('type'); py = {'object': dict, 'array': list, 'string': str, 'number': (int, float), 'integer': int}
if ty and (not isinstance(x, py[ty]) or isinstance(x, bool)): raise ValueError(f'{path}: not a {ty}')
if 'const' in s and x != s['const']: raise ValueError(f"{path}: must be {s['const']!r}")
if 'enum' in s and x not in s['enum']: raise ValueError(f'{path}: not one of {s["enum"]}')
if 'maximum' in s and x > s['maximum']: raise ValueError(f'{path}: above {s["maximum"]}')
if ty == 'array':
if not s.get('minItems', 0) <= len(x) <= s.get('maxItems', 1 << 30): raise ValueError(f'{path}: wrong length')
for i, v in enumerate(x): validate(v, s['items'], f'{path}[{i}]')
if ty == 'object':
props = s.get('properties', {}); extra = s.get('additionalProperties', True)
for k in s.get('required', []):
if k not in x: raise ValueError(f'{path}: missing {k}')
for k, v in x.items():
if k in props: validate(v, props[k], f'{path}.{k}')
elif extra is False: raise ValueError(f'{path}: extra key {k}')
elif isinstance(extra, dict): validate(v, extra, f'{path}.{k}')
# ------------------------------------------------------------------------------------ sun keys
def sun_set(p, date):
"""The five day keys from the preset date (copied from the mockup's run2.sun_set) plus the night key at NIGHT_EL: key -> {az, el, hour_utc}."""
day = datetime.fromisoformat(date).replace(tzinfo=timezone.utc); lat, lon, tz = p['lat'], p['lon'], p['tz_h']
geo = lambda t: sun.solar(day + timedelta(hours=t), lat, lon)[2]
def find(target, a, b):
fa = geo(a) - target
for _ in range(50):
m = (a + b) / 2; fm = geo(m) - target
if (fa < 0) == (fm < 0): a, fa = m, fm
else: b = m
return (a + b) / 2
noon = max((12 - lon / 15.0 - 1 + x / 600 for x in range(0, 1200)), key=lambda t: sun.solar(day + timedelta(hours=t), lat, lon)[1])
rise = find(-0.833, noon - 9, noon)
hours = dict(dawn=rise + 0.25, morning=9.5 - tz, noon=noon, golden=find(6.0, noon, noon + 9), dusk=find(-2.5, noon, noon + 9), night=find(NIGHT_EL, noon, noon + 14))
return {k: dict(az=sun.solar(day + timedelta(hours=h), lat, lon)[0], el=sun.solar(day + timedelta(hours=h), lat, lon)[1], hour_utc=h) for k, h in hours.items()}
# ------------------------------------------------------------------------------------ planes -> bytes
def u8(plane): return np.clip(np.rint(plane * 255.0), 0, 255).astype(np.uint8)
def encode(plane): return bytes(imagecodecs.webp_encode(u8(plane), level=WEBP_QUALITY, lossless=False))
def decode(b):
"""A plane's bytes as RGBA uint8; the codec returns RGB for a plane that is opaque everywhere, which is solid."""
a = imagecodecs.webp_decode(b)
return a if a.shape[-1] == 4 else np.concatenate([a, np.full(a.shape[:2] + (1,), 255, np.uint8)], -1)
def luma_range(decoded):
"""WCAG relative luminance (linear 0..1) of the sRGB colour of every solid pixel (alpha >= SOLID) over the planes together: (min, max)."""
lo, hi = 1.0, 0.0
for a in decoded:
m = a[..., 3] >= SOLID
if not m.any(): continue
c = a[..., :3][m].astype(np.float64) / 255.0; lin = np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4); y = lin @ np.array([0.2126, 0.7152, 0.0722])
lo, hi = min(lo, float(y.min())), max(hi, float(y.max()))
if hi < lo: raise ValueError('a frame has no solid pixel to measure')
return lo, hi
def check_budget(frame_bytes, plane_w, plane_h):
"""Refuse a bake the runtime could not hold: any two adjacent frames above PAIR_BYTES_MAX, or the planes of a frame pair decoding above DECODE_BYTES_MAX."""
if plane_w > PLANE_W_MAX: raise ValueError(f'plane width {plane_w} above {PLANE_W_MAX}')
for i in range(len(frame_bytes) - 1):
if frame_bytes[i] + frame_bytes[i + 1] > PAIR_BYTES_MAX: raise ValueError(f'frames {KEYS[i]} + {KEYS[i + 1]} are {frame_bytes[i] + frame_bytes[i + 1]} bytes, above {PAIR_BYTES_MAX}')
decoded = 2 * len(PLANES) * plane_w * plane_h * 4
if decoded > DECODE_BYTES_MAX: raise ValueError(f'a frame pair decodes to {decoded} bytes, above {DECODE_BYTES_MAX}')
def bake_id(frames_webp):
"""First 12 hex of sha256 over the plane bytes in key order, then far, mid, near."""
h = hashlib.sha256()
for k in KEYS:
for n in PLANES: h.update(frames_webp[k][n])
return h.hexdigest()[:12]
def write_bake(out, place, view, suns, frames_webp, default=None):
"""Write out/<place>-<bake_id>/ (planes + manifest.json), rewrite out/index.json, delete the place's previous dir. Refuses over budget before writing. Returns the directory."""
sizes = {k: {n: len(frames_webp[k][n]) for n in PLANES} for k in KEYS}; check_budget([sum(sizes[k].values()) for k in KEYS], PLANE_W, view['plane_h'])
bid = bake_id(frames_webp); name = f"{place['id']}-{bid}"; out = Path(out); out.mkdir(parents=True, exist_ok=True); dest = out / name
frames = []
for k in KEYS:
dec = [decode(frames_webp[k][n]) for n in PLANES]; lo, hi = luma_range(dec)
frames.append(dict(key=k, sun=dict(az=suns[k]['az'], el=suns[k]['el']), hour_utc=suns[k]['hour_utc'],
planes={n: dict(file=f'{k}-{n}.webp', bytes=sizes[k][n], w=PLANE_W, h=view['plane_h']) for n in PLANES}, bytes=sum(sizes[k].values()), luma=dict(min=lo, max=hi)))
manifest = dict(schema=1, baker_version=BAKER_VERSION, bake_id=bid, place=place, view=dict(view, window_deg=WINDOW_DEG, plane_w=PLANE_W), frames=frames, attribution=ATTRIBUTION)
validate(manifest, SCHEMA['$defs']['manifest'])
tmp = Path(tempfile.mkdtemp(dir=out, prefix='.bake-'))
for k in KEYS:
for n in PLANES: (tmp / f'{k}-{n}.webp').write_bytes(frames_webp[k][n])
(tmp / 'manifest.json').write_text(json.dumps(manifest, indent=1) + '\n')
idx_path = out / 'index.json'; idx = json.loads(idx_path.read_text()) if idx_path.exists() else dict(schema=1, default=place['id'], places={})
old = idx['places'].get(place['id']); idx['places'][place['id']] = name; idx['default'] = default or (idx['default'] if idx['default'] in idx['places'] else place['id'])
validate(idx, SCHEMA['$defs']['index'])
if dest.exists(): shutil.rmtree(dest)
os.rename(tmp, dest); (out / '.index.tmp').write_text(json.dumps(idx, indent=1) + '\n'); os.replace(out / '.index.tmp', idx_path)
if old and old != name: shutil.rmtree(out / old, ignore_errors=True)
return dest
# ------------------------------------------------------------------------------------ the bake
def bake_place(pid, relight_keys=KEYS):
"""stage 0, sweep, set_view, bake, then relight_planes for every sun key: (place dict, view dict, suns, {key: {plane: float RGBA}}). Needs RIDGE_TILES / RIDGE_WORK."""
import ridge
assert ridge.WIN == PLANE_W and ridge.H > 0
p = ridge.configure(ridge.load_preset(pid)); ridge.mosaic(p); d, A, Hh, _ = ridge.stage0(False); r = ridge.sweep(d, A, Hh); v = ridge.set_view(r['slots']); layers = ridge.bake(r['slots']); statics = ridge.statics()
suns = sun_set(p, p['date']); planes = {k: ridge.relight_planes(layers, suns[k]['az'], suns[k]['el'], *statics) for k in relight_keys}
place = dict(id=p['id'], name=p['name'], lat=p['lat'], lon=p['lon'], altitude_km=p['ground_m'] / 1000.0, tz_h=p['tz_h'], tz_name=p['tz_name'], date=p['date'])
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'], horizon_row=v['horizon_row'], sky_row=v['sky_row'] * ridge.H, near_row=v['near_row'] * ridge.H)
return place, view, suns, planes
def sheet(planes):
"""Contact sheet: the six frames over one flat sky, 2 columns x 3 rows (png bytes)."""
rows = []
for k in KEYS:
img = np.broadcast_to(np.array(SHEET_SKY), planes[k]['far'].shape[:2] + (3,)).copy()
for n in PLANES: a = planes[k][n]; img = img * (1 - a[..., 3:]) + a[..., :3] * a[..., 3:]
rows.append(img)
grid = np.concatenate([np.concatenate(rows[i:i + 2], 1) for i in range(0, 6, 2)], 0)
return bytes(imagecodecs.png_encode(u8(grid)))
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.split('\n')[0]); ap.add_argument('place', nargs='?'); ap.add_argument('--tiles'); ap.add_argument('--out'); ap.add_argument('--work'); ap.add_argument('--sheet'); ap.add_argument('--write-schema', action='store_true')
a = ap.parse_args(argv)
if a.write_schema: (HERE / 'ridge-bake.schema.json').write_text(json.dumps(SCHEMA, indent=1, ensure_ascii=False) + '\n'); return 0
if not (a.place and a.tiles and a.out): ap.error('place, --tiles and --out are required')
os.environ['RIDGE_TILES'] = a.tiles; os.environ['RIDGE_WORK'] = a.work or os.path.join(os.environ.get('TMPDIR', tempfile.gettempdir()), 'ridge-bake-work'); os.makedirs(os.environ['RIDGE_WORK'], exist_ok=True)
place, view, suns, planes = bake_place(a.place)
if a.sheet: Path(a.sheet).write_bytes(sheet(planes))
dest = write_bake(a.out, place, view, suns, {k: {n: encode(planes[k][n]) for n in PLANES} for k in KEYS})
print(dest); return 0
if __name__ == '__main__': sys.exit(main())

View file

@ -0,0 +1,312 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "ridge-bake manifest v1 and index v1",
"$defs": {
"manifest": {
"type": "object",
"required": [
"schema",
"baker_version",
"bake_id",
"place",
"view",
"frames",
"attribution"
],
"additionalProperties": false,
"properties": {
"schema": {
"const": 1
},
"baker_version": {
"type": "integer"
},
"bake_id": {
"type": "string"
},
"place": {
"type": "object",
"required": [
"id",
"name",
"lat",
"lon",
"altitude_km",
"tz_h",
"tz_name",
"date"
],
"additionalProperties": false,
"properties": {
"id": {
"type": "string"
},
"name": {
"type": "string"
},
"lat": {
"type": "number"
},
"lon": {
"type": "number"
},
"altitude_km": {
"type": "number"
},
"tz_h": {
"type": "number"
},
"tz_name": {
"type": "string"
},
"date": {
"type": "string"
}
}
},
"view": {
"type": "object",
"required": [
"look_az_deg",
"window_deg",
"plane_w",
"plane_h",
"px_per_deg_h",
"px_per_deg_v",
"horizon_row",
"sky_row",
"near_row"
],
"additionalProperties": false,
"properties": {
"look_az_deg": {
"type": "number"
},
"window_deg": {
"const": 72
},
"plane_w": {
"type": "integer",
"maximum": 4096
},
"plane_h": {
"type": "integer"
},
"px_per_deg_h": {
"type": "number"
},
"px_per_deg_v": {
"type": "number"
},
"horizon_row": {
"type": "number"
},
"sky_row": {
"type": "number"
},
"near_row": {
"type": "number"
}
}
},
"frames": {
"type": "array",
"minItems": 6,
"maxItems": 6,
"items": {
"type": "object",
"required": [
"key",
"sun",
"hour_utc",
"planes",
"bytes",
"luma"
],
"additionalProperties": false,
"properties": {
"key": {
"enum": [
"dawn",
"morning",
"noon",
"golden",
"dusk",
"night"
]
},
"sun": {
"type": "object",
"required": [
"az",
"el"
],
"additionalProperties": false,
"properties": {
"az": {
"type": "number"
},
"el": {
"type": "number"
}
}
},
"hour_utc": {
"type": "number"
},
"planes": {
"type": "object",
"required": [
"far",
"mid",
"near"
],
"additionalProperties": false,
"properties": {
"far": {
"type": "object",
"required": [
"file",
"bytes",
"w",
"h"
],
"additionalProperties": false,
"properties": {
"file": {
"type": "string"
},
"bytes": {
"type": "integer"
},
"w": {
"type": "integer"
},
"h": {
"type": "integer"
}
}
},
"mid": {
"type": "object",
"required": [
"file",
"bytes",
"w",
"h"
],
"additionalProperties": false,
"properties": {
"file": {
"type": "string"
},
"bytes": {
"type": "integer"
},
"w": {
"type": "integer"
},
"h": {
"type": "integer"
}
}
},
"near": {
"type": "object",
"required": [
"file",
"bytes",
"w",
"h"
],
"additionalProperties": false,
"properties": {
"file": {
"type": "string"
},
"bytes": {
"type": "integer"
},
"w": {
"type": "integer"
},
"h": {
"type": "integer"
}
}
}
}
},
"bytes": {
"type": "integer"
},
"luma": {
"type": "object",
"required": [
"min",
"max"
],
"additionalProperties": false,
"properties": {
"min": {
"type": "number"
},
"max": {
"type": "number"
}
}
}
}
}
},
"attribution": {
"type": "object",
"required": [
"credit_line",
"licence",
"dem_source",
"url"
],
"additionalProperties": false,
"properties": {
"credit_line": {
"type": "string"
},
"licence": {
"type": "string"
},
"dem_source": {
"type": "string"
},
"url": {
"type": "string"
}
}
}
}
},
"index": {
"type": "object",
"required": [
"schema",
"default",
"places"
],
"additionalProperties": false,
"properties": {
"schema": {
"const": 1
},
"default": {
"type": "string"
},
"places": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
}
}
}
}

View file

@ -476,9 +476,13 @@ def sky_hz(st, paperf):
img = img + glow[..., None] * (st['sky_sun'] * 0.8 * st['ex_t'])[None, None, :]
return img * paperf[..., None] / 0.93, hz
def relight(layers, az, el, paperf, grain, fmot, shadows=True):
def haze_colour(hz): return hz * (hx('#cdd7e7') / hx('#f5e2c8'))[None, :]
def relight(layers, az, el, paperf, grain, fmot, shadows=True, flat=None):
"""Opaque frame with the sky. `flat` (an RGB triple) replaces the sky and the haze colour by that one colour: the stand-in the planes are compared against."""
st = sun_state(az, el); shs = cast_shadows(layers, az, el) if shadows else [None] * len(layers); sky, hz = sky_hz(st, paperf)
hazec = hz * (hx('#cdd7e7') / hx('#f5e2c8'))[None, :]
hazec = haze_colour(hz)
if flat is not None: hazec = np.broadcast_to(np.asarray(flat, float), (W, 3)); sky = np.broadcast_to(np.asarray(flat, float), sky.shape)
F = floor_img(st, hazec, fmot) * (paperf[..., None] / 0.93)
img = np.where((rowang >= 0)[:, None, None], sky, F).astype(np.float32)
for Ly, sh3 in zip(layers, shs):
@ -486,6 +490,34 @@ def relight(layers, az, el, paperf, grain, fmot, shadows=True):
img = img * (1 - Ly['a'][..., None]) + face * Ly['a'][..., None]
return img * grain[..., None]
def group_slots(n):
"""Plane grouping by slot index: far = slot 0 (+ the floor), near = the last slot, mid = every slot between. Fewer than 3 slots cannot fill three planes."""
if n < 3: raise ValueError(f"a place needs at least 3 layer slots for the far/mid/near planes, this one has {n}")
return dict(far=[0], mid=list(range(1, n - 1)), near=[n - 1])
def relight_planes(layers, az, el, paperf, grain, fmot, shadows=True, ref=None):
"""The frame as three RGBA planes (window columns, float 0..1, straight alpha) with no sky drawn. Every pixel of relight is affine in the haze colour c: out = X + c Y
(the haze enters only as the foot mix and the final Beer-Lambert mix). Render each layer and the floor with c = 0 (X) and c = 1 (X + Y), composite each group over
nothing, and let the haze share become transparency: alpha = coverage - mean(Y), colour = X / alpha. Whatever sky the runtime draws behind then supplies the haze.
The split is exact for one group over a flat sky; stacked planes put a nearer group's haze over the farther ridge instead of over the sky (see the recomposite test for the measured loss)."""
st = sun_state(az, el); shs = cast_shadows(layers, az, el) if shadows else [None] * len(layers); out = {}
below = (rowang < 0)[:, None]; k = (paperf[..., None] / 0.93); runs = []
ref = haze_colour(sky_hz(st, paperf)[1]) if ref is None else np.broadcast_to(np.asarray(ref, float), (W, 3)); ref_w = win(ref[None].astype(np.float32))[0]
for c in (0.0, 1.0):
hc = np.full((W, 3), c, np.float32); F = (floor_img(st, hc, fmot) * k).astype(np.float32)
runs.append((F, [relight_layer(Ly, st, hc, F, sh3) * k for Ly, sh3 in zip(layers, shs)]))
for name, idx in group_slots(len(layers)).items():
img = [np.where(below[..., None], r[0], 0.0) if name == 'far' else np.zeros_like(r[0]) for r in runs]; cov = np.broadcast_to(below, (H, W)).astype(np.float32) if name == 'far' else np.zeros((H, W), np.float32)
for i in idx:
a = layers[i]['a'][..., None]
for j in (0, 1): img[j] = img[j] * (1 - a) + runs[j][1][i] * a
cov = cov * (1 - a[..., 0]) + a[..., 0]
X = win(img[0]); Yc = win(img[1] - img[0]); Y = Yc.mean(-1); alpha = np.clip(win(cov) - Y, 0, 1)
P = X + ref_w[None] * (Yc - Y[..., None]) # premultiplied colour: exact over the reference haze, per channel
col = np.where(alpha[..., None] > 1e-4, P / np.maximum(alpha, 1e-4)[..., None], 0.0) * win(grain)[..., None]
out[name] = np.concatenate([np.clip(col, 0, 1), alpha[..., None]], -1).astype(np.float32)
return out
def statics():
paperf = 0.93 + 0.09 * (0.5 * pn2(2, 11) + 0.3 * pn2(9, 12) + 0.2 * pn2(40, 13)) + 0.03 * (pn2(1, 14) - .5)
return paperf, 0.95 + 0.07 * pn2(1, 900), 0.88 + 0.2 * (0.6 * pn2(30, 810) + 0.4 * pn2(7, 811))

View file

@ -373,6 +373,118 @@ def test_paths_come_from_the_environment_with_no_default():
e = dict(env); e.update({'RIDGE_WORK': '.', 'RIDGE_TILES': '.'}); del e[var]
r = subprocess.run([sys.executable, '-I', '-c', 'import sys; sys.path.insert(0, %r); import ridge' % SRC], env=e, capture_output=True, text=True); assert r.returncode and var in r.stderr and 'not set' in r.stderr, (var, r.stderr[-200:])
# ---------------------------------------------------------------------------------------- planes export (export.py, ridge.relight_planes)
import export, tempfile, json, shutil
def _three_slot_layers():
"""three blocks at 6, 20 and 50 km in the same azimuth range, each standing above the one before it in angle: three slots"""
blocks = [block(100, 140, 6000, 9000, 300), block(100, 140, 20000, 23000, 900), block(100, 140, 50000, 53000, 2500)]
r, L = _bake_view(terrain(*blocks), 120.0); ridge.P['floor_agl_m'] = 2.0; return r, L # a low floor plane: the nearest rows are solid ground
def _flat_layers(n):
"""n slots, plane-grouping only needs the list length: the real layers of the 3-slot fixture, truncated / repeated"""
r, L = _three_slot_layers(); return [L[i % len(L)] for i in range(n)]
def _statics_flat_grain(): paperf, grain, fmot = ridge.statics(); return paperf, np.ones_like(grain), fmot
def _over(planes, sky):
img = np.broadcast_to(np.array(sky), planes[export.PLANES[0]].shape[:2] + (3,)).copy()
for n in export.PLANES: a = planes[n]; img = img * (1 - a[..., 3:]) + a[..., :3] * a[..., 3:]
return img
def test_the_far_plane_over_a_flat_sky_equals_the_opaque_relight_of_its_group():
"""The affine haze split is exact for one group: the far plane (floor + slot 0) over one flat colour equals relight of slot 0 alone with that colour as sky and haze (grain off, no shadows) within 1/255 mean and 4/255 max.
The planes carry no sky: above the ridge their alpha is 0."""
r, L = _three_slot_layers(); f = _statics_flat_grain(); sun = (200.0, 40.0); sky = export.SHEET_SKY
planes = ridge.relight_planes(L, *sun, *f, shadows=False, ref=sky); img = _over(dict(far=planes['far'], mid=0 * planes['mid'], near=0 * planes['near']), sky)
want = ridge.win(ridge.relight(L[:1], *sun, *f, shadows=False, flat=sky)); d = np.abs(img - want) * 255
assert d.mean() < 1.0 and d.max() < 4.0, ('the far plane over a flat sky differs from its opaque relight', d.mean(), d.max())
assert planes['far'][0, :, 3].max() < 0.01 and planes['near'][0, :, 3].max() < 0.01, 'the top row (sky) is not transparent'
def test_stacked_planes_stay_close_to_the_opaque_relight_on_vienna_noon():
"""Real Vienna bake at noon, three planes over a flat sky vs relight(flat=that sky): the stacking loss (a nearer group's haze veils the farther plane instead of the sky) measured 7/255 mean; the bound is 9, so a split
that loses colour or alpha shows. The spec's 2/255 pin is not reachable with this trick (reported as a deviation)."""
saved = ridge.P; ridge.configure(ridge.load_preset('vienna')); d, A, Hh, _ = ridge.stage0(False); r = ridge.sweep(d, A, Hh); ridge.set_view(r['slots']); L = ridge.bake(r['slots']); f = _statics_flat_grain()
sun = export.sun_set(ridge.P, ridge.P['date'])['noon']; sky = export.SHEET_SKY; planes = ridge.relight_planes(L, sun['az'], sun['el'], *f, shadows=False, ref=sky)
err = np.abs(_over(planes, sky) - ridge.win(ridge.relight(L, sun['az'], sun['el'], *f, shadows=False, flat=sky))).mean() * 255; ridge.P = saved
assert err < 9.0, ('stacked planes drift from the opaque relight', err)
def test_plane_grouping_far_mid_near_and_refuses_fewer_than_three_slots():
"""far = slot 0, near = the last slot, mid = every slot between (the union); a 3-slot place fills all three planes; fewer than 3 slots are refused."""
assert ridge.group_slots(3) == dict(far=[0], mid=[1], near=[2]) and ridge.group_slots(6) == dict(far=[0], mid=[1, 2, 3, 4], near=[5])
for n in (0, 1, 2):
try: ridge.group_slots(n)
except ValueError: continue
assert False, ('a place with %d slots was accepted' % n)
r, L = _three_slot_layers(); f = _statics_flat_grain(); pl = ridge.relight_planes(L[:3], 200.0, 40.0, *f, shadows=False)
assert all(pl[n][..., 3].max() > 0.5 for n in export.PLANES), {n: float(pl[n][..., 3].max()) for n in export.PLANES}
try: ridge.relight_planes(L[:2], 200.0, 40.0, *f, shadows=False)
except ValueError: pass
else: assert False, 'a 2-slot place was relit into planes'
def test_straight_alpha_planes_unpremultiply_the_composite():
"""Planes carry straight (un-premultiplied) colour: the mid plane (slot 1, 16 km) and the near plane (slot 2, 5 km) each alone over a flat sky equal the opaque relight of that one slot over the same sky, on the rows
above the horizon (the floor belongs to the far plane). Their bodies are translucent (the haze share is alpha's deficit), so premultiplied colour would be darker by alpha and fail by tens of 1/255. u8() keeps colour and alpha apart."""
a = np.zeros((2, 2, 4), np.float32); a[0, 0] = (0.5, 0.25, 0.75, 0.5); b = export.u8(a); assert tuple(b[0, 0]) == (128, 64, 191, 128) and tuple(b[1, 1]) == (0, 0, 0, 0)
r, L = _three_slot_layers(); f = _statics_flat_grain(); sun = (200.0, 40.0); sky = export.SHEET_SKY; pl = ridge.relight_planes(L, *sun, *f, shadows=False, ref=sky); top = int((ridge.rowang >= 0).sum())
for name, i in (('mid', 1), ('near', 2)):
got = _over({n: (pl[n] if n == name else 0 * pl[n]) for n in export.PLANES}, sky)[:top]; want = ridge.win(ridge.relight(L[i:i + 1], *sun, *f, shadows=False, flat=sky))[:top]
body = pl[name][:top, :, 3] > 0.3; assert body.sum() > 1000 and pl[name][:top, :, 3][body].mean() < 0.97, (name, 'the fixture has no translucent body to test')
d = np.abs(got - want) * 255; assert d.mean() < 0.5 and d.max() < 4.0, (name, 'plane over a flat sky differs from its slot relight: colour is premultiplied or the haze split is wrong', d.mean(), d.max())
def _fixture_bake(out, n_keys=6):
r, L = _three_slot_layers(); f = _statics_flat_grain(); suns = {k: dict(az=100.0 + 20 * i, el=-10.0 + 15 * i, hour_utc=float(i)) for i, k in enumerate(export.KEYS)}
planes = {k: ridge.relight_planes(L, suns[k]['az'], max(suns[k]['el'], 5.0) if k != 'night' else 5.0, *f, shadows=False) for k in export.KEYS}
place = dict(id='synthetic', name='Synthetic', lat=48.0, lon=16.0, altitude_km=0.1, tz_h=2, tz_name='CEST', date='2026-09-23')
view = dict(look_az_deg=120.0, plane_h=ridge.H, px_per_deg_h=ridge.HPX_DEG, px_per_deg_v=ridge.PXDEG_V, horizon_row=100.0, sky_row=24.0, near_row=396.0)
webp = {k: {n: export.encode(planes[k][n]) for n in export.PLANES} for k in export.KEYS}; return place, view, suns, webp
def test_manifest_validates_bake_id_is_deterministic_and_luma_is_recorded():
"""Two bakes of the same input give the same bake_id and bytes; the manifest validates against the schema, planes are the window wide (<= the cap), frame pairs fit the budget, plane paths exist relative to
manifest.json, luma min <= max in 0..1 per frame, the index points at the dir and a rebake replaces the place's old dir."""
d = tempfile.mkdtemp()
try:
place, view, suns, webp = _fixture_bake(d); a = export.write_bake(d + '/a', place, view, suns, webp); b = export.write_bake(d + '/b', place, view, suns, webp)
assert a.name == b.name and a.name == 'synthetic-' + export.bake_id(webp), (a.name, b.name)
m = json.load(open(a / 'manifest.json')); export.validate(m, export.SCHEMA['$defs']['manifest']); assert m['bake_id'] == a.name.split('-')[1] and [f['key'] for f in m['frames']] == list(export.KEYS)
assert m['view']['plane_w'] <= export.PLANE_W_MAX and m['view']['window_deg'] == 72
for f in m['frames']:
assert 0 <= f['luma']['min'] <= f['luma']['max'] <= 1, f['luma']; assert f['bytes'] == sum(p['bytes'] for p in f['planes'].values())
for p in f['planes'].values(): assert (a / p['file']).stat().st_size == p['bytes'] and p['w'] == export.PLANE_W
assert max(m['frames'][i]['bytes'] + m['frames'][i + 1]['bytes'] for i in range(5)) <= export.PAIR_BYTES_MAX
idx = json.load(open(d + '/a/index.json')); export.validate(idx, export.SCHEMA['$defs']['index']); assert idx == dict(schema=1, default='synthetic', places={'synthetic': a.name})
webp2 = {k: dict(v) for k, v in webp.items()}; webp2['noon']['far'] = export.encode(np.full((ridge.H, ridge.WIN, 4), 0.5, np.float32) * np.array([1, 1, 1, 2], np.float32)); c = export.write_bake(d + '/a', place, view, suns, webp2)
assert c.name != a.name and not a.exists() and json.load(open(d + '/a/index.json'))['places']['synthetic'] == c.name, 'the old dir of the place survives a rebake'
bad = json.loads(json.dumps(m)); bad['frames'][0]['extra'] = 1
try: export.validate(bad, export.SCHEMA['$defs']['manifest'])
except ValueError: pass
else: assert False, 'an extra key passed the schema'
committed = json.load(open(os.path.join(SRC, 'ridge-bake.schema.json'))); assert committed == json.loads(json.dumps(export.SCHEMA)), 'ridge-bake.schema.json is stale (export.py --write-schema)'
finally: shutil.rmtree(d)
def test_bake_id_follows_the_plane_bytes_in_order():
"""bake_id = first 12 hex of sha256 over the plane bytes in key order, then far, mid, near: one changed byte in any plane changes it, swapping two planes changes it, and the value equals an independent hash."""
import hashlib
w = {k: {n: bytes([i, j]) * 5 for j, n in enumerate(export.PLANES)} for i, k in enumerate(export.KEYS)}; want = hashlib.sha256(b''.join(w[k][n] for k in export.KEYS for n in ('far', 'mid', 'near'))).hexdigest()[:12]
assert export.bake_id(w) == want
for k in export.KEYS:
v = {kk: dict(vv) for kk, vv in w.items()}; v[k]['near'] = v[k]['near'] + b'x'; assert export.bake_id(v) != want, k
v = {kk: dict(vv) for kk, vv in w.items()}; v[k]['far'], v[k]['mid'] = v[k]['mid'], v[k]['far']; assert export.bake_id(v) != want, k
def test_budget_refuses_a_pair_above_the_cap_and_a_plane_above_the_width():
"""Any two ADJACENT frames above PAIR_BYTES_MAX are refused (a heavy frame next to a light one at the cap passes), as is a plane wider than the cap, and nothing is written."""
cap = export.PAIR_BYTES_MAX; ok = [cap // 2] * 6; export.check_budget(ok, export.PLANE_W, ridge.H)
for i in range(5):
bad = list(ok); bad[i] = cap // 2 + 1; bad[i + 1] = cap // 2 + 1
try: export.check_budget(bad, export.PLANE_W, ridge.H)
except ValueError: pass
else: assert False, ('adjacent pair over the cap accepted', i)
export.check_budget([cap - 1000, 1000, cap - 1000, 1000, cap - 1000, 1000], export.PLANE_W, ridge.H) # non-adjacent heavy frames are fine
try: export.check_budget(ok, export.PLANE_W_MAX + 1, ridge.H)
except ValueError: pass
else: assert False, 'a plane wider than the cap was accepted'
d = tempfile.mkdtemp()
try:
place, view, suns, webp = _fixture_bake(d); fat = {k: dict(v) for k, v in webp.items()}; fat['dusk']['mid'] = b'\0' * cap
try: export.write_bake(d + '/o', place, view, suns, fat)
except ValueError: assert not os.path.exists(d + '/o'), 'a refused bake left files'
else: assert False, 'an over-budget bake was written'
finally: shutil.rmtree(d)
def test_luma_range_reads_a_known_solid_plane_and_ignores_translucent_pixels():
"""Two hand-built planes: a solid mid-grey (sRGB 128 -> linear 0.2158) and a solid white (1.0); a translucent black pixel (alpha 100) is not measured. Reads back to 1e-3."""
a = np.zeros((4, 4, 4), np.uint8); a[..., 3] = 0; a[:2, :, :] = (128, 128, 128, 255); a[2, 0] = (0, 0, 0, 100)
b = np.zeros((4, 4, 4), np.uint8); b[0, 0] = (255, 255, 255, 255)
lo, hi = export.luma_range([a, b]); assert abs(lo - 0.2158) < 1e-3 and abs(hi - 1.0) < 1e-3, (lo, hi)
z = export.decode(export.encode(np.full((8, 8, 4), 1.0, np.float32))); assert z.shape == (8, 8, 4) and (z[..., 3] == 255).all(), 'an everywhere-opaque plane must read back as RGBA'
TESTS = [v for k, v in sorted(globals().items()) if k.startswith('test_')]
if __name__ == '__main__':
fails = 0