"""How many shade masks are actually NEW each frame? tools/shade_study.py costs a per-pixel shade mask as though every distinct 8x8 mask were DMA'd fresh every frame. That is the worst case, and it is the opposite of how this encoder works: it keeps a global tile store in ROM and reuses from it, serving roughly 55 cells a frame from reuse against about 8 genuinely new tiles. A face in a stable shot hardly changes, so its masks ought to persist too. This walks consecutive frames inside single shots, keeps the set of masks seen so far, and reports how many are new per frame once the shot has settled - the number that decides whether the technique is affordable, since only new masks cost a DMA. python tools/mask_reuse.py out/frame_scan.npz fields --shots 6 --run 24 """ from __future__ import annotations import argparse import json import sys from pathlib import Path import numpy as np ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) sys.path.insert(0, str(ROOT / "tools")) from rrmd.codebook import DESCRIPTOR_CYCLES, TILE_DMA_CYCLES, VBLANK_BUDGET_CYCLES # noqa: E402 from rrmd.encode import load_picture # noqa: E402 from rrmd.vdp import CELLS_X, CELLS_Y, TILE # noqa: E402 from shade_study import measure # noqa: E402 SPRITE_TABLE_CYCLES = 640 / 2 * 4.78 def box_cells(box: np.ndarray) -> tuple[int, int, int, int]: x, y, w, h = (int(v) for v in box) return (max(0, y // TILE), min(CELLS_Y, -(-(y + h) // TILE)), max(0, x // TILE), min(CELLS_X, -(-(x + w) // TILE))) # fmt: skip def masks_in(mask_of: np.ndarray, region: tuple[int, int, int, int] | None) -> set[bytes]: cy0, cy1, cx0, cx1 = region if region else (0, CELLS_Y, 0, CELLS_X) out: set[bytes] = set() for cy in range(cy0, cy1): for cx in range(cx0, cx1): m = mask_of[cy, cx] if m.min() != m.max(): out.add(m.tobytes()) return out def main(argv: list[str] | None = None) -> int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("scan", type=Path) ap.add_argument("fields", type=Path) ap.add_argument("--summary", type=Path, default=Path("out/full/summary.json")) ap.add_argument("--shots", type=int, default=6, help="how many shots to walk") ap.add_argument("--run", type=int, default=24, help="consecutive frames per shot") ap.add_argument("--settle", type=int, default=4, help="frames to ignore at a shot's start") ap.add_argument("--seed", type=int, default=3) args = ap.parse_args(argv) scan = dict(np.load(args.scan, allow_pickle=False)) names, n_faces, boxes = scan["names"], scan["n_faces"], scan["boxes"] shots = sorted(json.loads(args.summary.read_text())["shots"]) # shots long enough to hold a run, and preferring ones with faces in them usable = [] for a, b in zip(shots, shots[1:] + [len(names)]): if b - a >= args.run: faces = int((n_faces[a:b] > 0).sum()) usable.append((a, b, faces)) usable.sort(key=lambda t: -t[2]) rng = np.random.default_rng(args.seed) pick = usable[: max(args.shots * 2, 1)] chosen = [pick[i] for i in rng.choice(len(pick), min(args.shots, len(pick)), replace=False)] chosen.sort() print(f"{len(chosen)} shots of {args.run} frames (ignoring the first {args.settle} of each)") whole_new, face_new, face_tot = [], [], [] for start, end, faces in chosen: seen_w: set[bytes] = set() seen_f: set[bytes] = set() per_w, per_f = [], [] for k in range(args.run): i = start + k rgb = load_picture(args.fields / str(names[i])) m = measure(rgb) mw = masks_in(m["masks"], None) new_w = len(mw - seen_w) seen_w |= mw region = box_cells(boxes[i, 0]) if n_faces[i] > 0 else None mf = masks_in(m["masks"], region) if region else set() new_f = len(mf - seen_f) seen_f |= mf if k >= args.settle: per_w.append(new_w) per_f.append(new_f) if region: face_tot.append(len(mf)) whole_new += per_w face_new += per_f print(f" shot at {start:5d} ({faces:3d} frames with a face): new masks/frame " f"whole {np.mean(per_w):6.1f} face box {np.mean(per_f):5.1f}") w = np.array(whole_new, dtype=np.float64) f = np.array(face_new, dtype=np.float64) print("\n" + "=" * 74) print("NEW masks per frame once a shot has settled (only these cost a DMA)") print("=" * 74) for label, a in (("whole frame", w), ("face box", f)): if not len(a): continue cyc = a * (DESCRIPTOR_CYCLES + TILE_DMA_CYCLES) print(f"{label:<12} mean {a.mean():6.1f} median {np.median(a):6.1f} p95 {np.percentile(a, 95):6.1f} " f"max {a.max():5.0f}") print(f"{'':12} -> VBlank cycles mean {cyc.mean():8,.0f} p95 {np.percentile(cyc, 95):8,.0f}" f" = {100 * cyc.mean() / VBLANK_BUDGET_CYCLES:5.1f}% / " f"{100 * np.percentile(cyc, 95) / VBLANK_BUDGET_CYCLES:5.1f}% of the budget") if len(f) and face_tot: print(f"\nface box holds {np.mean(face_tot):.1f} masks on average, of which {f.mean():.1f} are new: " f"{100 * (1 - f.mean() / max(np.mean(face_tot), 1e-9)):.0f}% come from reuse") add = f * (DESCRIPTOR_CYCLES + TILE_DMA_CYCLES) + SPRITE_TABLE_CYCLES print(f"face-only with sprites, including the sprite table: mean " f"{add.mean():,.0f} cycles ({100 * add.mean() / VBLANK_BUDGET_CYCLES:.1f}% of budget), " f"p95 {np.percentile(add, 95):,.0f}") return 0 if __name__ == "__main__": raise SystemExit(main())