#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Rung 3's picture judge: run picture ROMs on the board and on NanoBoyAdvance (a closed-box detector, restart.md rule 5), save both last frames, and count the dots that differ. A match is OBSERVED evidence (the detector's behaviour, not the hardware's); a difference is a lead, written down, never fixed without a document or a hardware-calibrated test saying the board is wrong (restart.md rule 6). The hardware-calibrated pictures (hw-test's expected images) are judged separately by ``scripts/hw_pictures.py``. Two counts: dots that differ at all, and dots with a channel off by more than one (the colour effects' rounding, U-VID-9, is a known disagreement that would otherwise hide every other difference in a blended picture). Pictures go to tests/referee_runs/pictures/NAME-board.png, NAME-nba.png and NAME-diff.png (board | detector | dots off by more than one in red, by one in yellow), to be looked at, not only counted. python scripts/board_pictures.py --jobs 8 # the picture test ROMs python scripts/board_pictures.py ROM.gba --frames 900 --keys 400:8 python scripts/board_pictures.py --scenes # the scenes (scripts/build_scenes.py) """ from __future__ import annotations import argparse import json import os import subprocess import sys import tempfile import zlib from concurrent.futures import ThreadPoolExecutor from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "scripts")) sys.path.insert(0, os.environ.get("GBA_PYTHON_SRC", str(ROOT / "src"))) import referee_run from gba_python.ppu.view import png_bytes OUT = ROOT / "tests" / "referee_runs" / "pictures" SCENES = ROOT / "tests" / "referee_runs" / "scenes" # scripts/build_scenes.py # Picture ROMs with no text verdict (docs/validation.md "Rung 3"): name -> (path, frames). # hw-test's are also judged against their expected pictures (scripts/hw_pictures.py). PICTURE_ROMS = { "hw-bgpd": "reference/src/hw-test/ppu/bgpd/bgpd.gba", "hw-bgx": "reference/src/hw-test/ppu/bgx/bgx.gba", "hw-dispcnt-latch": "reference/src/hw-test/ppu/dispcnt-latch/dispcnt-latch.gba", "hw-greenswap": "reference/src/hw-test/ppu/greenswap/greenswap.gba", "hw-sprite-hmosaic": "reference/src/hw-test/ppu/sprite-hmosaic/sprite-hmosaic.gba", "destoer-hello_world": "reference/src/gba_tests-destoer/hello_world/hello_world.gba", "destoer-window_midframe": "reference/src/gba_tests-destoer/window_midframe/window_midframe.gba", "destoer-lyc_midline": "reference/src/gba_tests-destoer/lyc_midline/lyc_midline.gba", "destoer-line_timing": "reference/src/gba_tests-destoer/line_timing/line_timing.gba", "destoer-dma_priority": "reference/src/gba_tests-destoer/dma_priority/dma_priority.gba", "destoer-if_ack": "reference/src/gba_tests-destoer/if_ack/if_ack.gba", "destoer-isr": "reference/src/gba_tests-destoer/isr/isr.gba", "destoer-cond_invalid": "reference/src/gba_tests-destoer/cond_invalid/cond_invalid.gba", "js-hello": "reference/src/gba-tests/ppu/hello.gba", "js-shades": "reference/src/gba-tests/ppu/shades.gba", "js-stripes": "reference/src/gba-tests/ppu/stripes.gba", "al-hello": "reference/src/gba-tests-alyosha/ppu/hello.gba", "al-shades": "reference/src/gba-tests-alyosha/ppu/shades.gba", "al-stripes": "reference/src/gba-tests-alyosha/ppu/stripes.gba", "al-stripes_x_offset": "reference/src/gba-tests-alyosha/ppu/stripes_x_offset.gba", "al-Sprite_Disable_Midline": "reference/src/gba-tests-alyosha/ppu/Sprite_Disable_Midline.gba", "al-Sprite_Disable_on_VRAM_Access": ( "reference/src/gba-tests-alyosha/ppu/Sprite_Disable_on_VRAM_Access.gba" ), } def read_png(path: Path) -> list[list[tuple[int, int, int]]]: """Rows of (r, g, b) from an 8-bit RGB or RGBA PNG (the drivers' and the board's).""" data = path.read_bytes() at = 8 idat = b"" width = height = channels = 0 while at < len(data): length = int.from_bytes(data[at : at + 4], "big") kind = data[at + 4 : at + 8] body = data[at + 8 : at + 8 + length] if kind == b"IHDR": width = int.from_bytes(body[0:4], "big") height = int.from_bytes(body[4:8], "big") channels = {2: 3, 6: 4}[body[9]] elif kind == b"IDAT": idat += body at += 12 + length raw = zlib.decompress(idat) stride = width * channels rows = [] previous = bytearray(stride) pos = 0 for _ in range(height): kind = raw[pos] line = bytearray(raw[pos + 1 : pos + 1 + stride]) pos += 1 + stride for i in range(stride): left = line[i - channels] if i >= channels else 0 up = previous[i] corner = previous[i - channels] if i >= channels else 0 if kind == 1: line[i] = (line[i] + left) & 0xFF elif kind == 2: line[i] = (line[i] + up) & 0xFF elif kind == 3: line[i] = (line[i] + ((left + up) >> 1)) & 0xFF elif kind == 4: p = left + up - corner pa, pb, pc = abs(p - left), abs(p - up), abs(p - corner) pred = left if pa <= pb and pa <= pc else (up if pb <= pc else corner) line[i] = (line[i] + pred) & 0xFF rows.append([tuple(line[x * channels : x * channels + 3]) for x in range(width)]) previous = line return rows def to15(rgb: tuple[int, int, int]) -> int: r, g, b = rgb return (r >> 3) | (g >> 3) << 5 | (b >> 3) << 10 def off_by_more_than_one(a: int, b: int) -> bool: """A difference beyond the colour effects' rounding (docs/video.md U-VID-9).""" return any(abs(((a >> s) & 31) - ((b >> s) & 31)) > 1 for s in (0, 5, 10)) def compare(board: Path, detector: Path, diff: Path) -> dict: a = read_png(board) b = read_png(detector) differing = coarse = 0 rows_hit = set() canvas = [] for y in range(len(a)): row_a = [to15(c) for c in a[y]] row_b = [to15(c) for c in b[y]] mask = [] for x in range(len(row_a)): if row_a[x] != row_b[x]: differing += 1 rows_hit.add(y) if off_by_more_than_one(row_a[x], row_b[x]): coarse += 1 mask.append(0x001F) else: mask.append(0x03FF) # yellow: no channel off by more than one else: # The matching dots, dimmed, so the difference stands out. c = row_a[x] mask.append(((c & 31) >> 2) | (((c >> 5) & 31) >> 2) << 5 | ((c >> 10) >> 2) << 10) canvas.append(row_a + [0x7FFF] * 4 + row_b + [0x7FFF] * 4 + mask) diff.write_bytes(png_bytes(canvas)) lines = sorted(rows_hit) return { "differing_dots": differing, "coarse_dots": coarse, "lines": f"{lines[0]}-{lines[-1]} ({len(lines)})" if lines else "", } def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("roms", nargs="*", help="default: the picture test ROMs") parser.add_argument("--scenes", action="store_true", help="the built scenes instead") parser.add_argument("--bios", default="free") parser.add_argument("--frames", type=int, default=300) parser.add_argument("--keys", action="append", default=[], help="FRAME:MASK, both sides") parser.add_argument("--jobs", type=int, default=4) parser.add_argument("--json", type=Path) parser.add_argument("--out", type=Path, default=OUT, help="where the pictures go") parser.add_argument("--no-detector", action="store_true", help="board pictures only") args = parser.parse_args() if args.roms: jobs = [(Path(r).stem, Path(r)) for r in args.roms] elif args.scenes: jobs = [(f"scene-{p.stem}", p) for p in sorted(SCENES.glob("*.gba"))] else: jobs = [(name, ROOT / path) for name, path in PICTURE_ROMS.items()] out_dir = args.out out_dir.mkdir(parents=True, exist_ok=True) env = dict(os.environ, PYPY_GC_NURSERY="1M") env["PYTHONPATH"] = os.environ.get("GBA_PYTHON_SRC", str(ROOT / "src")) keys = [k for item in args.keys for k in ("--keys", item)] with tempfile.TemporaryDirectory(dir=out_dir) as scratch: bios = referee_run.bios_args(args.bios, Path(scratch)) def judge(job: tuple[str, Path]) -> dict: name, rom = job (Path(scratch) / name).mkdir() board_png = out_dir / f"{name}-board.png" nba_png = out_dir / f"{name}-nba.png" command = ["nice", sys.executable, "-m", "gba_python", str(rom), *bios] command += ["--frames", str(args.frames), "--png", str(board_png), *keys] subprocess.run(command, capture_output=True, env=env, timeout=7200, check=False) result = {"name": name, "rom": str(rom)} if not args.no_detector: driver = referee_run.DRIVERS["nba"] # A No-Intro .zip is unpacked only to a temporary file for the driver. nba_rom = referee_run.unzip_rom(Path(rom), Path(scratch) / name) command = [str(driver), str(nba_rom), *bios, "--frames", str(args.frames)] command += ["--png", str(nba_png), *keys] subprocess.run(command, capture_output=True, timeout=600, check=False) if board_png.exists() and nba_png.exists(): result |= compare(board_png, nba_png, out_dir / f"{name}-diff.png") else: result["differing_dots"] = None print( f"{name:40} {result.get('differing_dots')!s:>7} {result.get('coarse_dots')!s:>7}" f" {result.get('lines', '')}", flush=True, ) return result with ThreadPoolExecutor(max_workers=max(1, args.jobs)) as pool: results = list(pool.map(judge, jobs)) same = sum(r.get("differing_dots") == 0 for r in results) print(f"{same}/{len(results)} pictures identical to the detector's") if args.json: args.json.write_text(json.dumps(results, indent=1) + "\n", encoding="utf-8") return 0 if __name__ == "__main__": sys.exit(main())