diff --git a/scripts/ridge-bake/export.py b/scripts/ridge-bake/export.py index 23361384..5e72ae01 100644 --- a/scripts/ridge-bake/export.py +++ b/scripts/ridge-bake/export.py @@ -11,6 +11,7 @@ from pathlib import Path from zoneinfo import ZoneInfo, ZoneInfoNotFoundError HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) +from refusal import Refusal import numpy as np, imagecodecs BAKER_VERSION = 7 @@ -62,41 +63,41 @@ SCHEMA = {'$schema': 'https://json-schema.org/draft/2020-12/schema', 'title': 'r def tile_file(i, t, kind): return f'card-{i}-t{t:02d}-{kind}.webp' def validate(x, s, path='$'): - """The subset of JSON Schema SCHEMA uses; raises ValueError naming the path.""" + """The subset of JSON Schema SCHEMA uses; raises Refusal naming the path.""" if '$ref' in s: return validate(x, SCHEMA['$defs'][s['$ref'].split('/')[-1]], path) tys = s.get('type'); tys = [tys] if isinstance(tys, str) else tys; py = {'object': dict, 'array': list, 'string': str, 'number': (int, float), 'integer': int, 'null': type(None)} - if tys and not any(isinstance(x, py[t]) and not (isinstance(x, bool) and t != 'null') for t in tys): raise ValueError(f'{path}: not a {"/".join(tys)}') + if tys and not any(isinstance(x, py[t]) and not (isinstance(x, bool) and t != 'null') for t in tys): raise Refusal(f'{path}: not a {"/".join(tys)}') if s.get('format') == 'iana-tz': try: ZoneInfo(x) - except (ZoneInfoNotFoundError, ValueError, OSError): raise ValueError(f'{path}: {x!r} is not a time zone the system knows') - 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"]}') + except (ZoneInfoNotFoundError, ValueError, OSError): raise Refusal(f'{path}: {x!r} is not a time zone the system knows') + if 'const' in s and x != s['const']: raise Refusal(f"{path}: must be {s['const']!r}") + if 'enum' in s and x not in s['enum']: raise Refusal(f'{path}: not one of {s["enum"]}') + if 'maximum' in s and x > s['maximum']: raise Refusal(f'{path}: above {s["maximum"]}') if isinstance(x, list): - if not s.get('minItems', 0) <= len(x) <= s.get('maxItems', 1 << 30): raise ValueError(f'{path}: wrong length') + if not s.get('minItems', 0) <= len(x) <= s.get('maxItems', 1 << 30): raise Refusal(f'{path}: wrong length') for i, v in enumerate(x): validate(v, s['items'], f'{path}[{i}]') if isinstance(x, dict): props = s.get('properties', {}); extra = s.get('additionalProperties', True) for k in s.get('required', []): - if k not in x: raise ValueError(f'{path}: missing {k}') + if k not in x: raise Refusal(f'{path}: missing {k}') for k, v in x.items(): if k in props: validate(v, props[k], f'{path}.{k}') - elif extra is False: raise ValueError(f'{path}: extra key {k}') + elif extra is False: raise Refusal(f'{path}: extra key {k}') elif isinstance(extra, dict): validate(v, extra, f'{path}.{k}') def validate_manifest(m): """The schema plus what it cannot say: the plane keeps ridge.GROUND_ROWS_MIN rows under the horizon, every tile lists one entry per card, every card holds something in some tile, each file is named for its card and tile, bytes is the sum of the files.""" import ridge validate(m, SCHEMA['$defs']['manifest']); k = len(m['cards']); v = m['view'] - if v['plane_h'] - v['horizon_row'] < ridge.GROUND_ROWS_MIN - 1e-6: raise ValueError(f"$.view: {v['plane_h'] - v['horizon_row']:.1f} rows under the horizon, below the {ridge.GROUND_ROWS_MIN} the runtime needs (ridge.GROUND_ROWS_MIN)") + if v['plane_h'] - v['horizon_row'] < ridge.GROUND_ROWS_MIN - 1e-6: raise Refusal(f"$.view: {v['plane_h'] - v['horizon_row']:.1f} rows under the horizon, below the {ridge.GROUND_ROWS_MIN} the runtime needs (ridge.GROUND_ROWS_MIN)") for t, row in enumerate(m['tiles']): - if len(row) != k: raise ValueError(f'$.tiles[{t}]: {len(row)} entries for {k} cards') + if len(row) != k: raise Refusal(f'$.tiles[{t}]: {len(row)} entries for {k} cards') for i, e in enumerate(row): for kind in (('colour', 'geometry') if e else ()): - if e[kind]['file'] != tile_file(i, t, kind): raise ValueError(f'$.tiles[{t}][{i}].{kind}: file {e[kind]["file"]!r} is not {tile_file(i, t, kind)!r}') + if e[kind]['file'] != tile_file(i, t, kind): raise Refusal(f'$.tiles[{t}][{i}].{kind}: file {e[kind]["file"]!r} is not {tile_file(i, t, kind)!r}') for i in range(k): - if all(row[i] is None for row in m['tiles']): raise ValueError(f'card {i} is null in every tile') - if m['bytes'] != sum(e[kind]['bytes'] for row in m['tiles'] for e in row if e for kind in ('colour', 'geometry')): raise ValueError('bytes is not the sum of the files') + if all(row[i] is None for row in m['tiles']): raise Refusal(f'card {i} is null in every tile') + if m['bytes'] != sum(e[kind]['bytes'] for row in m['tiles'] for e in row if e for kind in ('colour', 'geometry')): raise Refusal('bytes is not the sum of the files') # ------------------------------------------------------------------------------------ cards -> bytes def u8(a): return np.clip(np.rint(np.asarray(a) * 255.0), 0, 255).astype(np.uint8) @@ -122,7 +123,7 @@ def composite_alpha(cards, h, w): 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}') + if bad.any(): y, x = np.unravel_index(int(np.argmax(err)), err.shape); raise Refusal(f'the cards do not composite to the opaque view within {tol}: {int(bad.sum())} pixels differ, worst {err.max():.3f} at x={x} row {y}') def run_tiles(r_max_m, rmin_m): """N, the consecutive tiles the loader keeps resident: the viewport arc at the smallest slide rate plus the offset's own swing (arc_max = HFOV_MAX_DEG / s_min + 2 (r_max / Rmin) 57.3 degrees, s_min = Rmin / (Rmin + r_max)), one straddled tile and two tiles of margin each side.""" @@ -134,12 +135,12 @@ def resident_bytes(bands, n): return max(sum(per[(t + k) % TILES] for k in range(n)) for t in range(TILES)) def check_budget(n_cards, tile_bytes, bands, r_max_m, rmin_m): """Refuse a bake the runtime could not hold: more than MAX_CARDS cards, a tile whose files together are above TILE_BYTES_MAX, every file of the place above PLACE_BYTES_MAX, or the worst run of run_tiles(r_max_m, rmin_m) consecutive tiles lit above RESIDENT_BYTES_MAX.""" - if n_cards > MAX_CARDS: raise ValueError(f'{n_cards} cards, above {MAX_CARDS}') + if n_cards > MAX_CARDS: raise Refusal(f'{n_cards} cards, above {MAX_CARDS}') for t, b in enumerate(tile_bytes): - if b > TILE_BYTES_MAX: raise ValueError(f'tile {t} is {b} bytes, above {TILE_BYTES_MAX}') - if sum(tile_bytes) > PLACE_BYTES_MAX: raise ValueError(f'the place is {sum(tile_bytes)} bytes, above {PLACE_BYTES_MAX}') + if b > TILE_BYTES_MAX: raise Refusal(f'tile {t} is {b} bytes, above {TILE_BYTES_MAX}') + if sum(tile_bytes) > PLACE_BYTES_MAX: raise Refusal(f'the place is {sum(tile_bytes)} bytes, above {PLACE_BYTES_MAX}') n = run_tiles(r_max_m, rmin_m); res = resident_bytes(bands, n) - if res > RESIDENT_BYTES_MAX: raise ValueError(f'{n} consecutive tiles light to {res} bytes, above {RESIDENT_BYTES_MAX}') + if res > RESIDENT_BYTES_MAX: raise Refusal(f'{n} consecutive tiles light to {res} bytes, above {RESIDENT_BYTES_MAX}') FIT_QUAD = 48 # Gauss-Legendre nodes for the least-squares line (exact for the smooth alpha(beta) to far below a card pixel) FIT_GRID = 513 # points the worst error is looked for on, ends included: the error is smooth between them, so the maximum found is within 0.01 card px of the continuous one @@ -171,10 +172,10 @@ def solve_r_max(dist, bands, px_per_deg, phis=None): else: hi = mid r_max = math.floor(lo * 10) / 10 if r_max < R_MAX_FLOOR_M: - if cap < R_MAX_FLOOR_M: raise ValueError(f'r_max_m {r_max:g} is below {R_MAX_FLOOR_M:g} m: card 0 stands {rmin:.0f} m away in tile {near[1]} and the offset stays under half of that') + if cap < R_MAX_FLOOR_M: raise Refusal(f'r_max_m {r_max:g} is below {R_MAX_FLOOR_M:g} m: card 0 stands {rmin:.0f} m away in tile {near[1]} and the offset stays under half of that') tb = fit_table(dist, R_MAX_FLOOR_M, px_per_deg, phis); t, i = np.unravel_index(int(np.nanargmax(tb)), tb.shape) - if tb[t, i] > FIT_PX_MAX: raise ValueError(f'r_max_m {r_max:g} is below {R_MAX_FLOOR_M:g} m: card {i} in tile {t} errs {tb[t, i]:.1f} card px at {R_MAX_FLOOR_M:g} m (the bound is {FIT_PX_MAX:g})') - n = run_tiles(R_MAX_FLOOR_M, rmin); raise ValueError(f'r_max_m {r_max:g} is below {R_MAX_FLOOR_M:g} m: at {R_MAX_FLOOR_M:g} m, {n} consecutive tiles light to {resident_bytes(bands, n)} bytes, above {RESIDENT_BYTES_MAX}') + if tb[t, i] > FIT_PX_MAX: raise Refusal(f'r_max_m {r_max:g} is below {R_MAX_FLOOR_M:g} m: card {i} in tile {t} errs {tb[t, i]:.1f} card px at {R_MAX_FLOOR_M:g} m (the bound is {FIT_PX_MAX:g})') + n = run_tiles(R_MAX_FLOOR_M, rmin); raise Refusal(f'r_max_m {r_max:g} is below {R_MAX_FLOOR_M:g} m: at {R_MAX_FLOOR_M:g} m, {n} consecutive tiles light to {resident_bytes(bands, n)} bytes, above {RESIDENT_BYTES_MAX}') return r_max BAKE_ID_BLANK = '0' * 12 @@ -190,27 +191,27 @@ def write_bake(out, place, view, meta, packed, opaque, default=None): camera dict(r_max_m, r_max_forward_m)); opaque: TILES arrays (plane_h, TILE_W + 2 APRON), each the opaque view's coverage over a tile's columns. Refuses before writing a bake whose files decode to the wrong size, leave the frame, break a budget (the resident gate at r_max_m and at r_max_forward_m) or composite away from the opaque view in any tile. meta: dict(curvature, encoding). Returns the directory.""" cards, tiles, camera = packed['cards'], packed['tiles'], packed['camera']; k = len(cards); h = view['plane_h']; w = TILE_W + 2 * APRON - if len(tiles) != TILES or len(opaque) != TILES or any(len(row) != k for row in tiles): raise ValueError(f'the bake needs {TILES} tiles of {k} cards each') + if len(tiles) != TILES or len(opaque) != TILES or any(len(row) != k for row in tiles): raise Refusal(f'the bake needs {TILES} tiles of {k} cards each') for i in range(k): - if all(row[i] is None for row in tiles): raise ValueError(f'card {i} is null in every tile') + if all(row[i] is None for row in tiles): raise Refusal(f'card {i} is null in every tile') dec = [[None if e is None else (decode(e['colour']), decode(e['geometry'])) for e in row] for row in tiles]; bands = [[pair[0].shape[0] for pair in row if pair] for row in dec]; tile_bytes = [] for t, (row, drow) in enumerate(zip(tiles, dec)): tile_bytes.append(sum(len(e['colour']) + len(e['geometry']) for e in row if e)) for i, (e, pair) in enumerate(zip(row, drow)): if e is None: continue c, g = pair - if c.shape[:2] != g.shape[:2]: raise ValueError(f'tile {t} card {i}: colour and geometry are not one size') - if c.shape[1] != w: raise ValueError(f'tile {t} card {i} is {c.shape[1]} columns wide, not {w} (tile {TILE_W} + 2 apron {APRON})') - if c.shape[0] < 1 or e['top'] < 0 or e['top'] + c.shape[0] > h: raise ValueError(f'tile {t} card {i} leaves the {h} rows of the frame') - if opaque[t].shape != (h, w): raise ValueError(f'tile {t}: the opaque view is {opaque[t].shape}, the frame {(h, w)}') + if c.shape[:2] != g.shape[:2]: raise Refusal(f'tile {t} card {i}: colour and geometry are not one size') + if c.shape[1] != w: raise Refusal(f'tile {t} card {i} is {c.shape[1]} columns wide, not {w} (tile {TILE_W} + 2 apron {APRON})') + if c.shape[0] < 1 or e['top'] < 0 or e['top'] + c.shape[0] > h: raise Refusal(f'tile {t} card {i} leaves the {h} rows of the frame') + if opaque[t].shape != (h, w): raise Refusal(f'tile {t}: the opaque view is {opaque[t].shape}, the frame {(h, w)}') import ridge rmin = min(row[0]['distance_m'] for row in tiles if row[0]) # distance_m is exp of a float32 log: it lands a few parts in 1e7 off the clip, so the compare keeps 1e-5 of slack - if rmin < ridge.NEAR_CLIP_M * (1 - 1e-5): raise ValueError(f'card 0 stands {rmin:.1f} m away, nearer than the near clip {ridge.NEAR_CLIP_M:g} m: the distance of card 0 is measured at or beyond the clip (the near ground under it is not measured)') - if camera['r_max_forward_m'] < camera['r_max_m']: raise ValueError(f"r_max_forward_m {camera['r_max_forward_m']:g} is below r_max_m {camera['r_max_m']:g}: phi = 0 is one of the angles r_max_m holds for") + if rmin < ridge.NEAR_CLIP_M * (1 - 1e-5): raise Refusal(f'card 0 stands {rmin:.1f} m away, nearer than the near clip {ridge.NEAR_CLIP_M:g} m: the distance of card 0 is measured at or beyond the clip (the near ground under it is not measured)') + if camera['r_max_forward_m'] < camera['r_max_m']: raise Refusal(f"r_max_forward_m {camera['r_max_forward_m']:g} is below r_max_m {camera['r_max_m']:g}: phi = 0 is one of the angles r_max_m holds for") for r in (camera['r_max_m'], camera['r_max_forward_m']): check_budget(k, tile_bytes, bands, r, rmin) for t, (row, drow) in enumerate(zip(tiles, dec)): try: check_cover([(e['top'], pair[0][..., 3] / 255.0) for e, pair in zip(row, drow) if e], opaque[t]) - except ValueError as ex: raise ValueError(f'tile {t}: {ex}') + except Refusal as ex: raise Refusal(f'tile {t}: {ex}') out = Path(out) manifest = dict(schema=3, baker_version=BAKER_VERSION, bake_id=BAKE_ID_BLANK, place=place, view=dict(view, ring_w=RING_W, tile_w=TILE_W, tiles=TILES, apron=APRON), curvature=meta['curvature'], encoding=dict(meta['encoding'], normal='rt8'), camera=dict(r_max_m=camera['r_max_m'], r_max_forward_m=camera['r_max_forward_m']), cards=[dict(near_m=c['near_m'], far_m=c['far_m']) for c in cards], @@ -257,7 +258,7 @@ def pack(bake): import ridge sm = bake['seams']; sp = bake['splits_km']; k = len(sp) + 1; ppd = bake['view']['px_per_deg_h']; inner = slice(APRON, APRON + TILE_W); enc = bake['meta']['encoding'] for i in range(k): - if all(tile[i]['alpha'].shape[0] == 0 for tile in bake['cards']): raise ValueError(f"card {i} is empty: it lies between the splits {' and '.join(f'{sp[j]:g} km' for j in (i - 1, i) if 0 <= j < len(sp))} (card_split_km {sp}) and holds no terrain nothing nearer hides; move or remove a split") + if all(tile[i]['alpha'].shape[0] == 0 for tile in bake['cards']): raise Refusal(f"card {i} is empty: it lies between the splits {' and '.join(f'{sp[j]:g} km' for j in (i - 1, i) if 0 <= j < len(sp))} (card_split_km {sp}) and holds no terrain nothing nearer hides; move or remove a split") tiles, dist, near, bands = [], [], [], []; any_solid = [False] * k for tile in bake['cards']: row, drow, nrow, brow = [], [], [], [] @@ -269,7 +270,7 @@ def pack(bake): row.append(dict(top=c['top'], colour=encode_colour(c['albedo'], c['alpha']), geometry=encode_geometry(c['n_r'], c['n_t'], c['logd'], enc, c['wall']), distance_m=dm)); drow.append(dm); brow.append(c['alpha'].shape[0]) tiles.append(row); dist.append(drow); near.append(nrow); bands.append(brow) for i in range(k): - if not any_solid[i]: raise ValueError(f'card {i} holds no solid terrain apart from its wall rows') + if not any_solid[i]: raise Refusal(f'card {i} holds no solid terrain apart from its wall rows') r_max = solve_r_max(near, bands, ppd); r_fwd = solve_r_max(near, bands, ppd, phis=1); rmin = min(row[0] for row in near if row[0] is not None); n = run_tiles(r_fwd, rmin); worst = np.nanmax(fit_table(near, r_max, ppd), axis=0) cards = [dict(near_m=float(np.median(sm[i - 1])) if i else None, far_m=float(np.median(sm[i])) if i < len(sm) else None) for i in range(k)] return dict(cards=cards, tiles=tiles, camera=dict(r_max_m=r_max, r_max_forward_m=r_fwd), report=dict(fit_px=[float(x) for x in worst], run_tiles=n, resident_bytes=resident_bytes(bands, n), nearest_m=rmin)) # nearest_m: the nearest solid terrain of the place diff --git a/scripts/ridge-bake/refusal.py b/scripts/ridge-bake/refusal.py new file mode 100644 index 00000000..213d8369 --- /dev/null +++ b/scripts/ridge-bake/refusal.py @@ -0,0 +1,2 @@ +"""The baker's refusal: raised wherever ridge.py or export.py declines a preset, a view or a bake. The fixtures catch this class only, so an exception from numpy or the standard library reaching them is a crash (mutate.py: CRASHED), never a kill.""" +class Refusal(ValueError): pass diff --git a/scripts/ridge-bake/ridge.py b/scripts/ridge-bake/ridge.py index 08f973d4..1ec57b10 100644 --- a/scripts/ridge-bake/ridge.py +++ b/scripts/ridge-bake/ridge.py @@ -14,6 +14,7 @@ import os, hashlib from zoneinfo import ZoneInfo, ZoneInfoNotFoundError from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) +from refusal import Refusal import numpy as np, tifffile def _env_dir(name, what): @@ -35,12 +36,12 @@ def load_preset(pid, path=Path(__file__).resolve().parent / 'places.json'): """The preset dict. tz is required, an IANA zone the system knows (the runtime draws named sky moments in the place's local day). card_split_km is the ordered list of authored seam depths (km): required, strictly increasing, at most export.MAX_CARDS - 1 (the cap is export's, which owns the budget); refused here, before any march.""" d = json.load(open(path)); p = dict(next(x for x in d['presets'] if x['id'] == pid)); sp = p.get('card_split_km') from export import MAX_CARDS - if not sp: raise 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") + if not sp: raise Refusal(f"preset {pid}: card_split_km is required (an ordered list of 1 to {MAX_CARDS - 1} depths in km)") + if len(sp) > MAX_CARDS - 1 or any(b <= a for a, b in zip(sp, sp[1:])): raise Refusal(f"preset {pid}: card_split_km {sp} must be strictly increasing with at most {MAX_CARDS - 1} entries") tz = p.get('tz') - if not isinstance(tz, str) or not tz: raise ValueError(f"preset {pid}: tz is required (an IANA time zone name such as Europe/Vienna)") + if not isinstance(tz, str) or not tz: raise Refusal(f"preset {pid}: tz is required (an IANA time zone name such as Europe/Vienna)") try: ZoneInfo(tz) - except (ZoneInfoNotFoundError, ValueError, OSError): raise ValueError(f"preset {pid}: tz {tz!r} is not a time zone the system knows") + except (ZoneInfoNotFoundError, ValueError, OSError): raise Refusal(f"preset {pid}: tz {tz!r} is not a time zone the system knows") return p # ====================================================================== configuration, DEM @@ -199,12 +200,12 @@ def set_view(skyline, sky_row=0.04, near_row=0.66): """AUTHORED vertical mapping, linear in elevation angle: row = (TOP_DEG - angle) * PXDEG_V over the whole 600-row frame (cylindrical, horizontal 17.78 px/deg). skyline is the highest angle any sample reaches in each ring column (W,), straight from the march. Three anchors on the whole ring (rulings ridge-ring-vertical-anchors, ridge-ground-rows-below-horizon): the highest skyline angle of the ring sits at `sky_row` (4%) of the frame height, the LOWEST sits at `near_row` (66%) where the scale allows, and the horizon keeps GROUND_ROWS_MIN rows under it. PXDEG_V = the lesser of (near_row - sky_row) * 600 / (highest - lowest) and (600 - GROUND_ROWS_MIN - sky_row * 600) / highest, clamped to - [E_MIN, 10] x 17.78 px/deg = vertical exaggeration 0.5x..10x; a skyline whose highest angle cannot keep the ground rows even at E_MIN refuses (ValueError naming sky_deg, the scale needed and the floor). + [E_MIN, 10] x 17.78 px/deg = vertical exaggeration 0.5x..10x; a skyline whose highest angle cannot keep the ground rows even at E_MIN refuses (Refusal naming sky_deg, the scale needed and the floor). TOP_DEG = highest + sky_row*600/PXDEG_V; BOTTOM_DEG = TOP_DEG - 600/PXDEG_V. Returns the view, with `binds` naming the anchor that set the scale: 'skyline', 'horizon', 'floor' or 'ceiling'.""" global rowang, PXDEG_V, TOP_DEG, BOTTOM_DEG sk = np.asarray(skyline); sky = float(sk.max()); low = float(sk.min()); lo, hi = E_MIN * HPX_DEG, 10 * HPX_DEG fit = (near_row - sky_row) * H / max(sky - low, 0.05); hold = (H - GROUND_ROWS_MIN - sky_row * H) / sky if sky > 0 else math.inf - if hold < lo: raise ValueError(f"the whole-ring skyline reaches {sky:.2f} degrees: holding {GROUND_ROWS_MIN} rows under the horizon needs {hold:.2f} px/deg, below the floor {lo:.2f} px/deg ({E_MIN:g}x)") + if hold < lo: raise Refusal(f"the whole-ring skyline reaches {sky:.2f} degrees: holding {GROUND_ROWS_MIN} rows under the horizon needs {hold:.2f} px/deg, below the floor {lo:.2f} px/deg ({E_MIN:g}x)") ppd = float(np.clip(min(fit, hold), lo, hi)); binds = 'horizon' if hold < fit and ppd == hold else 'floor' if ppd == lo else 'ceiling' if ppd == hi else 'skyline' PXDEG_V = ppd; TOP_DEG = sky + sky_row * H / ppd; BOTTOM_DEG = TOP_DEG - H / ppd; rowang = TOP_DEG - (np.arange(H) + 0.5) / PXDEG_V return dict(top_deg=TOP_DEG, bottom_deg=BOTTOM_DEG, px_per_deg=PXDEG_V, exaggeration=PXDEG_V / HPX_DEG, horizon_row=TOP_DEG * PXDEG_V, sky_deg=sky, low_deg=low, sky_row=sky_row, near_row=near_row, binds=binds) @@ -267,7 +268,7 @@ def cards(d, a, h, seams, nrm=None): nrm is normals(d, h) of the same columns (default: computed from h as given, so pass it for columns cut from the ring: the lateral slope reads the neighbouring columns). Rows of any card below the angle of its first sample (hit and idx == 0) are its wall: they keep that sample's distance, their albedo is the ground material at their height with the face up (n_up = 1), and `wall` flags them (card 0's first sample is the near march's NEAR_START_M, so no row of it is wall under a real frame). Card 0 draws the near march (join_near; the samples nearer than NEAR_CLIP_M) under the silhouette of the terrain at the clip as ordinary terrain: its own normal, the albedo of its own height and n_up; `near` (h, n) bool flags the pixels whose hit lies on the near side of the clip sample (the rows that were card 0's wall), whose distance is then never above the clip. Each card: dict(top, alpha (h,n), albedo (h,n,3), n_r, n_t, logd (ln metres) (h,n), wall (h,n) bool, near (h,n) bool).""" d = np.asarray(d, np.float64); a = np.asarray(a, np.float64); h = np.asarray(h, np.float64); seams = np.asarray(seams, np.float64); nk, n = a.shape; nc = len(seams) + 1 - if d[0] >= NEAR_CLIP_M: raise ValueError(f"card 0 draws the ground under the near clip from the near march, but the first sample is at {d[0]:g} m (the clip is {NEAR_CLIP_M:g} m): pass join_near") + if d[0] >= NEAR_CLIP_M: raise Refusal(f"card 0 draws the ground under the near clip from the near march, but the first sample is at {d[0]:g} m (the clip is {NEAR_CLIP_M:g} m): pass join_near") n_r, n_t, n_u = nrm if nrm is not None else normals(d, h); ld = np.broadcast_to(np.log(d)[:, None], (nk, n)); p = 1.0 / PXDEG_V; lo = rowang - 0.5 * p; kn = int(np.searchsorted(d, NEAR_CLIP_M)) # kn: the samples nearer than the clip ks0 = [np.searchsorted(d, seams[i - 1] * math.exp(-XF)) for i in range(1, nc)]; ks1 = [np.searchsorted(d, seams[i] * math.exp(XF)) for i in range(nc - 1)] F = np.zeros((nc, H, n)); X = np.ones((nc, H, n)); G = np.zeros((nc, 5, H, n)); Wl = np.zeros((nc, H, n), bool); Nr = np.zeros((nc, H, n), bool) # coverage, far fade, then (logd, h, n_r, n_t, n_u); wall rows; near rows (the ground under the clip) diff --git a/scripts/ridge-bake/tests/mutate.py b/scripts/ridge-bake/tests/mutate.py index cf377812..34a13d45 100644 --- a/scripts/ridge-bake/tests/mutate.py +++ b/scripts/ridge-bake/tests/mutate.py @@ -34,7 +34,7 @@ MUTANTS = { # name -> (text in ridge.py or export.py, replacement) 'near: the heights are stored float32': (", np.float64) for dk in d])", ", np.float32) for dk in d])"), 'near: the place prefilter is not applied': ("; a, h = prefilter(d, h, sigma_m)\n", "; a, h = prefilter(d, h, 0.0)\n"), 'near: the far normals are computed over the joined march (not apart)': ("nn, nf = normals(dn, hn), normals(d, h)", "nj_ = normals(np.concatenate([dn, d]), np.concatenate([hn, h])); nn, nf = tuple(x[:len(dn)] for x in nj_), tuple(x[len(dn):] for x in nj_)"), - 'near: cards accepts a march that starts at the clip': ("if d[0] >= NEAR_CLIP_M: raise ValueError", "if False: raise ValueError"), + 'near: cards accepts a march that starts at the clip': ("if d[0] >= NEAR_CLIP_M: raise Refusal", "if False: raise Refusal"), 'pack: near pixels count as solid terrain': ("solid = (al >= 0.5) & ~wl & ~nr;", "solid = (al >= 0.5) & ~wl;"), 'pack: the non-wall fallback pool reads near pixels': ("((al > 0) & ~wl & ~nr, ld)", "((al > 0) & ~wl, ld)"), 'pack: the lit fallback pool reads near pixels': ("((al > 0) & ~nr, ld)", "(al > 0, ld)"), @@ -64,7 +64,7 @@ MUTANTS = { # name -> (text in ridge.py or export.py, replacement) 'bake_id: card-major instead of tile-major': ("bake_id(text, [(e['colour'], e['geometry']) for row in tiles for e in row if e])", "bake_id(text, [(row[i]['colour'], row[i]['geometry']) for i in range(k) for row in tiles if row[i]])"), 'bake_id: the manifest is not hashed (a manifest moves under its id)': ("h = hashlib.sha256(); h.update(manifest_text.encode('utf-8'))", "h = hashlib.sha256()"), 'bake_id: the manifest is hashed with the id already in it (the blank is skipped)': ("bid = bake_id(text, [", "bid = bake_id(text.replace(BAKE_ID_BLANK, '111111111111'), ["), - 'write: the per-tile cover check is dropped': ("except ValueError as ex: raise ValueError(f'tile {t}: {ex}')", "except ValueError as ex: pass"), + 'write: the per-tile cover check is dropped': ("except Refusal as ex: raise Refusal(f'tile {t}: {ex}')", "except Refusal as ex: pass"), 'write: the apron width is not checked': ("if c.shape[1] != w: raise", "if False: raise"), 'budget: the tile cap is ignored': ("if b > TILE_BYTES_MAX: raise", "if False: raise"), 'budget: the place cap is ignored': ("if sum(tile_bytes) > PLACE_BYTES_MAX: raise", "if False: raise"), diff --git a/scripts/ridge-bake/tests/test_ridge.py b/scripts/ridge-bake/tests/test_ridge.py index da8b0755..51b3161a 100644 --- a/scripts/ridge-bake/tests/test_ridge.py +++ b/scripts/ridge-bake/tests/test_ridge.py @@ -217,7 +217,8 @@ def _write(out, b, packed, **kw): args = dict(place=b['place'], view=b['view'], meta=b['meta'], packed=packed, opaque=b['opaque']); args.update(kw); return export.write_bake(out, **args) def _refuses(out, b, packed, why, **kw): try: _write(out, b, packed, **kw) - except ValueError: assert not os.path.exists(out), ('a refused bake left files', why) + except export.Refusal: assert not os.path.exists(out), ('a refused bake left files', why) + except Exception as e: raise AssertionError(f'{why}: the writer failed with {type(e).__name__}, not a Refusal: {e}') else: assert False, why def _pins(): assert (export.RING_W, export.TILES, export.TILE_W, export.APRON, export.MAX_CARDS, export.BAKER_VERSION) == (6400, 32, 200, 2, 6, 7), 'the ring layout is pinned' @@ -233,7 +234,7 @@ def test_schema3(): def bad(f, why): x = mk(); f(x) try: export.validate_manifest(x) - except ValueError: return + except export.Refusal: return raise AssertionError(why) bad(lambda x: x['camera'].pop('r_max_forward_m'), 'a camera without its forward offset validated'); bad(lambda x: x['camera'].pop('r_max_m'), 'a camera without its offset validated') bad(lambda x: x['tiles'].pop(), 'a manifest of 31 tiles validated'); bad(lambda x: x['tiles'][3].pop(), 'a tile with a card missing validated'); bad(lambda x: x['tiles'][3].append(None), 'a tile with an extra card validated'); bad(lambda x: x['view'].pop('apron'), 'a missing apron validated') @@ -290,15 +291,15 @@ def test_tile_crop_and_null(): for i, why in ((1, '20 km'), (2, '55 km')): gone = [[empty if j == i else c for j, c in enumerate(tile)] for tile in b['cards']] try: export.pack(dict(b, cards=gone)) - except ValueError as e: assert f'card {i} is empty' in str(e) and why in str(e), str(e) + except export.Refusal as e: assert f'card {i} is empty' in str(e) and why in str(e), str(e) else: assert False, ('an empty card', i, 'was packed') liquid = [[dict(c, alpha=c['alpha'] * 0.4) if j == 1 else c for j, c in enumerate(tile)] for tile in t0['cards']] try: export.pack(dict(t0, cards=liquid)) - except ValueError as e: assert 'no solid terrain' in str(e), str(e) + except export.Refusal as e: assert 'no solid terrain' in str(e), str(e) else: assert False, 'a card with no solid pixel in any tile was packed' walled = [[dict(c, wall=np.ones_like(c['wall'])) if j == 1 else c for j, c in enumerate(tile)] for tile in t0['cards']] try: export.pack(dict(t0, cards=walled)) - except ValueError as e: assert 'no solid terrain' in str(e), str(e) + except export.Refusal as e: assert 'no solid terrain' in str(e), str(e) else: assert False, 'a card that is all wall was packed' finally: shutil.rmtree(d) def test_cover_and_size_refusals_write_nothing(): @@ -308,11 +309,11 @@ def test_cover_and_size_refusals_write_nothing(): try: b = _toy(); pk = export.pack(b); c = b['cards'][3][2]; hole = c['alpha'].copy(); hole[:, 100:140] = 0; bad = [list(r) for r in pk['tiles']]; bad[3][2] = dict(bad[3][2], colour=export.encode_colour(c['albedo'], hole)); _refuses(d + '/hole', b, dict(pk, tiles=bad), 'a bake whose card leaves a hole was written') try: _write(d + '/hole', b, dict(pk, tiles=bad)) - except ValueError as e: assert 'tile 3' in str(e), str(e) + except export.Refusal as e: assert 'tile 3' in str(e), str(e) off = [list(r) for r in pk['tiles']]; off[7][0] = dict(off[7][0], top=H - 5); _refuses(d + '/off', b, dict(pk, tiles=off), 'a card leaving the frame was written') narrow = [list(r) for r in pk['tiles']]; c0 = b['cards'][2][0]; narrow[2][0] = dict(narrow[2][0], colour=export.encode_colour(c0['albedo'][:, 2:-2], c0['alpha'][:, 2:-2]), geometry=export.encode_geometry(c0['n_r'][:, 2:-2], c0['n_t'][:, 2:-2], c0['logd'][:, 2:-2], b['meta']['encoding'])); _refuses(d + '/apron', b, dict(pk, tiles=narrow), 'a tile without its apron was written') try: _write(d + '/apron', b, dict(pk, tiles=narrow)) - except ValueError as e: assert 'apron' in str(e), str(e) + except export.Refusal as e: assert 'apron' in str(e), str(e) mism = [list(r) for r in pk['tiles']]; mism[4][1] = dict(mism[4][1], geometry=export.encode_geometry(c0['n_r'][:50], c0['n_t'][:50], c0['logd'][:50], b['meta']['encoding'])); _refuses(d + '/size', b, dict(pk, tiles=mism), 'a colour and geometry of two sizes were written') _refuses(d + '/rows', b, pk, 'view plane_h disagreeing with the opaque view was written', view=dict(b['view'], plane_h=H + 1)); _refuses(d + '/short', b, dict(pk, tiles=pk['tiles'][:31]), 'a bake of 31 tiles was written') finally: shutil.rmtree(d) @@ -326,36 +327,36 @@ def test_card_cap_refusals(): for bad in ([5, 10, 20, 30, 40, 50], [6, 6], [6, 5], []): p = os.path.join(d, 'p.json'); json.dump(dict(presets=[dict(id='x', tz='UTC', card_split_km=bad)]), open(p, 'w')) # a valid zone, so only the splits can refuse it try: ridge.load_preset('x', p) - except ValueError: pass + except export.Refusal: pass else: assert False, ('a preset with splits', bad, 'was accepted') json.dump(dict(presets=[dict(id='x')]), open(os.path.join(d, 'q.json'), 'w')) try: ridge.load_preset('x', os.path.join(d, 'q.json')) - except ValueError: pass + except export.Refusal: pass else: assert False, 'a preset without card_split_km was defaulted' json.dump(dict(presets=[dict(id='x', tz='Europe/Vienna', card_split_km=[1, 2, 3, 4, 5])]), open(os.path.join(d, 'r.json'), 'w')); assert ridge.load_preset('x', os.path.join(d, 'r.json'))['card_split_km'] == [1, 2, 3, 4, 5] for bad_tz in (None, '', 'Not/AZone'): p = os.path.join(d, 'tz.json'); json.dump(dict(presets=[dict(id='x', card_split_km=[6], **({} if bad_tz is None else dict(tz=bad_tz)))]), open(p, 'w')) try: ridge.load_preset('x', p) - except ValueError: pass + except export.Refusal: pass else: assert False, ('a preset with tz', bad_tz, 'was accepted') place = dict(id='synthetic', name='S', lat=0.0, lon=0.0, altitude_km=0.0, eye_m=1.0, tz='UTC'); meta = dict(curvature=dict(r_earth_m=1.0, k_ref=0.1), encoding=dict(log_d_min=0.0, log_d_max=1.0)); view = dict(look_az_deg=0.0, plane_h=H, px_per_deg_h=1.0, px_per_deg_v=1.0, exaggeration=1.0, horizon_row=1.0, sky_row=1.0, near_row=1.0) full = [np.ones((H, 204)) for _ in range(32)]; cards = lambda k: [dict(near_m=None if i == 0 else 1.0, far_m=None if i == k - 1 else 1.0) for i in range(k)]; cam = dict(r_max_m=100.0, r_max_forward_m=100.0) big = dict(cards=cards(6), tiles=[[_flat_entry(0, H, seed=0)] + [_flat_entry(0, H) for _ in range(5)] for _ in range(32)], camera=cam) try: export.write_bake(d + '/big', place, view, meta, big, full) - except ValueError as e: assert 'consecutive tiles' in str(e), str(e) + except export.Refusal as e: assert 'consecutive tiles' in str(e), str(e) else: assert False, 'six full-frame cards in every tile were written' assert not os.path.exists(d + '/big') ok = dict(cards=cards(6), tiles=[[_flat_entry(0, H, seed=0)] + [_flat_entry(0, 100, seed=i) for i in range(1, 6)] for _ in range(32)], camera=cam); dest = export.write_bake(d + '/six', place, view, meta, ok, full); assert len(json.load(open(dest / 'manifest.json'))['cards']) == 6 fwd = lambda r: dict(ok, camera=dict(r_max_m=100.0, r_max_forward_m=r)); bands6 = [[H] + [100] * 5] * 32; assert export.resident_bytes(bands6, export.run_tiles(100.0, 1000.0)) <= export.RESIDENT_BYTES_MAX < export.resident_bytes(bands6, export.run_tiles(1e6, 1000.0)), 'the fixture cannot tell the gate at r_max_forward_m from the gate at r_max_m' try: export.write_bake(d + '/fwd', place, view, meta, fwd(1e6), full) - except ValueError as e: assert 'consecutive tiles' in str(e), str(e) + except export.Refusal as e: assert 'consecutive tiles' in str(e), str(e) else: assert False, 'a bake whose forward offset breaks the resident gate was written' try: export.write_bake(d + '/low', place, view, meta, fwd(50.0), full) - except ValueError as e: assert 'below r_max_m' in str(e), str(e) + except export.Refusal as e: assert 'below r_max_m' in str(e), str(e) else: assert False, 'a bake whose forward offset is below the worst-case offset was written' assert not os.path.exists(d + '/fwd') and not os.path.exists(d + '/low') try: export.check_budget(7, [1000] * 32, [[10] * 7] * 32, 100.0, 1000.0) - except ValueError as e: assert 'above 6' in str(e) + except export.Refusal as e: assert 'above 6' in str(e) else: assert False, '7 cards were accepted' finally: shutil.rmtree(d) def test_budgets(): @@ -363,7 +364,7 @@ def test_budgets(): none = [[] for _ in range(export.TILES)]; call = lambda tb, bands, r=100.0, rmin=1000.0: export.check_budget(3, tb, bands, r, rmin) def refused(*a, **k): try: call(*a, **k) - except ValueError: return True + except export.Refusal: return True return False assert not refused([235_000] + [0] * 31, none) and refused([235_001] + [0] * 31, none), 'the tile cap' assert not refused([234_375] * 32, none) and refused([234_375] * 31 + [234_376], none), 'the place cap' @@ -402,11 +403,11 @@ def test_r_max(): held_f = export.solve_r_max(dist2, heavy, ppd, phis=1); assert held_f >= held and export.resident_bytes(heavy, export.run_tiles(held_f, 20000.0)) <= export.RESIDENT_BYTES_MAX < export.resident_bytes(heavy, export.run_tiles(held_f + 1.0, 20000.0)), ('the resident gate does not bind the forward offset', held_f, held) two = [[5000.0, 40.0 if t == 7 else 5000.0] for t in range(32)] try: export.solve_r_max(two, [[100, 100] for _ in range(32)], ppd) - except ValueError as e: assert 'below 25' in str(e) and 'card 1' in str(e) and 'tile 7' in str(e), str(e) + except export.Refusal as e: assert 'below 25' in str(e) and 'card 1' in str(e) and 'tile 7' in str(e), str(e) else: assert False, 'a bake whose r_max_m is below 25 was accepted' close = [[30.0] for _ in range(32)] try: export.solve_r_max(close, bands, ppd) - except ValueError as e: assert 'below 25' in str(e) and 'card 0' in str(e), str(e) + except export.Refusal as e: assert 'below 25' in str(e) and 'card 0' in str(e), str(e) else: assert False, 'a nearest card at 30 m was accepted' finally: export.FIT_PX_MAX, export.PHI_STEPS = saved def test_pack_distance_and_r_max_in_the_bake(): @@ -541,7 +542,7 @@ def test_the_near_clip_compare_does_not_depend_on_float32_rounding(): for clip in (500.0, 520.0, 700.0): ridge.NEAR_CLIP_M = clip; b = _toy(dists=(clip, 15000.0, 50000.0), amp=0.0); pk = export.pack(b); assert pk['tiles'][0][0]['distance_m'] != 0 try: dest = _write(d + f'/ok{clip:g}', b, pk) - except ValueError as e: assert 'near clip' not in str(e), ('a card 0 at the near clip was refused', clip, str(e)); raise + except export.Refusal as e: assert 'near clip' not in str(e), ('a card 0 at the near clip was refused', clip, str(e)); raise assert dest.exists(), ('a card 0 at the near clip was refused', clip) b = _toy(dists=(698.9, 15000.0, 50000.0), amp=0.0); ridge.NEAR_CLIP_M = 700.0; _refuses(d + '/under', b, export.pack(b), 'a card 0 under the near clip was written') finally: ridge.NEAR_CLIP_M = saved; shutil.rmtree(d) @@ -551,7 +552,7 @@ def test_set_view_keeps_the_ground_rows_under_the_horizon(): assert ridge.GROUND_ROWS_MIN == 150 and ridge.E_MIN == 0.5 and ridge.NEAR_CLIP_M == 500.0, 'the authored constants are pinned' sk = np.full(W, 5.0); sk[100] = 60.0 try: ridge.set_view(sk) - except ValueError as e: + except export.Refusal as e: if 'under the horizon' not in str(e): raise # not the refusal: a crash assert '60.00' in str(e) and '8.89' in str(e) and '0.5x' in str(e), str(e) else: assert False, 'a skyline that cannot hold the ground rows was accepted' @@ -568,12 +569,12 @@ def test_the_near_clip_and_the_ground_rows_are_refused_at_the_writer(): try: b = _toy(); pk = export.pack(b); near = export.pack(_toy(dists=(300.0, 15000.0, 50000.0))); assert near['report']['nearest_m'] < ridge.NEAR_CLIP_M try: _write(d + '/near', b, near) - except ValueError as e: assert 'near clip' in str(e), str(e); assert not os.path.exists(d + '/near') + except export.Refusal as e: assert 'near clip' in str(e), str(e); assert not os.path.exists(d + '/near') else: assert False, 'a bake whose card 0 stands inside the near clip was written' _refuses(d + '/short', b, pk, 'a plane with 149 rows under the horizon was written', view=dict(b['view'], horizon_row=451.0)); dest = _write(d + '/ok', b, pk, view=dict(b['view'], horizon_row=450.0)); m = json.load(open(dest / 'manifest.json')); export.validate_manifest(m) m['view']['horizon_row'] = 450.5 try: export.validate_manifest(m) - except ValueError as e: assert 'GROUND_ROWS_MIN' in str(e), str(e) + except export.Refusal as e: assert 'GROUND_ROWS_MIN' in str(e), str(e) else: assert False, 'validate_manifest accepted a short plane' finally: shutil.rmtree(d) # ---------------------------------------------------------------------------------------- the near ground: the place's own terrain under the clip, drawn by card 0 inside the clip's silhouette @@ -630,7 +631,7 @@ def test_cards_refuses_a_march_without_the_near_ground(): """ridge.cards on a march whose first sample is the near clip (not joined to the near march) raises, naming join_near: card 0 can never extrude the clip sample again.""" A, Hh = rays(THREE); ridge.P.update(eye_m=EYE); ridge.set_view(A.max(0)) try: ridge.cards(D, _w(A), _w(Hh), np.zeros((0, NW))) - except ValueError as e: assert 'join_near' in str(e), str(e) + except export.Refusal as e: assert 'join_near' in str(e), str(e) else: assert False, 'cards drew a march that starts at the near clip' def test_near_march_starts_at_your_feet(): """The near march starts at NEAR_START_M = 1 m, strictly increasing in steps of max(1 m, 0.02 d) up to 10 m, its last sample under the clip; over flat ground with a 1.6 m eye and a frame bottom below -8 degrees (the ray of the frame bottom meets the ground 11 m out) card 0 has no wall row and draws the ground to the bottom row."""