"""Does per-pixel 3-level shadow/highlight earn its keep? Measured, per frame. The quality question is asked per frame and per stratum, never as a single mean: a technique that wins 20 % on a few frames and loses 8 % on many is not an improvement, and a mean hides exactly that. So this reports mean, median, the worst regression and the share of frames improved, for stable shots, close-up faces, dark scenes, shot transitions and a random control - and tracks error inside the detected face boxes alongside whole-frame error, because that is where the user says detail is missing. The cost question is asked in the same units the encoder already budgets in. Choosing a shade per pixel needs a mask at pixel resolution, which the hardware can only get from a second layer's priority bits plus sprite operators, so the cost counted here is: how many cells actually need a non-uniform mask, how many distinct 8x8 masks that is (the mask layer's tile count), the DMA bytes and VBlank cycles those add against the player's 40,000-cycle budget, and what that does to the window in which the Z80 may not touch the cartridge. python tools/shade_study.py out/frame_scan.npz fields --per-stratum 40 """ from __future__ import annotations import argparse import sys from pathlib import Path import numpy as np ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) from rrmd.codebook import DESCRIPTOR_CYCLES, TILE_DMA_CYCLES, VBLANK_BUDGET_CYCLES # noqa: E402 from rrmd.encode import _cells, _weighted_dist, fit_region, load_picture # noqa: E402 from rrmd.vdp import CELLS_X, CELLS_Y, HIGHLIGHT, NORMAL, SHADOW, TILE, raw_to_rgb # noqa: E402 NAMETABLE_BYTES = 2 * 64 * CELLS_Y # a second plane's table, as plane A's is DMA'd now def measure(rgb: np.ndarray) -> dict: """Per-cell error for the scheme as built and with a per-pixel shade, plus the masks the latter would need. One fit, shared, so the comparison is like for like; the 3-level figure reuses the lines fitted for the per-cell scheme, which makes it a floor on the gain rather than a best case (a refit would do better).""" lines, line_of, shade_of, _pens, _history = fit_region(rgb) cells = _cells(rgb) base = np.zeros((CELLS_Y, CELLS_X)) three = np.zeros((CELLS_Y, CELLS_X)) masks: dict[bytes, int] = {} mask_of = np.zeros((CELLS_Y, CELLS_X, TILE, TILE), np.uint8) non_uniform = 0 for cy in range(CELLS_Y): for cx in range(CELLS_X): line = lines[line_of[cy, cx]] cell = cells[cy, cx] pal1 = raw_to_rgb(line, int(shade_of[cy, cx])) base[cy, cx] = _weighted_dist(cell, pal1).min(axis=-1).sum() pal3 = np.concatenate([raw_to_rgb(line, s) for s in (NORMAL, SHADOW, HIGHLIGHT)]) d3 = _weighted_dist(cell, pal3) pick = d3.argmin(axis=-1) three[cy, cx] = np.take_along_axis(d3, pick[..., None], -1).sum() shade_mask = (pick // 16).astype(np.uint8) mask_of[cy, cx] = shade_mask if shade_mask.min() != shade_mask.max(): non_uniform += 1 key = shade_mask.tobytes() masks[key] = masks.get(key, 0) + 1 return {"base": base, "three": three, "non_uniform": non_uniform, "distinct_masks": len(masks), "masks": mask_of} # fmt: skip def region_error(err: np.ndarray, box: np.ndarray) -> tuple[float, int]: """Total error and pixel count over the cells a pixel box covers.""" x, y, w, h = (int(v) for v in box) cx0, cy0 = max(0, x // TILE), max(0, y // TILE) cx1 = min(CELLS_X, -(-(x + w) // TILE)) cy1 = min(CELLS_Y, -(-(y + h) // TILE)) if cx1 <= cx0 or cy1 <= cy0: return 0.0, 0 sub = err[cy0:cy1, cx0:cx1] return float(sub.sum()), sub.size * TILE * TILE def region_masks(mask_of: np.ndarray, box: np.ndarray) -> tuple[int, int]: """Distinct masks and non-uniform cells inside one pixel box. The global scheme is unaffordable, so the question becomes whether the technique is affordable where it is worth most. A box costs only its own cells' masks, and sprites carry the operator without a second name table, so this is the cost that decides a face-only variant. """ x, y, w, h = (int(v) for v in box) cx0, cy0 = max(0, x // TILE), max(0, y // TILE) cx1 = min(CELLS_X, -(-(x + w) // TILE)) cy1 = min(CELLS_Y, -(-(y + h) // TILE)) if cx1 <= cx0 or cy1 <= cy0: return 0, 0 seen: set[bytes] = set() non_uniform = 0 for cy in range(cy0, cy1): for cx in range(cx0, cx1): m = mask_of[cy, cx] if m.min() != m.max(): non_uniform += 1 seen.add(m.tobytes()) return len(seen), non_uniform def strata(scan: dict, shots: set[int], n: int, seed: int) -> dict[str, np.ndarray]: """Frame indices per stratum: stable, face close-up, dark, transition, control.""" luma, diff, boxes, n_faces = scan["luma"], scan["diff"], scan["boxes"], scan["n_faces"] total = len(luma) idx = np.arange(total) is_shot = np.zeros(total, bool) for s in shots: if 0 <= s < total: is_shot[s] = True near_shot = np.convolve(is_shot, np.ones(9), mode="same") > 0 area = boxes[:, 0, 2] * boxes[:, 0, 3] quiet = diff < np.percentile(diff, 35) dark = luma < np.percentile(luma, 12) pools = { "stable": idx[quiet & ~near_shot & ~dark], "face close-up": idx[(n_faces > 0) & (area > 48 * 48)], "dark": idx[dark & ~near_shot], "transition": idx[is_shot], "control": idx, } rng = np.random.default_rng(seed) out = {} for name, pool in pools.items(): if len(pool) == 0: print(f"warning: stratum {name!r} is empty") continue take = min(n, len(pool)) out[name] = np.sort(rng.choice(pool, take, replace=False)) return out def report(name: str, rows: list[dict]) -> None: whole = np.array([100 * (1 - r["three_total"] / r["base_total"]) for r in rows]) print(f"\n{name} (n={len(rows)})") print(f" whole frame mean {whole.mean():+6.2f}% median {np.median(whole):+6.2f}% " f"worst {whole.min():+6.2f}% improved {100 * (whole > 0).mean():5.1f}% of frames") faces = [r for r in rows if r["face_pixels"]] if faces: f = np.array([100 * (1 - r["face_three"] / r["face_base"]) for r in faces if r["face_base"] > 0]) if len(f): print(f" face region mean {f.mean():+6.2f}% median {np.median(f):+6.2f}% " f"worst {f.min():+6.2f}% improved {100 * (f > 0).mean():5.1f}% of {len(f)} frames") nu = np.array([r["non_uniform"] for r in rows]) dm = np.array([r["distinct_masks"] for r in rows]) print(f" cost cells needing a mask {nu.mean():6.1f} of {CELLS_X * CELLS_Y} " f"({100 * nu.mean() / (CELLS_X * CELLS_Y):.0f}%) distinct masks/frame {dm.mean():6.1f} " f"(max {dm.max()})") def encode_cycles(log: Path) -> dict[int, int]: """Per-frame VBlank cycles the current encode actually spends, from encode.log. The mask layer's cost only matters relative to what each frame already uses: the budget binds at the peaks, not the mean, so a technique is affordable only if frame + mask stays under VBLANK_BUDGET_CYCLES on the expensive frames too. """ import re pat = re.compile(r"^frame\s+(\d+) .* cyc\s+(\d+) ") out: dict[int, int] = {} if not log.exists(): return out for line in log.read_text().splitlines(): m = pat.match(line) if m: out[int(m[1])] = int(m[2]) return out def added_cycles(distinct_masks: float) -> float: """VBlank cycles the mask layer adds: its tiles, plus a second name table.""" return distinct_masks * (DESCRIPTOR_CYCLES + TILE_DMA_CYCLES) + NAMETABLE_BYTES / 2 * 4.78 def efficiency(rows: list[dict], cyc: dict[int, int]) -> None: """Quality won against resource spent, per frame, and what it does to the peaks. The two are not in the same units, so no single number settles it; the ratio below is read as "percent of error removed per percent of the VBlank budget spent", which is at least monotone in both and comparable between techniques. """ pct = np.array([100 * (1 - r["three_total"] / r["base_total"]) for r in rows]) add = np.array([added_cycles(r["distinct_masks"]) for r in rows]) spend = 100 * add / VBLANK_BUDGET_CYCLES ratio = pct / spend print("\n" + "=" * 78) print("QUALITY WON PER RESOURCE SPENT") print("=" * 78) print(f"error removed : mean {pct.mean():+6.2f}% median {np.median(pct):+6.2f}%") print(f"VBlank budget spent : mean {spend.mean():6.2f}% median {np.median(spend):6.2f}%") print(f"ratio (removed/spent) : mean {ratio.mean():6.2f} median {np.median(ratio):6.2f} " f"worst {ratio.min():6.2f}") print(" (above 1.0 means more error removed than budget consumed, in percent terms)") have = [r for r in rows if r["frame"] in cyc] if have: now = np.array([cyc[r["frame"]] for r in have], dtype=np.float64) then = now + np.array([added_cycles(r["distinct_masks"]) for r in have]) over = then > VBLANK_BUDGET_CYCLES print(f"\nagainst what each frame already spends (n={len(have)} matched to encode.log):") print(f" current cycles : mean {now.mean():9,.0f} p95 {np.percentile(now, 95):9,.0f} max {now.max():9,.0f}") print(f" with the mask : mean {then.mean():9,.0f} p95 {np.percentile(then, 95):9,.0f} max {then.max():9,.0f}") print(f" frames over the {VBLANK_BUDGET_CYCLES:,}-cycle budget: {int(over.sum())} of {len(have)} " f"({100 * over.mean():.0f}%)") if over.any(): print(" those frames cannot have the mask at all: the encoder would have to raise") print(" their tolerance instead, trading the gain back for worse quality at cuts.") def face_only(rows: list[dict], cyc: dict[int, int]) -> None: """The variant the global numbers leave open: the mask over the face box alone. Sprites are the highlight operator, so a box needs no second name table - only its own mask tiles and the sprite table. A face is also small enough to stay inside the per-line sprite limits, which a full-screen overlay cannot. """ have = [r for r in rows if r.get("face_cells") and r["face_base"] > 0] if not have: print() print("no face boxes in the sample: cannot size the face-only variant") return gain = np.array([100 * (1 - r["face_three"] / r["face_base"]) for r in have]) tiles = np.array([r["face_masks"] for r in have], dtype=np.float64) add = tiles * (DESCRIPTOR_CYCLES + TILE_DMA_CYCLES) + 640 / 2 * 4.78 # sprite table, no plane spend = 100 * add / VBLANK_BUDGET_CYCLES print() print("=" * 78) print("FACE-ONLY VARIANT: the mask over the detected face box, carried by sprites") print("=" * 78) print(f"frames with a face box in the sample: {len(have)}") print(f"mask tiles for the box : mean {tiles.mean():6.1f} p95 {np.percentile(tiles, 95):6.1f} max {tiles.max():.0f}") print(f"face-region error removed : mean {gain.mean():+6.2f}% median {np.median(gain):+6.2f}% worst {gain.min():+6.2f}%") print(f"VBlank budget spent : mean {spend.mean():6.2f}% p95 {np.percentile(spend, 95):6.2f}%") print(f"ratio (removed/spent) : mean {(gain / spend).mean():6.2f} median {np.median(gain / spend):6.2f}") matched = [r for r in have if r["frame"] in cyc] if matched: now = np.array([cyc[r["frame"]] for r in matched], dtype=np.float64) then = now + np.array([r["face_masks"] for r in matched]) * (DESCRIPTOR_CYCLES + TILE_DMA_CYCLES) + 640 / 2 * 4.78 print() print(f"with what those frames already spend (n={len(matched)}):") print(f" current : mean {now.mean():9,.0f} p95 {np.percentile(now, 95):9,.0f} max {now.max():9,.0f}") print(f" with it : mean {then.mean():9,.0f} p95 {np.percentile(then, 95):9,.0f} max {then.max():9,.0f}") print(f" frames over budget: {int((then > VBLANK_BUDGET_CYCLES).sum())} of {len(matched)} " f"({100 * (then > VBLANK_BUDGET_CYCLES).mean():.0f}%)") def cost_model(all_rows: list[dict]) -> None: """What the mask layer costs in the player's own budget units.""" dm = np.array([r["distinct_masks"] for r in all_rows], dtype=np.float64) nu = np.array([r["non_uniform"] for r in all_rows], dtype=np.float64) print("\n" + "=" * 78) print("COST of a per-pixel shade mask, in the player's budget units") print("=" * 78) print(f"mask tiles needed per frame: mean {dm.mean():.1f}, p95 {np.percentile(dm, 95):.1f}, " f"max {dm.max():.0f}") # Worst case: every mask tile is a fresh DMA with its own descriptor. tile_cycles = dm * (DESCRIPTOR_CYCLES + TILE_DMA_CYCLES) table_cycles = NAMETABLE_BYTES / 2 * 4.78 # a word per two bytes, blanking rate total = tile_cycles + table_cycles print(f"\nVBlank cycles added (budget {VBLANK_BUDGET_CYCLES:,}):") print(f" mask tile DMA + descriptors : mean {tile_cycles.mean():9,.0f} p95 {np.percentile(tile_cycles, 95):9,.0f}") print(f" second plane's name table : {table_cycles:9,.0f} (every frame)") print(f" total : mean {total.mean():9,.0f} p95 {np.percentile(total, 95):9,.0f} " f"= {100 * total.mean() / VBLANK_BUDGET_CYCLES:.0f}% / {100 * np.percentile(total, 95) / VBLANK_BUDGET_CYCLES:.0f}% of the budget") print(f"\nDMA bytes added per frame: mean {32 * dm.mean() + NAMETABLE_BYTES:,.0f} " f"(mask tiles {32 * dm.mean():,.0f} + name table {NAMETABLE_BYTES:,})") print(f"VRAM for mask tiles: mean {32 * dm.mean() / 1024:.1f} KB, max {32 * dm.max() / 1024:.1f} KB " f"(about 12.8 KB is spare above the name table)") print(f"\nCells that actually need a mask: mean {100 * nu.mean() / (CELLS_X * CELLS_Y):.0f}% - " "the rest are uniform and the per-cell scheme already covers them.") print("Arbitration: every cycle above goes into the window where V_GO is clear and the") print("Z80 may not read the cartridge. The driver refills at twice the drain rate while") print("allowed, so the ring (230 ms) tolerates a longer window, but the measured budget") print("already peaks at 39,966 of 40,000 cycles on hard cuts - those frames have no room.") 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("--per-stratum", type=int, default=40) ap.add_argument("--seed", type=int, default=5) ap.add_argument("--summary", type=Path, default=Path("out/full/summary.json")) ap.add_argument("--crops", type=Path, default=Path("out/shade_crops")) args = ap.parse_args(argv) import json scan = dict(np.load(args.scan, allow_pickle=False)) shots = set(json.loads(args.summary.read_text())["shots"]) if args.summary.exists() else set() groups = strata(scan, shots, args.per_stratum, args.seed) names = scan["names"] print(f"sampling {sum(len(v) for v in groups.values())} frames from {len(names)}: " + ", ".join(f"{k} {len(v)}" for k, v in groups.items())) done: dict[int, dict] = {} all_rows: list[dict] = [] for name, picks in groups.items(): rows = [] for i in picks: if i not in done: rgb = load_picture(args.fields / str(names[i])) m = measure(rgb) fb, fp = (0.0, 0) tb = 0.0 face_masks = face_cells = 0 if scan["n_faces"][i] > 0: fb, fp = region_error(m["base"], scan["boxes"][i, 0]) tb, _ = region_error(m["three"], scan["boxes"][i, 0]) face_masks, face_cells = region_masks(m["masks"], scan["boxes"][i, 0]) done[i] = {"frame": int(i), "name": str(names[i]), "base_total": float(m["base"].sum()), "three_total": float(m["three"].sum()), "face_base": fb, "face_three": tb, "face_pixels": fp, "non_uniform": m["non_uniform"], "distinct_masks": m["distinct_masks"], "face_masks": face_masks, "face_cells": face_cells} # fmt: skip rows.append(done[i]) report(name, rows) all_rows.extend(rows) rows_all = list(done.values()) efficiency(rows_all, encode_cycles(Path("out/full/encode.log"))) face_only(rows_all, encode_cycles(Path("out/full/encode.log"))) cost_model(rows_all) out = args.scan.with_name("shade_study.json") out.write_text(json.dumps({str(int(k)): v for k, v in sorted(done.items())}, indent=1)) print(f"\nper-frame rows -> {out}") return 0 if __name__ == "__main__": raise SystemExit(main())