ridge-bake: bake_id addresses the whole bake, the manifest as written (its id blanked) and then the tile files, so a manifest change is a new directory
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
fa2e216039
commit
fcfa26c2bc
3 changed files with 21 additions and 13 deletions
|
|
@ -171,14 +171,16 @@ def solve_r_max(dist, bands, px_per_deg, phis=None):
|
|||
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}')
|
||||
return r_max
|
||||
|
||||
def bake_id(files):
|
||||
"""First 12 hex of sha256 over the tile files, tile-major then card, colour then geometry (a null card tile writes none). files: [(colour bytes, geometry bytes)] in that order."""
|
||||
h = hashlib.sha256()
|
||||
BAKE_ID_BLANK = '0' * 12
|
||||
def bake_id(manifest_text, files):
|
||||
"""First 12 hex of sha256 over the whole bake: the manifest.json text as written with its bake_id value BAKE_ID_BLANK (the id cannot hash itself), then the tile files, tile-major then card, colour then geometry (a null card tile writes none), so any change to the manifest or a tile is a new directory.
|
||||
files: [(colour bytes, geometry bytes)] in that order."""
|
||||
h = hashlib.sha256(); h.update(manifest_text.encode('utf-8'))
|
||||
for colour, geometry in files: h.update(colour); h.update(geometry)
|
||||
return h.hexdigest()[:12]
|
||||
|
||||
def write_bake(out, place, view, meta, packed, opaque, default=None):
|
||||
"""Write out/<place>-<bake_id>/ (tile WebPs + manifest.json), rewrite out/index.json, delete the place's previous dir. packed: dict(cards [dict(near_m, far_m)], tiles [TILES][cards] of dict(top, colour bytes, geometry bytes, distance_m) or None,
|
||||
"""Write out/<place>-<bake_id>/ (tile WebPs + manifest.json; the id addresses both), rewrite out/index.json, delete the place's previous dir. packed: dict(cards [dict(near_m, far_m)], tiles [TILES][cards] of dict(top, colour bytes, geometry bytes, distance_m) or None,
|
||||
camera dict(r_max_m, r_max_forward_m)); opaque: TILES arrays (plane_h, TILE_W + 2 APRON), each the opaque view's coverage over a tile's columns. Refuses before writing a bake whose files decode to the wrong size, leave the frame, break a budget (the resident gate at r_max_m and at r_max_forward_m) or composite
|
||||
away from the opaque view in any tile. meta: dict(curvature, encoding). Returns the directory."""
|
||||
cards, tiles, camera = packed['cards'], packed['tiles'], packed['camera']; k = len(cards); h = view['plane_h']; w = TILE_W + 2 * APRON
|
||||
|
|
@ -201,16 +203,18 @@ def write_bake(out, place, view, meta, packed, opaque, default=None):
|
|||
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}')
|
||||
bid = bake_id([(e['colour'], e['geometry']) for row in tiles for e in row if e]); name = f"{place['id']}-{bid}"; out = Path(out); dest = out / name
|
||||
manifest = dict(schema=3, baker_version=BAKER_VERSION, bake_id=bid, 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']),
|
||||
out = Path(out)
|
||||
manifest = dict(schema=3, baker_version=BAKER_VERSION, bake_id=BAKE_ID_BLANK, place=place, view=dict(view, ring_w=RING_W, tile_w=TILE_W, tiles=TILES, apron=APRON), curvature=meta['curvature'], encoding=dict(meta['encoding'], normal='rt8'), camera=dict(r_max_m=camera['r_max_m'], r_max_forward_m=camera['r_max_forward_m']),
|
||||
cards=[dict(near_m=c['near_m'], far_m=c['far_m']) for c in cards],
|
||||
tiles=[[None if e is None else dict(top=e['top'], h=pair[0].shape[0], distance_m=e['distance_m'], colour=dict(file=tile_file(i, t, 'colour'), bytes=len(e['colour'])), geometry=dict(file=tile_file(i, t, 'geometry'), bytes=len(e['geometry'])))
|
||||
for i, (e, pair) in enumerate(zip(row, drow))] for t, (row, drow) in enumerate(zip(tiles, dec))], bytes=sum(tile_bytes), attribution=ATTRIBUTION)
|
||||
validate_manifest(manifest); out.mkdir(parents=True, exist_ok=True); tmp = Path(tempfile.mkdtemp(dir=out, prefix='.bake-'))
|
||||
validate_manifest(manifest); text = json.dumps(manifest, indent=1) + '\n'; blank = f'"bake_id": "{BAKE_ID_BLANK}"'; assert text.count(blank) == 1
|
||||
bid = bake_id(text, [(e['colour'], e['geometry']) for row in tiles for e in row if e]); name = f"{place['id']}-{bid}"; dest = out / name; text = text.replace(blank, f'"bake_id": "{bid}"')
|
||||
out.mkdir(parents=True, exist_ok=True); tmp = Path(tempfile.mkdtemp(dir=out, prefix='.bake-'))
|
||||
for t, row in enumerate(tiles):
|
||||
for i, e in enumerate(row):
|
||||
if e: (tmp / tile_file(i, t, 'colour')).write_bytes(e['colour']); (tmp / tile_file(i, t, 'geometry')).write_bytes(e['geometry'])
|
||||
(tmp / 'manifest.json').write_text(json.dumps(manifest, indent=1) + '\n')
|
||||
(tmp / 'manifest.json').write_text(text)
|
||||
idx_path = out / 'index.json'; idx = json.loads(idx_path.read_text()) if idx_path.exists() else dict(schema=1, default=place['id'], places={})
|
||||
old = idx['places'].get(place['id']); idx['places'][place['id']] = name; idx['default'] = default or (idx['default'] if idx['default'] in idx['places'] else place['id'])
|
||||
validate(idx, SCHEMA['$defs']['index'])
|
||||
|
|
|
|||
|
|
@ -35,7 +35,9 @@ MUTANTS = { # name -> (text in ridge.py or export.py, replacement)
|
|||
'tile: the apron is shifted (a tile starts at its own first column)': ("ridge.ring_cols(x, t * TILE_W - APRON, TILE_W + 2 * APRON)", "ridge.ring_cols(x, t * TILE_W, TILE_W + 2 * APRON)"),
|
||||
'tile: the seams are cut from tile 0 for every tile': ("cols(sm, t), tuple(cols(x, t) for x in nrm)", "cols(sm, 0), tuple(cols(x, t) for x in nrm)"),
|
||||
'view: the vertical anchors read the first 72 degrees only (the old window)': ("sk = np.asarray(skyline); sky", "sk = np.asarray(skyline)[:1280]; sky"),
|
||||
'bake_id: card-major instead of tile-major': ("bake_id([(e['colour'], e['geometry']) for row in tiles for e in row if e])", "bake_id([(row[i]['colour'], row[i]['geometry']) for i in range(k) for row in tiles if row[i]])"),
|
||||
'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 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"),
|
||||
|
|
|
|||
|
|
@ -244,10 +244,12 @@ def test_manifest_v3_writer():
|
|||
d = tempfile.mkdtemp()
|
||||
try:
|
||||
b = _toy(); pk = export.pack(b); pk2 = export.pack(b); files = lambda p: [(e['colour'], e['geometry']) for row in p['tiles'] for e in row if e]; assert files(pk) == files(pk2), 'two packs gave different bytes'
|
||||
a = _write(d + '/a', b, pk); assert a.name == 'toy-' + export.bake_id(files(pk)) and sorted(os.listdir(d + '/a')) == sorted(['index.json', a.name]); m = json.load(open(a / 'manifest.json')); export.validate_manifest(m)
|
||||
import hashlib; want = hashlib.sha256(b''.join(c + g for c, g in files(pk))).hexdigest()[:12]; assert export.bake_id(files(pk)) == want, 'bake_id is not the sha256 of the tile files, tile-major then card, colour then geometry'
|
||||
assert export.bake_id([(g, c) for c, g in files(pk)]) != want and export.bake_id(files(pk)[::-1]) != want and export.bake_id([f for i, f in enumerate(files(pk)) if i % 3 != 1] + [f for i, f in enumerate(files(pk)) if i % 3 == 1]) != want, 'bake_id ignores the file order'
|
||||
pk3 = [list(f) for f in files(pk)]; pk3[40][1] += b'x'; assert export.bake_id([tuple(f) for f in pk3]) != want, 'a changed byte kept the bake_id'
|
||||
a = _write(d + '/a', b, pk); m = json.load(open(a / 'manifest.json')); export.validate_manifest(m); text = open(a / 'manifest.json', encoding='utf-8').read(); blank = text.replace(f'"bake_id": "{m["bake_id"]}"', f'"bake_id": "{export.BAKE_ID_BLANK}"'); assert blank != text and a.name == 'toy-' + m['bake_id'] and sorted(os.listdir(d + '/a')) == sorted(['index.json', a.name])
|
||||
import hashlib; want = hashlib.sha256(blank.encode() + b''.join(c + g for c, g in files(pk))).hexdigest()[:12]; assert m['bake_id'] == want and export.bake_id(blank, files(pk)) == want, 'bake_id is not the sha256 of the manifest with its id blanked, then the tile files tile-major, then card, colour then geometry'
|
||||
assert export.bake_id(blank, [(g, c) for c, g in files(pk)]) != want and export.bake_id(blank, files(pk)[::-1]) != want and export.bake_id(blank, [f for i, f in enumerate(files(pk)) if i % 3 != 1] + [f for i, f in enumerate(files(pk)) if i % 3 == 1]) != want, 'bake_id ignores the file order'
|
||||
pk3 = [list(f) for f in files(pk)]; pk3[40][1] += b'x'; assert export.bake_id(blank, [tuple(f) for f in pk3]) != want, 'a changed byte kept the bake_id'
|
||||
assert export.bake_id(blank.replace('"r_max_forward_m"', '"r_max_forward_m "', 1), files(pk)) != want and export.bake_id(blank + ' ', files(pk)) != want, 'a changed manifest kept the bake_id'
|
||||
pk4 = dict(pk, camera=dict(pk['camera'], r_max_forward_m=pk['camera']['r_max_forward_m'] + 0.1)); a4 = _write(d + '/d', b, pk4); assert a4.name != a.name and [(e['colour'], e['geometry']) for row in pk4['tiles'] for e in row if e] == files(pk), 'a manifest moved under the same bake id (tile bytes identical, camera differs)'
|
||||
assert m['cards'][0]['near_m'] is None and m['cards'][-1]['far_m'] is None and m['cards'][0]['far_m'] == m['cards'][1]['near_m'] and len(m['cards']) == 3
|
||||
for t, row in enumerate(m['tiles']):
|
||||
for i, e in enumerate(row):
|
||||
|
|
|
|||
Loading…
Reference in a new issue