ridge-bake: K+1 layered-depth G-buffer cards split by K authored seams; manifest v2
ridge.py: elev (shared by march and prefilter), prefilter, normals, set_view from the march skyline, coverage, seams (one forward-energy DP per authored split), cards (first visible hit at or beyond the near seam, crest coverage, cross-fade over seam +- XF, nested alphas so the composite equals the opaque coverage, cropped to the row band). load_preset requires card_split_km (strictly increasing, at most MAX_CARDS - 1). export.py: manifest v2, two WebPs per card, check_cover, check_budget on count, total bytes and decoded bytes, sheet. places.json: Vienna card_split_km [6, 40], prefilter_m 100. The seam prior is 0.05 rows/nat^2 (tie-break only): at 2.0 the seam hopped across a receding ridge between two columns, which the spec's own side-by-side test forbids. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
568f6c19d3
commit
9bcd7f0db7
5 changed files with 543 additions and 232 deletions
|
|
@ -1,26 +1,27 @@
|
|||
"""Ridge backdrop export: bake a place with ridge.py and write its three WebP planes per sun key, a manifest and the index.
|
||||
"""Ridge backdrop export: bake a place with ridge.py and write its K+1 G-buffer cards (colour + geometry WebP each), a manifest v2 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)."""
|
||||
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)
|
||||
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
|
||||
|
||||
BAKER_VERSION = 1
|
||||
PLANES = ('far', 'mid', 'near')
|
||||
BAKER_VERSION = 2
|
||||
WINDOW_DEG = 72
|
||||
PLANE_W = 1280 # every plane is the whole 72 deg window
|
||||
PLANE_W = 1280 # every card is the whole 72 deg window wide
|
||||
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)
|
||||
MAX_CARDS = 6 # per place; a full-frame card decodes to 2 textures x 1280 x 600 x 4 B = 6.1 MB, the decode budget below holds 3 of them and cropping to the row band is what lets a livelier place have more
|
||||
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
|
||||
WEBP_QUALITY = 80
|
||||
SHEET_SKY = (0.80, 0.86, 0.94) # the flat sky of the contact sheet
|
||||
SHEET_LIGHT = (-0.35, 0.55, 0.76) # the fixed light of the contact sheet in (along ray, across ray, up); the sheet is a look at the cards, the client lights the real thing
|
||||
ATTRIBUTION = dict(
|
||||
credit_line='Contains modified Copernicus data: DEM © DLR e.V. 2010-2014 and © Airbus Defence and Space GmbH 2014-2018 provided under COPERNICUS by the European Union and ESA; all rights reserved.',
|
||||
licence='Copernicus DEM licence: free, full and open access, with the credit line shown',
|
||||
|
|
@ -29,28 +30,33 @@ ATTRIBUTION = dict(
|
|||
|
||||
# ------------------------------------------------------------------------------------ schema (the one dict the schema file and the validator both come from)
|
||||
_num, _int, _str = {'type': 'number'}, {'type': 'integer'}, {'type': 'string'}
|
||||
_numnull = {'type': ['number', 'null']}
|
||||
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=dict(_obj(min=_num, max=_num), description='min and max WCAG relative luminance of the three planes composited far, mid, near over a flat mid-grey sky, over pixels whose composite coverage 1 - prod(1 - alpha) is at least 0.5'))},
|
||||
_file = _obj(file=_str, bytes=_int)
|
||||
SCHEMA = {'$schema': 'https://json-schema.org/draft/2020-12/schema', 'title': 'ridge-bake manifest v2 and index v1', '$defs': {
|
||||
'manifest': _obj(schema={'const': 2}, baker_version=_int, bake_id=_str,
|
||||
place=_obj(id=_str, name=_str, lat=_num, lon=_num, altitude_km=_num, eye_m=_num),
|
||||
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.')},
|
||||
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})}}
|
||||
|
||||
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}')
|
||||
tys = s.get('type'); tys = [tys] if isinstance(tys, str) else tys; py = {'object': dict, 'array': list, 'string': str, 'number': (int, float), 'integer': int, 'null': type(None)}
|
||||
if tys and not any(isinstance(x, py[t]) and not (isinstance(x, bool) and t != 'null') for t in tys): raise ValueError(f'{path}: not a {"/".join(tys)}')
|
||||
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 isinstance(x, list):
|
||||
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':
|
||||
if isinstance(x, dict):
|
||||
props = s.get('properties', {}); extra = s.get('additionalProperties', True)
|
||||
for k in s.get('required', []):
|
||||
if k not in x: raise ValueError(f'{path}: missing {k}')
|
||||
|
|
@ -59,51 +65,60 @@ def validate(x, s, path='$'):
|
|||
elif extra is False: raise ValueError(f'{path}: extra key {k}')
|
||||
elif isinstance(extra, dict): validate(v, extra, f'{path}.{k}')
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------ 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))
|
||||
# ------------------------------------------------------------------------------------ cards -> bytes
|
||||
def u8(a): return np.clip(np.rint(np.asarray(a) * 255.0), 0, 255).astype(np.uint8)
|
||||
def encode_colour(albedo, alpha):
|
||||
"""Lossy RGB albedo with lossless alpha coverage, straight (not premultiplied); the colour under a zero alpha is zeroed."""
|
||||
a = u8(alpha); rgb = u8(albedo) * (a[..., None] > 0); return bytes(imagecodecs.webp_encode(np.dstack([rgb, a]), level=WEBP_QUALITY, lossless=False))
|
||||
def encode_geometry(n_r, n_t, logd, enc):
|
||||
"""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 decode(b):
|
||||
"""A plane's bytes as RGBA uint8; the codec returns RGB for a plane that is opaque everywhere, which is solid."""
|
||||
"""A WebP's bytes as RGBA uint8; the codec returns RGB for an image that is opaque everywhere, which is solid."""
|
||||
a = imagecodecs.webp_decode(b)
|
||||
return a if a.shape[-1] == 4 else np.concatenate([a, np.full(a.shape[:2] + (1,), 255, np.uint8)], -1)
|
||||
|
||||
def check_budget(frame_bytes, plane_w, plane_h):
|
||||
"""Refuse a bake the runtime could not hold: any two adjacent frames (night with dawn too) 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)):
|
||||
j = (i + 1) % len(frame_bytes) # night wraps to dawn, as the runtime's frameChoice and the CI sizeGate pair them
|
||||
if frame_bytes[i] + frame_bytes[j] > PAIR_BYTES_MAX: raise ValueError(f'frames {KEYS[i]} + {KEYS[j]} are {frame_bytes[i] + frame_bytes[j]} 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 composite_alpha(cards, h, w):
|
||||
"""Coverage of the alpha-over of all cards, each (top, rgba uint8 or float alpha (rows, w)) placed at its rows of an h x w frame."""
|
||||
clear = np.ones((h, w))
|
||||
for top, al in cards: clear[top:top + al.shape[0]] *= 1 - np.asarray(al, np.float64)
|
||||
return 1 - clear
|
||||
def check_cover(cards, opaque, tol=COVER_TOL):
|
||||
"""Refuse a bake whose cards, alpha-over, differ from the opaque view's coverage by more than tol anywhere: a hole shows the sky through terrain, an excess is a ghost. cards: [(top, alpha 0..1 (rows, w))], opaque (h, w)."""
|
||||
err = np.abs(composite_alpha(cards, *opaque.shape) - opaque); bad = err > tol
|
||||
if bad.any(): y, x = np.unravel_index(int(np.argmax(err)), err.shape); raise ValueError(f'the cards do not composite to the opaque view within {tol}: {int(bad.sum())} pixels differ, worst {err.max():.3f} at x={x} row {y}')
|
||||
|
||||
def bake_id(frames_webp):
|
||||
"""First 12 hex of sha256 over the plane bytes in key order, then far, mid, near."""
|
||||
def check_budget(card_bytes, w, bands):
|
||||
"""Refuse a bake the runtime could not hold: more than MAX_CARDS cards, a card wider than PLANE_W_MAX, every card file together above TOTAL_BYTES_MAX, or the cards decoding (2 textures x w x band rows x 4 bytes each) above DECODE_BYTES_MAX."""
|
||||
if len(card_bytes) > MAX_CARDS: raise ValueError(f'{len(card_bytes)} cards, above {MAX_CARDS}')
|
||||
if w > PLANE_W_MAX: raise ValueError(f'card width {w} above {PLANE_W_MAX}')
|
||||
if sum(card_bytes) > TOTAL_BYTES_MAX: raise ValueError(f'the cards are {sum(card_bytes)} bytes, above {TOTAL_BYTES_MAX}')
|
||||
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 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()
|
||||
for k in KEYS:
|
||||
for n in PLANES: h.update(frames_webp[k][n])
|
||||
for colour, geometry in cards: h.update(colour); h.update(geometry)
|
||||
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 before writing a bake whose planes are not one size, differ from view plane_h, or exceed the budget measured on the decoded planes. Returns the directory."""
|
||||
sizes = {k: {n: len(frames_webp[k][n]) for n in PLANES} for k in KEYS}; dec = {k: [decode(frames_webp[k][n]) for n in PLANES] for k in KEYS}
|
||||
shapes = {a.shape[:2] for k in KEYS for a in dec[k]}
|
||||
if len(shapes) != 1: raise ValueError(f'the planes are not one size: {sorted(shapes)}')
|
||||
h, w = shapes.pop()
|
||||
if h != view['plane_h']: raise ValueError(f"the planes are {h} rows, the view says {view['plane_h']}")
|
||||
check_budget([sum(sizes[k].values()) for k in KEYS], w, h)
|
||||
for k in KEYS: check_near_cover(dec[k][-1], view['horizon_row'])
|
||||
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:
|
||||
lo, hi = luma_range(dec[k])
|
||||
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=w, h=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=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])
|
||||
def write_bake(out, place, view, meta, cards, opaque, default=None):
|
||||
"""Write out/<place>-<bake_id>/ (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."""
|
||||
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)}')
|
||||
w = dec[0][0].shape[1]; h = view['plane_h']
|
||||
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)
|
||||
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'])))
|
||||
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'])
|
||||
(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'])
|
||||
|
|
@ -114,25 +129,40 @@ def write_bake(out, place, view, suns, frames_webp, default=None):
|
|||
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."""
|
||||
def bake_place(pid):
|
||||
"""stage 0, prefilter, set_view, coverage, seams, cards: dict(place, view, meta, cards (ridge.cards arrays), seams (K, w) in m, cov (bins, w), opaque (h, w) coverage). 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
|
||||
p = ridge.configure(ridge.load_preset(pid)); ridge.mosaic(p); d, _, Hh, _ = ridge.stage0(False); a, h = ridge.prefilter(d, Hh, p.get('prefilter_m', 0)); v = ridge.set_view(a.max(0))
|
||||
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])))
|
||||
return dict(place=place, view=view, meta=meta, cards=ridge.cards(d, aw, hw, sm, nrm), seams=sm, cov=cov, opaque=ridge.opaque(aw), edges=ridge.log_edges(d))
|
||||
|
||||
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 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 = []
|
||||
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))
|
||||
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)
|
||||
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."""
|
||||
h, w = bake['opaque'].shape; sky = np.broadcast_to(np.array(SHEET_SKY), (h, w, 3)); comp = sky.copy(); panels = []
|
||||
for c in bake['cards']:
|
||||
rgb, al = lit(c); alone = sky.copy(); sl = slice(c['top'], c['top'] + al.shape[0]); alone[sl] = sky[sl] * (1 - al[..., None]) + rgb * al[..., None]; panels.append(alone)
|
||||
for c in reversed(bake['cards']): rgb, al = lit(c); sl = slice(c['top'], c['top'] + al.shape[0]); comp[sl] = comp[sl] * (1 - al[..., None]) + rgb * al[..., None]
|
||||
cov = bake['cov']; img = np.repeat(np.log1p(cov[::-1]) / np.log1p(cov.max()), 2, 0); depth = np.dstack([img] * 3) * 0.92 + 0.04; nb = cov.shape[0]; cols = np.arange(w)
|
||||
for k, s in enumerate(bake['seams']):
|
||||
j = np.clip(np.searchsorted(bake['edges'], np.log(s), 'right') - 1, 0, nb - 1); col = [(0.24, 0.78, 1.0), (1.0, 0.47, 0.24), (0.6, 1.0, 0.4), (1.0, 0.9, 0.3), (0.9, 0.4, 1.0)][k % 5]
|
||||
for dy in (0, 1): depth[(nb - 1 - j) * 2 + dy, cols] = col
|
||||
return bytes(imagecodecs.png_encode(u8(np.concatenate([comp] + panels + [depth], 0))))
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(description=__doc__.split('\n')[0]); ap.add_argument('place', nargs='?'); ap.add_argument('--tiles'); ap.add_argument('--out'); ap.add_argument('--work'); ap.add_argument('--sheet'); ap.add_argument('--write-schema', action='store_true')
|
||||
|
|
@ -140,9 +170,9 @@ def main(argv=None):
|
|||
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})
|
||||
bake = bake_place(a.place)
|
||||
if a.sheet: Path(a.sheet).write_bytes(sheet(bake))
|
||||
dest = write_bake(a.out, bake['place'], bake['view'], bake['meta'], pack(bake), bake['opaque'])
|
||||
print(dest); return 0
|
||||
|
||||
if __name__ == '__main__': sys.exit(main())
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
{
|
||||
"_doc": "Place presets for the A+D baker (ridge.py). eye = observer lat/lon; eye_h_m = eye above the local DEM surface (ground_override_m replaces the DEM ground elevation, used for Vienna to keep round 1's 183.3 m); look_at = target lat/lon whose bearing centres the 72 deg window (or az_deg); rmax_km = ring radius (decides the tile list: every 1x1 deg GLO-30 tile whose rectangle intersects the circle).",
|
||||
"_doc": "Place presets for the A+D baker (ridge.py). eye = observer lat/lon; eye_h_m = eye above the local DEM surface (ground_override_m replaces the DEM ground elevation, used for Vienna to keep round 1's 183.3 m); look_at = target lat/lon whose bearing centres the 72 deg window (or az_deg); rmax_km = ring radius (decides the tile list: every 1x1 deg GLO-30 tile whose rectangle intersects the circle); card_split_km = the ordered list of 1 to MAX_CARDS - 1 authored seam depths in km (the seam search refines each per column; K splits make K+1 cards; required, never defaulted); prefilter_m = Gaussian sigma in metres of the height low-pass before the cards are cut (default 0).",
|
||||
"presets": [
|
||||
{
|
||||
"id": "vienna",
|
||||
|
|
@ -11,6 +11,11 @@
|
|||
"ground_override_m": 183.3,
|
||||
"az_deg": 214.0,
|
||||
"rmax_km": 95,
|
||||
"card_split_km": [
|
||||
6,
|
||||
40
|
||||
],
|
||||
"prefilter_m": 100,
|
||||
"viewpoint_source": {
|
||||
"status": "existing observer of the round-1 mockup (the scene camera used by the game), not photo-sourced; eye 30 m above ground as in round 1"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"title": "ridge-bake manifest v1 and index v1",
|
||||
"title": "ridge-bake manifest v2 and index v1",
|
||||
"$defs": {
|
||||
"manifest": {
|
||||
"type": "object",
|
||||
|
|
@ -10,13 +10,18 @@
|
|||
"bake_id",
|
||||
"place",
|
||||
"view",
|
||||
"frames",
|
||||
"curvature",
|
||||
"encoding",
|
||||
"cards",
|
||||
"w",
|
||||
"h",
|
||||
"bytes",
|
||||
"attribution"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"schema": {
|
||||
"const": 1
|
||||
"const": 2
|
||||
},
|
||||
"baker_version": {
|
||||
"type": "integer"
|
||||
|
|
@ -32,9 +37,7 @@
|
|||
"lat",
|
||||
"lon",
|
||||
"altitude_km",
|
||||
"tz_h",
|
||||
"tz_name",
|
||||
"date"
|
||||
"eye_m"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
|
|
@ -53,14 +56,8 @@
|
|||
"altitude_km": {
|
||||
"type": "number"
|
||||
},
|
||||
"tz_h": {
|
||||
"eye_m": {
|
||||
"type": "number"
|
||||
},
|
||||
"tz_name": {
|
||||
"type": "string"
|
||||
},
|
||||
"date": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
|
@ -73,6 +70,7 @@
|
|||
"plane_h",
|
||||
"px_per_deg_h",
|
||||
"px_per_deg_v",
|
||||
"exaggeration",
|
||||
"horizon_row",
|
||||
"sky_row",
|
||||
"near_row"
|
||||
|
|
@ -98,6 +96,9 @@
|
|||
"px_per_deg_v": {
|
||||
"type": "number"
|
||||
},
|
||||
"exaggeration": {
|
||||
"type": "number"
|
||||
},
|
||||
"horizon_row": {
|
||||
"type": "number"
|
||||
},
|
||||
|
|
@ -109,157 +110,125 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"frames": {
|
||||
"curvature": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"r_earth_m",
|
||||
"k_ref"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"r_earth_m": {
|
||||
"type": "number"
|
||||
},
|
||||
"k_ref": {
|
||||
"type": "number"
|
||||
}
|
||||
}
|
||||
},
|
||||
"encoding": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"log_d_min",
|
||||
"log_d_max",
|
||||
"normal"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"log_d_min": {
|
||||
"type": "number"
|
||||
},
|
||||
"log_d_max": {
|
||||
"type": "number"
|
||||
},
|
||||
"normal": {
|
||||
"const": "rt8"
|
||||
}
|
||||
}
|
||||
},
|
||||
"cards": {
|
||||
"type": "array",
|
||||
"minItems": 6,
|
||||
"minItems": 1,
|
||||
"maxItems": 6,
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"key",
|
||||
"sun",
|
||||
"hour_utc",
|
||||
"planes",
|
||||
"bytes",
|
||||
"luma"
|
||||
"top",
|
||||
"h",
|
||||
"near_m",
|
||||
"far_m",
|
||||
"median_m",
|
||||
"colour",
|
||||
"geometry"
|
||||
],
|
||||
"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": {
|
||||
"top": {
|
||||
"type": "integer"
|
||||
},
|
||||
"luma": {
|
||||
"h": {
|
||||
"type": "integer"
|
||||
},
|
||||
"near_m": {
|
||||
"type": [
|
||||
"number",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"far_m": {
|
||||
"type": [
|
||||
"number",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"median_m": {
|
||||
"type": "number"
|
||||
},
|
||||
"colour": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"min",
|
||||
"max"
|
||||
"file",
|
||||
"bytes"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"min": {
|
||||
"type": "number"
|
||||
"file": {
|
||||
"type": "string"
|
||||
},
|
||||
"max": {
|
||||
"type": "number"
|
||||
"bytes": {
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"description": "min and max WCAG relative luminance of the three planes composited far, mid, near over a flat mid-grey sky, over pixels whose composite coverage 1 - prod(1 - alpha) is at least 0.5"
|
||||
}
|
||||
},
|
||||
"geometry": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"file",
|
||||
"bytes"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"file": {
|
||||
"type": "string"
|
||||
},
|
||||
"bytes": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"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."
|
||||
}
|
||||
},
|
||||
"w": {
|
||||
"type": "integer"
|
||||
},
|
||||
"h": {
|
||||
"type": "integer"
|
||||
},
|
||||
"bytes": {
|
||||
"type": "integer"
|
||||
},
|
||||
"attribution": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
|
|
|
|||
|
|
@ -1,13 +1,13 @@
|
|||
"""Round-2 baker: A's painter baked from D's sweep, driven by a place preset from places.json (ray sampling, the round-1 recommendation).
|
||||
"""Ridge baker: the ray march of a place, cut into K+1 layered-depth G-buffer cards by K authored seams (places.json), no painter, no sun.
|
||||
Offline baker for the ridge backdrop (scripts/ridge-bake); export.py drives it.
|
||||
|
||||
load_preset(id) -> configure() : observer, tiles, mosaic origin, ring radius, window azimuth, painter constants from places.json
|
||||
load_preset(id) -> configure() : observer, tiles, mosaic origin, ring radius, window azimuth, card splits and prefilter from places.json
|
||||
stage0(detail) : ray march of all 6400 azimuth columns (curvature+refraction), optional authored sub-DEM foreground detail, cached
|
||||
sweep() : D's per-column scan -> spans (with own height/run = per-peak slope) -> wrapped chains -> 7-knot layer cap
|
||||
set_view(slots) : authored Y mapping: angle -> row, ground plane at the bottom (see set_view)
|
||||
bake(slots) : sun-independent per-layer arrays
|
||||
relight(layers, az, el) : shading + atmosphere + floor + sky
|
||||
Vertical exaggeration is AUTHORED and derived per view by set_view (printed on the page)."""
|
||||
prefilter(d, h, sigma_m) : Gaussian low-pass of the sampled heights (along each ray, across rays at equal distance), angles recomputed with elev
|
||||
set_view(skyline) : authored Y mapping from the march skyline: angle -> row, see set_view
|
||||
coverage(d, a) / seams(cov, ..) : visible rows per log-distance bin; one forward-energy seam per authored split, per column
|
||||
normals(d, h) / cards(...) : per-sample normals; the K+1 cards (coverage, distance, normal, albedo), each cropped to its band of rows
|
||||
Vertical exaggeration is AUTHORED and derived per view by set_view (printed on the page). The client owns lighting, haze and ink (ruling ridge-cards-runtime-lit)."""
|
||||
import sys, time, math, json
|
||||
import os, hashlib
|
||||
from pathlib import Path
|
||||
|
|
@ -31,7 +31,12 @@ P = {} # configured preset
|
|||
rowang = np.zeros(H); PXDEG_V = 100.0; TOP_DEG = 2.6; BOTTOM_DEG = -3.4
|
||||
|
||||
def load_preset(pid, path=Path(__file__).resolve().parent / 'places.json'):
|
||||
d = json.load(open(path)); p = next(x for x in d['presets'] if x['id'] == pid); return dict(p)
|
||||
"""The preset dict. card_split_km is the ordered list of authored seam depths (km): required, strictly increasing, at most export.MAX_CARDS - 1 (the cap is export's, which owns the budget); refused here, before any march."""
|
||||
d = json.load(open(path)); p = dict(next(x for x in d['presets'] if x['id'] == pid)); sp = p.get('card_split_km')
|
||||
from export import MAX_CARDS
|
||||
if not sp: raise ValueError(f"preset {pid}: card_split_km is required (an ordered list of 1 to {MAX_CARDS - 1} depths in km)")
|
||||
if len(sp) > MAX_CARDS - 1 or any(b <= a for a, b in zip(sp, sp[1:])): raise ValueError(f"preset {pid}: card_split_km {sp} must be strictly increasing with at most {MAX_CARDS - 1} entries")
|
||||
return p
|
||||
|
||||
# ====================================================================== configuration, DEM
|
||||
def tiles_for(p):
|
||||
|
|
@ -112,6 +117,11 @@ def schedule(detail):
|
|||
d.append(d[-1] + min(250.0, max(10.0 if detail else 40.0, 0.004 * d[-1])))
|
||||
return np.array(d)
|
||||
|
||||
def elev(h, d, curvature=True):
|
||||
"""Elevation angle (degrees) of height h (m) at distance d (m) from the eye: Earth curvature with refraction. The one formula of march and prefilter."""
|
||||
drop = d * d / (2 * R_EARTH) * (1 - KREF) if curvature else 0.0
|
||||
return np.degrees(np.arctan2(h - P['eye_m'] - drop, d))
|
||||
|
||||
def march(detail=False, curvature=True):
|
||||
m, lt, ll = mosaic(P); az = np.radians((np.arange(W) + 0.5) / W * 360.0); d = schedule(detail); cosl = math.cos(math.radians(P['lat']))
|
||||
A = np.zeros((len(d), W), np.float32); Hh = np.zeros_like(A); sa, ca = np.sin(az), np.cos(az)
|
||||
|
|
@ -119,8 +129,7 @@ def march(detail=False, curvature=True):
|
|||
lat = P['lat'] + dk * ca / 111320.0; lon = P['lon'] + dk * sa / (111320.0 * cosl)
|
||||
h = bil(m, lt, ll, lat, lon)
|
||||
if detail and dk < DETAIL['fade_to_m']: h = h + detail_height(dk * sa, dk * ca, dk)
|
||||
drop = dk * dk / (2 * R_EARTH) * (1 - KREF) if curvature else 0.0
|
||||
A[k] = np.degrees(np.arctan2(h - P['eye_m'] - drop, dk)); Hh[k] = h
|
||||
A[k] = elev(h, dk, curvature); Hh[k] = h
|
||||
return d, A, Hh
|
||||
|
||||
def rays_key(detail):
|
||||
|
|
@ -142,18 +151,116 @@ def blurw(a, s):
|
|||
return o
|
||||
|
||||
|
||||
|
||||
# ====================================================================== prefilter: the march is a heightfield of roofs and hills; the cards want the hills
|
||||
def prefilter(d, h, sigma_m):
|
||||
"""Gaussian low-pass of the ray heights h (K, W): along each ray with sigma sigma_m metres (weighted by sample spacing, the schedule is not uniform), then across rays at equal distance with
|
||||
sigma = sigma_m / (d * COLW) columns (periodic, exact in the Fourier domain). Angles are recomputed from the filtered heights with elev. Returns (angles, heights); sigma_m 0 leaves the heights as they are."""
|
||||
d = np.asarray(d, np.float64); h = np.asarray(h, np.float64)
|
||||
if sigma_m > 0:
|
||||
f = np.fft.rfftfreq(h.shape[1]); sc = sigma_m / (d * COLW)
|
||||
h = np.fft.irfft(np.fft.rfft(h, axis=1) * np.exp(-2 * (np.pi * f[None, :] * sc[:, None]) ** 2), n=h.shape[1], axis=1)
|
||||
dd = np.gradient(d); out = np.empty_like(h)
|
||||
for k in range(len(d)):
|
||||
r = int(min(3 * sigma_m / dd[k] + 1, 60)); lo, hi = max(0, k - r), min(len(d), k + r + 1)
|
||||
w = np.exp(-0.5 * ((d[lo:hi] - d[k]) / sigma_m) ** 2) * dd[lo:hi]; out[k] = (w[:, None] * h[lo:hi]).sum(0) / w.sum()
|
||||
h = out
|
||||
return elev(h, d[:, None]), h
|
||||
|
||||
def normals(d, h):
|
||||
"""Surface normal at every ray sample (n_r, n_t, n_up), each (K, W): n_r along the ray, n_t across it (towards increasing azimuth), n_up vertical. The slopes are the ray's own dh/dd and the difference of the
|
||||
neighbouring columns at the SAME sample (equal distance, never equal row) over 2 d COLW, both times the authored vertical exaggeration PXDEG_V / HPX_DEG, so a face reads as steep as the view draws it."""
|
||||
d = np.asarray(d, np.float64); h = np.asarray(h, np.float64); E = PXDEG_V / HPX_DEG
|
||||
sr = E * np.gradient(h, d, axis=0); st = E * (np.roll(h, -1, axis=1) - np.roll(h, 1, axis=1)) / (2 * d[:, None] * COLW); nz = 1.0 / np.sqrt(1 + sr * sr + st * st)
|
||||
return -sr * nz, -st * nz, nz
|
||||
|
||||
# ====================================================================== the authored Y mapping
|
||||
def set_view(slots, sky_row=0.04, near_row=0.66):
|
||||
"""AUTHORED vertical mapping, linear in elevation angle: row = (TOP_DEG - angle) * PXDEG_V over the whole 600-row frame (cylindrical, horizontal 17.78 px/deg).
|
||||
Two anchors: the highest ridge top in the window sits at `sky_row` (4%) of the frame height, the LOWEST crest of the nearest layer in the window sits at `near_row` (66%);
|
||||
everything below is that layer's body, its foot, and the ground-plane band. PXDEG_V = (near_row - sky_row) * 600 / (highest top - lowest near crest), clamped to
|
||||
[17.78, 178] px/deg = vertical exaggeration 1x..10x. TOP_DEG = highest top + sky_row*600/PXDEG_V; BOTTOM_DEG = TOP_DEG - 600/PXDEG_V; horizon (angle 0) at row TOP_DEG*PXDEG_V."""
|
||||
def set_view(skyline, sky_row=0.04, near_row=0.66):
|
||||
"""AUTHORED vertical mapping, linear in elevation angle: row = (TOP_DEG - angle) * PXDEG_V over the whole 600-row frame (cylindrical, horizontal 17.78 px/deg). skyline is the highest angle any sample reaches in each
|
||||
ring column (W,), straight from the march. Two anchors: the highest skyline angle in the window sits at `sky_row` (4%) of the frame height, the LOWEST sits at `near_row` (66%); everything below is body and ground.
|
||||
PXDEG_V = (near_row - sky_row) * 600 / (highest - lowest), clamped to [17.78, 178] px/deg = vertical exaggeration 1x..10x. TOP_DEG = highest + sky_row*600/PXDEG_V; BOTTOM_DEG = TOP_DEG - 600/PXDEG_V."""
|
||||
global rowang, PXDEG_V, TOP_DEG, BOTTOM_DEG
|
||||
cols = (P['win0'] + np.arange(WIN)) % W; sky = max(float(S['top'][cols][S['wt'][cols] > 0].max()) for S in slots if (S['wt'][cols] > 0).any())
|
||||
near = slots[-1]; act = near['wt'][cols] > 0; c_low = float(blurw(near['top'], 3.0)[cols][act].min()) if act.any() else sky - 2.0
|
||||
ppd = float(np.clip((near_row - sky_row) * H / max(sky - c_low, 0.05), HPX_DEG, 10 * HPX_DEG))
|
||||
w = win(np.asarray(skyline)[None, :])[0]; sky = float(w.max()); low = float(w.min())
|
||||
ppd = float(np.clip((near_row - sky_row) * H / max(sky - low, 0.05), HPX_DEG, 10 * HPX_DEG))
|
||||
PXDEG_V = ppd; TOP_DEG = sky + sky_row * H / ppd; BOTTOM_DEG = TOP_DEG - H / ppd; rowang = TOP_DEG - (np.arange(H) + 0.5) / PXDEG_V
|
||||
return dict(top_deg=TOP_DEG, bottom_deg=BOTTOM_DEG, px_per_deg=PXDEG_V, exaggeration=PXDEG_V / HPX_DEG, horizon_row=TOP_DEG * PXDEG_V, sky_deg=sky, near_crest_low_deg=c_low,
|
||||
sky_row=sky_row, near_row=near_row)
|
||||
return dict(top_deg=TOP_DEG, bottom_deg=BOTTOM_DEG, px_per_deg=PXDEG_V, exaggeration=PXDEG_V / HPX_DEG, horizon_row=TOP_DEG * PXDEG_V, sky_deg=sky, low_deg=low, sky_row=sky_row, near_row=near_row)
|
||||
|
||||
# ====================================================================== coverage and seams
|
||||
COV_BINS = 160 # log-distance bins between the first and the last sample
|
||||
SIG_B = 1.5 # blur of the coverage along depth (bins): seams settle in gaps
|
||||
SEAM_LAM, SEAM_UNARY = 2.0, 0.25 # forward energy: a seam that moves a bin between neighbouring columns pays SEAM_LAM per bin plus every visible row it sweeps; one that sits in visible terrain pays SEAM_UNARY x those rows (cross-fadable)
|
||||
SEAM_PRIOR = 0.05 # the authored depth only breaks ties between equal gaps, rows per nat^2: a stronger pull makes a seam hop across a ridge it cannot follow (2.0 hopped a 4 to 15 km ridge between two columns, a tear)
|
||||
SEAM_SEP = 0.4 # seams at least this far apart in log-distance (nat)
|
||||
XF = 0.07 # half-width of a seam's cross-fade, nat (about two bins)
|
||||
|
||||
def log_edges(d, nb=COV_BINS): L = np.log(np.asarray(d, np.float64)); return np.linspace(L[0], L[-1] + 1e-9, nb + 1)
|
||||
|
||||
def opaque(a):
|
||||
"""Coverage 0..1 of every frame row by the opaque view of angles a (K, n): the share of the row's angular span under the column skyline."""
|
||||
p = 1.0 / PXDEG_V; lo = rowang - 0.5 * p; return np.clip((np.asarray(a, np.float64).max(0)[None, :] - lo[:, None]) / p, 0, 1)
|
||||
|
||||
def coverage(d, a, nb=COV_BINS):
|
||||
"""(nb, n): rows of the opaque view first revealed by the samples of each log-distance bin, per column. The rows below the first sample (nearer than it) count in bin 0. Needs set_view."""
|
||||
a = np.asarray(a, np.float64); edges = log_edges(d, nb); kb = np.clip(np.searchsorted(edges, np.log(d), 'right') - 1, 0, nb - 1)
|
||||
runmax = np.maximum.accumulate(a, axis=0); prev = np.vstack([np.full((1, a.shape[1]), BOTTOM_DEG), runmax[:-1]])
|
||||
C = np.zeros((nb, a.shape[1])); np.add.at(C, kb, np.clip(np.minimum(a, TOP_DEG) - np.maximum(prev, BOTTOM_DEG), 0, None) * PXDEG_V)
|
||||
C[0] += np.clip(np.minimum(a[0], TOP_DEG) - BOTTOM_DEG, 0, None) * PXDEG_V
|
||||
return C
|
||||
|
||||
def _dt(f, u):
|
||||
"""out[i] = min_k f[k] + |u[i] - u[k]| along axis 0, u increasing: two cumulative-minimum passes (Felzenszwalb & Huttenlocher's L1 distance transform)."""
|
||||
u = u.reshape((-1,) + (1,) * (f.ndim - 1)); return np.minimum(np.minimum.accumulate(f - u, axis=0) + u, np.flip(np.minimum.accumulate(np.flip(f + u, 0), axis=0), 0) - u)
|
||||
|
||||
def seams(cov, targets, d):
|
||||
"""(K, n) ordered seam distances (m), one per authored target (m), each column. One 1D forward-energy DP per seam, in target order (seam carving, Avidan & Shamir 2007; forward energy, Rubinstein et al. 2008): unary
|
||||
SEAM_UNARY x the rows at the seam; moving a bin between neighbouring columns costs SEAM_LAM per bin plus the rows swept, an L1 distance in u = cumsum(rows) + SEAM_LAM x bin; a weak prior to the target. Seam k is held at
|
||||
least SEAM_SEP nat beyond seam k-1 in every column. Sequential, not joint: a joint DP has NB^K states per column and seams in gaps do not interact."""
|
||||
cov = np.asarray(cov, np.float64); nb, n = cov.shape; edges = log_edges(d, nb); bc = 0.5 * (edges[:-1] + edges[1:]); sep = int(math.ceil(SEAM_SEP / (edges[1] - edges[0]))); INF = 1e12
|
||||
r = int(3 * SIG_B) + 1; kern = np.exp(-0.5 * (np.arange(-r, r + 1) / SIG_B) ** 2); kern /= kern.sum(); pad = np.pad(cov, ((r, r), (0, 0)), mode='edge'); Cs = sum(kv * pad[i:i + nb] for i, kv in enumerate(kern))
|
||||
bins = np.arange(nb); lo = np.zeros(n, int); out = np.zeros((len(targets), n))
|
||||
for t, T in enumerate(targets):
|
||||
prior = SEAM_PRIOR * (bc - math.log(T)) ** 2; need = np.minimum(lo + (sep if t else 0), nb - 1); feas = bins[:, None] >= need[None, :]
|
||||
warp = lambda x: np.cumsum(0.5 * (cov[:, x - 1] + cov[:, x])) + SEAM_LAM * bins
|
||||
cost = np.where(feas[:, 0], SEAM_UNARY * Cs[:, 0] + prior, INF); store = [cost]
|
||||
for x in range(1, n): cost = np.where(feas[:, x], _dt(cost, warp(x)) + SEAM_UNARY * Cs[:, x] + prior, INF); store.append(cost)
|
||||
j = np.zeros(n, int); j[-1] = int(np.argmin(store[-1]))
|
||||
for x in range(n - 1, 0, -1): u = warp(x); j[x - 1] = int(np.argmin(store[x - 1] + np.abs(u - u[j[x]])))
|
||||
out[t] = np.exp(bc[j]); lo = j
|
||||
return out
|
||||
|
||||
# ====================================================================== cards: layered depth, one per band between seams
|
||||
GRASS, FOREST, ROCK, SNOW = (0.36, 0.44, 0.26), (0.22, 0.31, 0.20), (0.47, 0.44, 0.41), (0.93, 0.95, 0.97)
|
||||
def albedo(h, n_up):
|
||||
"""The authored material, a few numbers: valley green to forest to rock by height, rock where the face is steep, snow above the tree line. Straight colour, no light in it."""
|
||||
t = lambda a, b: np.clip((h - a) / (b - a), 0, 1)[..., None]; c = np.asarray(GRASS) + (np.asarray(FOREST) - GRASS) * t(150, 900); c = c + (np.asarray(ROCK) - c) * t(1300, 2000)
|
||||
c = c + (np.asarray(ROCK) - c) * np.clip((0.93 - n_up) / 0.25, 0, 1)[..., None]; return c + (np.asarray(SNOW) - c) * (t(1900, 2300) * np.clip((n_up - 0.55) / 0.3, 0, 1)[..., None])
|
||||
|
||||
def cards(d, a, h, seams, nrm=None):
|
||||
"""K+1 cards, nearest first, from the angles a and heights h (samples, n) of n columns and the (K, n) seams (m). Card i holds per pixel the FIRST VISIBLE hit at or beyond seam i-1 (less XF): layered depth, so a farther
|
||||
card keeps the terrain a nearer ridge hides. Its alpha is that pixel's coverage (a crest row holds the share of its angular span under the card's running maximum) times 1 - smoothstep over seam i +- XF in
|
||||
log-distance of the hit; card 0 owns the rows below the first sample, the last card has no far edge. Alphas are then made nested so the alpha-over composite of all cards is exactly the opaque coverage (a row two
|
||||
cards both hold partly is not counted twice). Distance and normal are interpolated between sample k-1 and k by angle. Each card is cropped to the rows where its 8-bit alpha is not zero.
|
||||
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))."""
|
||||
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)
|
||||
for x in range(n):
|
||||
for i in range(nc):
|
||||
k0 = 0 if i == 0 else int(ks0[i - 1][x]); k1 = nk if i == nc - 1 else int(ks1[i][x])
|
||||
if k1 <= k0: continue
|
||||
rm = np.maximum.accumulate(a[k0:k1, x]); idx = np.searchsorted(rm, lo, 'right'); hit = idx < len(rm); idx = np.minimum(idx, len(rm) - 1); kk = k0 + idx
|
||||
if not hit.any(): continue
|
||||
kp = np.maximum(kk - 1, k0); prev = np.where(idx > 0, rm[np.maximum(idx - 1, 0)], rm[idx] - 1.0)
|
||||
t = np.where(idx > 0, np.clip((rowang - prev) / np.maximum(rm[idx] - prev, 1e-9), 0, 1), 1.0); mix = lambda arr: arr[kp, x] + t * (arr[kk, x] - arr[kp, x])
|
||||
F[i, :, x] = np.where(hit, np.clip((rm[-1] - lo) / p, 0, 1), 0); lh = mix(ld)
|
||||
G[i, :, :, x] = np.where(hit, np.stack([lh, mix(h), mix(n_r), mix(n_t), mix(n_u)]), 0)
|
||||
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
|
||||
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)))
|
||||
return out
|
||||
|
|
|
|||
|
|
@ -1,13 +1,13 @@
|
|||
"""Fixtures for the ridge baker (march, prefilter, coverage, seams, normals, cards, export). Plain asserts, no pytest needed: venv/bin/python tests/test_ridge.py (exit code 1 on failure).
|
||||
RIDGE_SRC selects the source directory (default ..) (the mutation runner points it at a patched copy).
|
||||
Synthetic terrain has a known right answer; the Vienna tests bake the real preset (its rays come from stage0: RIDGE_TILES needs the tiles, or a cached rays file must exist)."""
|
||||
import os, sys, math, traceback
|
||||
import os, sys, math, json, shutil, tempfile, traceback
|
||||
SRC = os.environ.get('RIDGE_SRC') or os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'); sys.path.insert(0, SRC) # RIDGE_WORK and RIDGE_TILES must be set (tests/run.sh sets them)
|
||||
import numpy as np, ridge
|
||||
from ridge import W
|
||||
import numpy as np, ridge, export
|
||||
from ridge import W, WIN, H
|
||||
|
||||
EYE = 100.0; GROUND = 50.0 # ground below the eye: every ray climbs, so only the placed blocks make ridges
|
||||
ridge.P = dict(id='synthetic', rmax_km=60)
|
||||
ridge.P = dict(id='synthetic', rmax_km=95, eye_m=100.0, win0=0)
|
||||
D = ridge.schedule(False)
|
||||
def az_of(x): return (x + 0.5) / W * 360.0
|
||||
def col_of(az): return int(round(az / 360.0 * W - 0.5)) % W
|
||||
|
|
@ -44,6 +44,206 @@ 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:])
|
||||
|
||||
# ---------------------------------------------------------------------------------------- synthetic bakes: the shared steps of export.bake_place on rays the fixtures make
|
||||
def _bake(hfun, splits_km, sigma=0.0):
|
||||
"""prefilter, set_view, coverage, seams, cards on synthetic rays (window = columns 0..WIN, i.e. azimuth 0..72): the dict bake_place returns."""
|
||||
A, Hh = rays(hfun); ridge.P.update(win0=0, eye_m=EYE); a, h = ridge.prefilter(D, Hh, sigma); v = ridge.set_view(a.max(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])))
|
||||
return dict(place=place, view=view, meta=meta, cards=ridge.cards(D, aw, hw, sm, nrm), 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
|
||||
|
||||
def test_seams_fall_in_depth_gaps():
|
||||
"""Three ridges at 3, 20 and 70 km: targets [6, 40] give a seam in (3, 20) and one in (20, 70) in EVERY column, ordered with at least 0.4 nat between; targets [6] give one seam in (3, 20)."""
|
||||
b = _bake(THREE, [6, 40]); s = b['seams']; assert s.shape == (2, WIN)
|
||||
assert (s[0] > 3600).all() and (s[0] < 20000).all() and (s[1] > 21500).all() and (s[1] < 70000).all(), (s.min(1), s.max(1)); assert (np.log(s[1]) - np.log(s[0]) >= 0.4 - 1e-9).all()
|
||||
s1 = _bake(THREE, [6])['seams']; assert s1.shape == (1, WIN) and (s1[0] > 3600).all() and (s1[0] < 20000).all(), (s1.min(), s1.max())
|
||||
def _receding(dk, az):
|
||||
"""A ridge 300 m thick whose distance runs from 4 km at azimuth 0 to 15 km at azimuth 72."""
|
||||
dr = 4000.0 + 11000.0 * np.clip(az / 72.0, 0, 1); return np.where((az <= 72) & (np.abs(dk - dr) < 150), 1500.0, 0.0)
|
||||
def test_seam_never_splits_a_receding_ridge_side_by_side():
|
||||
"""A ridge whose distance runs 4 to 15 km across azimuth, target 6 km: the nearer card's alpha on the ridge's body never jumps between neighbouring columns (a tear, one card here and the other next door); it may fade, slowly, over the cross-fade.
|
||||
With the swept-rows term out of the seam cost the seam hops across the ridge between two columns."""
|
||||
b = _bake(terrain(_receding), [6]); c0 = _canvas(b['cards'][0]); c1 = _canvas(b['cards'][1]); crest = np.argmax(b['opaque'] > 0.5, axis=0); r = np.clip(crest + 4, 0, H - 1)
|
||||
a0 = c0[r, np.arange(WIN)]; a1 = c1[r, np.arange(WIN)]; ok = crest > 0
|
||||
assert np.abs(np.diff(a0[ok])).max() < 0.35 and np.abs(np.diff(a1[ok])).max() < 0.35, ('a card appears or vanishes between neighbouring columns', np.abs(np.diff(a0[ok])).max(), np.abs(np.diff(a1[ok])).max())
|
||||
assert ((a0 + (1 - a0) * a1)[ok] > 0.999).all(), 'the ridge body is not covered by the two cards together'
|
||||
def test_far_card_keeps_terrain_hidden_behind_a_nearer_ridge():
|
||||
"""Layered depth: a far ridge (20 km) lower in angle than the near ridge (3 km) in azimuth 0..36 and higher in 36..72. Where the near card is opaque in front of the far ridge (columns 100..500) the mid card still holds that ridge, at its distance."""
|
||||
b = _bake(terrain(block(0, 359.99, 3000, 3600, 350), block(0, 36, 20000, 21500, 700), block(36, 359.99, 20000, 21500, 1800)), [6]); c0, c1 = b['cards']
|
||||
top_far = ridge.opaque(b['a']); lo = theta(700, 20000); r = _row(lo - 0.2)
|
||||
for x in (100, 300, 500):
|
||||
assert _canvas(c0)[r, x] > 0.99, ('the near ridge does not cover the far one here', x); assert _canvas(c1)[r, x] > 0.99, ('the far card lost the terrain behind the near ridge', x)
|
||||
assert abs(math.exp(_canvas(c1, 'logd')[r, x]) - 20000) < 1500, (x, math.exp(_canvas(c1, 'logd')[r, x]))
|
||||
assert _canvas(c0, 'alpha')[_row(theta(1800, 20000) - 0.2), 900] > 0.99 and _canvas(c1)[_row(theta(1800, 20000) + 0.1), 900] < 0.5 + 0.5, 'sanity'
|
||||
def test_crossfade_is_complementary():
|
||||
"""A ridge across the seam (seam fixed at 6 km, the ridge's front face at 5.9 km inside the cross-fade): the nearer card is partly transparent over the window, the farther card is opaque on the ridge, and the composite stays at coverage 1 below the crest."""
|
||||
A, Hh = rays(terrain(block(0, 359.99, 5900, 6100, 900))); ridge.P.update(win0=0, eye_m=EYE); ridge.set_view(A.max(0)); aw, hw = ridge.win(A), ridge.win(Hh)
|
||||
cs = ridge.cards(D, aw, hw, np.full((1, WIN), 6000.0)); c0, c1 = _canvas(cs[0]), _canvas(cs[1]); crest = int(np.argmax(ridge.opaque(aw)[:, 500] > 0.5)); r = crest + 6
|
||||
assert 0.2 < c0[r, 500] < 0.8, ('the near card does not fade over the window', c0[r, 500]); assert c1[r, 500] > 0.99, 'the far card is not opaque on the ridge'
|
||||
comp = 1 - (1 - c0) * (1 - c1); assert (comp[crest + 3:, :] > 0.999).all(), 'the composite dips below coverage 1 under the crest'
|
||||
def test_normals_of_a_tilted_plane():
|
||||
"""A plane with front slope s (north) and lateral slope l (east), seen towards azimuth 0: n = (-E s, -E l, 1) normalised, E the authored exaggeration (a dropped E fails)."""
|
||||
s, l, E = 0.12, -0.08, 3.0; saved = ridge.PXDEG_V; ridge.PXDEG_V = E * ridge.HPX_DEG
|
||||
try:
|
||||
az = (np.arange(W) + 0.5) / W * 2 * math.pi; h = 300.0 + s * D[:, None] * np.cos(az)[None, :] + l * D[:, None] * np.sin(az)[None, :]; nr, nt, nu = ridge.normals(D, h); k = len(D) // 2; x = [0, 1, 2, W - 2, W - 1]
|
||||
want = np.array([-E * s, -E * l, 1.0]); want /= np.linalg.norm(want); got = np.array([nr[k, x].mean(), nt[k, x].mean(), nu[k, x].mean()]); assert np.abs(got - want).max() < 2e-3, (got, want)
|
||||
assert np.abs(nr ** 2 + nt ** 2 + nu ** 2 - 1).max() < 1e-9
|
||||
finally: ridge.PXDEG_V = saved
|
||||
def test_lateral_slope_uses_equal_distance_not_equal_row():
|
||||
"""A plane with lateral slope l at 20 km, a 3 km ridge only for azimuth above 40 deg: at the 20 km samples, in the columns around the ridge's azimuth edge, the across-ray slope is the plane's own l (neighbouring columns at the same distance), not a step between the ridge and the plane."""
|
||||
l = 0.05; saved = ridge.PXDEG_V; ridge.PXDEG_V = 2.0 * ridge.HPX_DEG
|
||||
try:
|
||||
az = (np.arange(W) + 0.5) / W * 360.0; A, Hh = rays(lambda dk, a: np.where(dk > 10000, GROUND + l * dk * np.radians(a), GROUND) + np.where((a > 40) & (dk >= 3000) & (dk < 3600), 400.0, 0.0))
|
||||
nr, nt, nu = ridge.normals(D, Hh); k = int(np.searchsorted(D, 20000)); x0 = int(40 / 360 * W); want = -2.0 * l / math.sqrt(1 + 4 * l * l + (2.0 * 0.0) ** 2)
|
||||
assert np.abs(nt[k, x0 - 20:x0 + 20] / nu[k, x0 - 20:x0 + 20] + 2.0 * l).max() < 5e-3, nt[k, x0 - 5:x0 + 5] / nu[k, x0 - 5:x0 + 5]
|
||||
finally: ridge.PXDEG_V = saved
|
||||
def test_prefilter_flattens_roofs_and_keeps_hills():
|
||||
"""A 25 m bump 60 m wide at 2 km drops below 5 m; a 400 m hill (3 km scale) keeps at least 90% of its height."""
|
||||
ridge.P.update(eye_m=EYE); roof = lambda dk, az: GROUND + np.where((az < 1.72) & (dk >= 2000) & (dk < 2060), 25.0, 0.0)
|
||||
hill = lambda dk, az: GROUND + 400.0 * np.exp(-((dk - 10000.0) / 3000.0) ** 2 - ((np.radians(((az + 180) % 360) - 180) * dk) / 3000.0) ** 2)
|
||||
for f, name in ((roof, 'roof'), (hill, 'hill')):
|
||||
A, Hh = rays(f); a, h = ridge.prefilter(D, Hh, 100.0); k = int(np.argmin(np.abs(D - (2030 if name == 'roof' else 10000)))); x = int(np.argmax(Hh[k]))
|
||||
if name == 'roof': assert h[k, x] - GROUND < 5.0 and Hh[k, x] - GROUND >= 24.9, ('the roof survives the low-pass', h[k, x] - GROUND)
|
||||
else: assert h[k, x] - GROUND >= 0.9 * 400.0, ('the hill is flattened', h[k, x] - GROUND)
|
||||
assert np.allclose(ridge.prefilter(D, Hh, 0.0)[1], Hh), 'sigma 0 changed the heights'
|
||||
def test_crest_rows_have_fractional_coverage():
|
||||
"""The top row of a card's run has alpha equal to the share of its angular span under the running maximum, and the rows below it are 1 (a lower ridge in columns 0..640 so its crest is not at the frame's top edge)."""
|
||||
A, Hh = rays(terrain(block(0, 36, 5000, 5600, 500), block(36, 359.99, 5000, 5600, 560))); ridge.P.update(win0=0, eye_m=EYE); ridge.set_view(A.max(0)); aw, hw = ridge.win(A), ridge.win(Hh); c = ridge.cards(D, aw, hw, np.zeros((0, WIN)))[0]
|
||||
cv = _canvas(c)[:, 300]; r = int(np.argmax(cv > 0)); top = float(aw.max(0)[300]); p = 1.0 / ridge.PXDEG_V; want = (top - (ridge.rowang[r] - 0.5 * p)) / p
|
||||
assert 0.0 < want < 1.0 and abs(cv[r] - want) < 0.01, (cv[r], want, r); assert (cv[r + 1:] > 0.999).all()
|
||||
def test_cards_composite_to_the_opaque_view():
|
||||
"""Alpha-over of all cards, last to first, equals the opaque march coverage within 0.02 everywhere, and where opaque the nearest solid card's distance is the first-hit distance of the march."""
|
||||
for hf, sp in ((THREE, [6, 40]), (terrain(_receding), [6]), (terrain(block(0, 359.99, 3000, 3600, 350), block(0, 36, 20000, 21500, 700), block(36, 359.99, 20000, 21500, 1800)), [6])):
|
||||
b = _bake(hf, sp); comp = 1 - np.prod([1 - _canvas(c) for c in b['cards']], axis=0); assert np.abs(comp - b['opaque']).max() < 0.02, np.abs(comp - b['opaque']).max()
|
||||
rm = np.maximum.accumulate(b['a'], axis=0); col = 640; r = _row(float(b['a'][:, col].max()) - 0.5); k = int(np.searchsorted(rm[:, col], ridge.rowang[r], 'left')); first = None
|
||||
for c in b['cards']:
|
||||
if _canvas(c)[r, col] > 0.99: first = math.exp(_canvas(c, 'logd')[r, col]); break
|
||||
assert first is not None and abs(first - D[k]) < 0.1 * D[k] + 60, (first, D[k])
|
||||
|
||||
# ---------------------------------------------------------------------------------------- the real thing: Vienna
|
||||
def _vienna(splits):
|
||||
saved = ridge.P
|
||||
try:
|
||||
p = ridge.configure(dict(ridge.load_preset('vienna'), card_split_km=splits)); d, _, Hh, _ = ridge.stage0(False); a, h = ridge.prefilter(d, Hh, p['prefilter_m']); ridge.set_view(a.max(0)); aw = ridge.win(a); hw = ridge.win(h)
|
||||
nrm = tuple(ridge.win(x) for x in ridge.normals(d, h)); cov = ridge.coverage(d, aw); sm = ridge.seams(cov, [k * 1000.0 for k in splits], d); return d, aw, ridge.cards(d, aw, hw, sm, nrm), sm, ridge.opaque(aw)
|
||||
finally: ridge.P = saved
|
||||
def test_vienna_k1_k2_k3():
|
||||
"""Vienna with card_split_km [6], [6, 40] and [6, 20, 40]: 2, 3 and 4 cards, seams ordered in every column, each composite equals the opaque view within 0.02; the cross-fade column count of each K is printed."""
|
||||
for sp in ([6], [6, 40], [6, 20, 40]):
|
||||
d, aw, cs, sm, op = _vienna(sp); assert len(cs) == len(sp) + 1 and sm.shape == (len(sp), WIN)
|
||||
if len(sp) > 1: assert (np.diff(np.log(sm), axis=0) >= 0.4 - 1e-9).all(), 'seams out of order'
|
||||
comp = 1 - np.prod([1 - _canvas(c) for c in cs], axis=0); assert np.abs(comp - op).max() < 0.02, (sp, np.abs(comp - op).max())
|
||||
xf = int(np.any([((0.02 < _canvas(c)) & (_canvas(c) < 0.98)).sum(0) > 3 for c in cs], axis=0).sum())
|
||||
print(f' K={len(sp)} splits {sp}: {len(cs)} cards, bands {[(c["top"], c["alpha"].shape[0]) for c in cs]}, seam medians km {[round(float(np.median(s)) / 1000, 1) for s in sm]}, cross-fade columns {xf} of {WIN}')
|
||||
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
|
||||
try: b = export.bake_place('vienna'); P = ridge.P; rowang = ridge.rowang; pxv = ridge.PXDEG_V
|
||||
finally: ridge.P = saved
|
||||
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()
|
||||
try:
|
||||
dest = export.write_bake(d, pl, view, b['meta'], export.pack(b), b['opaque']); m = json.load(open(dest / 'manifest.json')); export.validate(m, export.SCHEMA['$defs']['manifest'])
|
||||
assert json.load(open(d + '/index.json'))['default'] == 'vienna' and sorted(os.listdir(d)) == sorted(['index.json', dest.name]), os.listdir(d); print(' vienna manifest bytes', m['bytes'], 'cards', [(c['top'], c['h'], c['colour']['bytes'] + c['geometry']['bytes']) for c in m['cards']])
|
||||
finally: shutil.rmtree(d)
|
||||
|
||||
# ---------------------------------------------------------------------------------------- export: manifest v2, budget, cover
|
||||
def _packed(b=None):
|
||||
b = b or _bake(THREE, [6, 40]); 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)
|
||||
except ValueError: assert not os.path.exists(out), ('a refused bake left files', why)
|
||||
else: assert False, why
|
||||
def test_manifest_v2_writer():
|
||||
"""Two independent bakes give the same bytes and bake_id; the manifest validates (an extra key does not), cards are nearest first with their bands and seam medians, the files are what the manifest says, the index points at the dir, a rebake replaces
|
||||
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'
|
||||
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['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
|
||||
assert m['bytes'] == sum(c[k]['bytes'] for c in m['cards'] for k in ('colour', 'geometry')) and m['encoding']['normal'] == 'rt8' and m['curvature'] == dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF)
|
||||
idx = json.load(open(d + '/a/index.json')); export.validate(idx, export.SCHEMA['$defs']['index']); assert idx == dict(schema=1, default='synthetic', places={'synthetic': a.name})
|
||||
pk3 = [dict(c) for c in pk]; pk3[1]['geometry'] = pk3[1]['geometry'] + b'x'; assert export.bake_id([(c['colour'], c['geometry']) for c in pk3]) != export.bake_id([(c['colour'], c['geometry']) for c in pk]), 'a changed byte kept the bake_id'
|
||||
import hashlib; want = hashlib.sha256(b''.join(c['colour'] + c['geometry'] for c in pk)).hexdigest()[:12]; assert export.bake_id([(c['colour'], c['geometry']) for c in pk]) == want, 'bake_id is not the sha256 of the card files, colour then geometry, in index order'
|
||||
assert export.bake_id([(c['geometry'], c['colour']) for c in pk]) != want and export.bake_id([(c['colour'], c['geometry']) for c in pk[::-1]]) != want, 'bake_id ignores the file order'
|
||||
bad = json.loads(json.dumps(m)); bad['cards'][0]['extra'] = 1
|
||||
try: export.validate(bad, export.SCHEMA['$defs']['manifest'])
|
||||
except ValueError: pass
|
||||
else: assert False, 'an extra key passed the schema'
|
||||
assert json.load(open(os.path.join(SRC, 'ridge-bake.schema.json'))) == json.loads(json.dumps(export.SCHEMA)), 'ridge-bake.schema.json is stale (export.py --write-schema)'
|
||||
want = dict(credit_line='Contains modified Copernicus data: DEM © DLR e.V. 2010-2014 and © Airbus Defence and Space GmbH 2014-2018 provided under COPERNICUS by the European Union and ESA; all rights reserved.',
|
||||
licence='Copernicus DEM licence: free, full and open access, with the credit line shown', dem_source='Copernicus DEM GLO-30 (30 m)', url='https://spacedata.copernicus.eu/collections/copernicus-digital-elevation-model')
|
||||
assert m['attribution'] == want, m['attribution']
|
||||
c = export.write_bake(d + '/a', b['place'], b['view'], b['meta'], pk, b['opaque'])
|
||||
assert c.name == a.name; other = dict(b['place'], id='other'); export.write_bake(d + '/a', other, b['view'], b['meta'], pk, b['opaque']); assert json.load(open(d + '/a/index.json'))['default'] == 'synthetic'
|
||||
export.write_bake(d + '/a', other, b['view'], b['meta'], pk, b['opaque'], default='other'); assert json.load(open(d + '/a/index.json'))['default'] == 'other'
|
||||
idx = json.load(open(d + '/a/index.json')); idx['default'] = 'gone'; open(d + '/a/index.json', 'w').write(json.dumps(idx)); export.write_bake(d + '/a', other, b['view'], b['meta'], pk, b['opaque']); assert json.load(open(d + '/a/index.json'))['default'] == 'other'
|
||||
finally: shutil.rmtree(d)
|
||||
def test_cover_and_size_refusals_write_nothing():
|
||||
"""write_bake measures the files it is handed: a card with a hole (alpha zeroed in a band of columns) fails the cover check, a card leaving the frame, cards of two widths and a colour/geometry size mismatch are refused, and nothing is written."""
|
||||
d = tempfile.mkdtemp()
|
||||
try:
|
||||
b, pk = _packed(); c1 = b['cards'][1]; hole = c1['alpha'].copy(); hole[:, 200:260] = 0
|
||||
holed = [dict(c) for c in pk]; holed[1]['colour'] = export.encode_colour(c1['albedo'], hole); holed[2] = dict(pk[2], colour=export.encode_colour(b['cards'][2]['albedo'], b['cards'][2]['alpha'] * 0)); _refuses(d + '/hole', b, holed, 'a bake whose cards leave a hole was written')
|
||||
_refuses(d + '/off', b, [dict(c, top=H - 5) if i == 0 else c for i, c in enumerate(pk)], 'a card leaving the frame was written')
|
||||
narrow = [dict(c) for c in pk]; narrow[0]['colour'] = export.encode_colour(b['cards'][0]['albedo'][:, :1000], b['cards'][0]['alpha'][:, :1000]); _refuses(d + '/wide', b, narrow, 'cards of two widths were written')
|
||||
_refuses(d + '/rows', b, pk, 'view plane_h disagreeing with the opaque view was written', view=dict(b['view'], plane_h=H + 1))
|
||||
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)
|
||||
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()
|
||||
try:
|
||||
for bad in ([5, 10, 20, 30, 40, 50], [6, 6], [6, 5], []):
|
||||
p = os.path.join(d, 'p.json'); json.dump(dict(presets=[dict(id='x', card_split_km=bad)]), open(p, 'w'))
|
||||
try: ridge.load_preset('x', p)
|
||||
except ValueError: pass
|
||||
else: assert False, ('a preset with splits', bad, 'was accepted')
|
||||
json.dump(dict(presets=[dict(id='x')]), open(os.path.join(d, 'q.json'), 'w'))
|
||||
try: ridge.load_preset('x', os.path.join(d, 'q.json'))
|
||||
except 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)
|
||||
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
|
||||
try: export.check_budget([1000] * 7, WIN, [10] * 7)
|
||||
except ValueError as e: assert 'above 6' in str(e)
|
||||
else: assert False, '7 cards were accepted'
|
||||
try: export.check_budget([750_001, 750_000], WIN, [10, 10])
|
||||
except ValueError as e: assert 'bytes' in str(e)
|
||||
else: assert False, 'cards above TOTAL_BYTES_MAX were accepted'
|
||||
export.check_budget([750_000, 750_000], WIN, [10, 10])
|
||||
try: export.check_budget([1, 1], export.PLANE_W_MAX + 1, [10, 10])
|
||||
except ValueError: pass
|
||||
else: assert False, 'a card wider than the cap was accepted'
|
||||
finally: shutil.rmtree(d)
|
||||
def test_cards_are_cropped_to_their_band():
|
||||
"""Each card is exactly the rows where its 8-bit alpha is non-zero; the manifest top and h place it back at the same rows (colour and geometry decode to that band, alpha in the file equals the canvas row for row)."""
|
||||
d = tempfile.mkdtemp()
|
||||
try:
|
||||
b, pk = _packed(); dest = export.write_bake(d, b['place'], b['view'], b['meta'], pk, b['opaque']); m = json.load(open(dest / 'manifest.json'))
|
||||
for c, rec in zip(b['cards'], m['cards']):
|
||||
canvas = _canvas(c); rows = np.flatnonzero(np.rint(canvas * 255).max(1) > 0); assert rec['top'] == rows[0] and rec['h'] == rows[-1] - rows[0] + 1 == c['alpha'].shape[0], (rec, rows[0], rows[-1])
|
||||
col = export.decode((dest / rec['colour']['file']).read_bytes()); assert col.shape[:2] == (rec['h'], WIN) and np.abs(col[..., 3].astype(int) - np.rint(c['alpha'] * 255)).max() == 0, 'the written alpha is not the card alpha'
|
||||
assert export.decode((dest / rec['geometry']['file']).read_bytes()).shape[:2] == (rec['h'], WIN)
|
||||
finally: shutil.rmtree(d)
|
||||
|
||||
TESTS = [v for k, v in sorted(globals().items()) if k.startswith("test_")]
|
||||
if __name__ == '__main__':
|
||||
fails = 0
|
||||
|
|
|
|||
Loading…
Reference in a new issue