#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Drive hw-test's two interactive PPU menus on the board and read their results (rung 4). hw-test (BSD-3-Clause, fleroviux and contributors) is "GBA hardware tests"; nothing of its source is copied here, only the menu order and what each screen prints: - ``ppu/status-irq-dma``: four sub-tests (DISPSTAT, VCOUNT, IRQ (IF), DMA), each printing "NAME: PASS n" or "NAME: FAIL n / expected: m" against values that its source states (``test_expect``; the README: "tests the timing of DISPSTAT flag changes, VCOUNT changes and PPU IRQ and DMA requests"). Read from background 0's map, as scripts/board_screens.py does. - ``ppu/ram-access-timing``: a stall map, one bit per CPU cycle for 1,231 cycles after a line-0 H-blank IRQ, for a chosen layer setup. The ROM keeps the map in SRAM (``0E000000``) before it shows it, so the map is read from the board's SRAM (the cartridge is run with SRAM fitted). The ROM stores no expectation; the author's comments beside the PRAM options give the hardware's repeating 4-cycle pattern for some of them ("1000", "1010", "0000", "0010"), and those are the only ones judged here (``PRAM_EXPECTED``); the rest are printed, read by eye. python scripts/hw_menus.py status [--bios "$BIOS"] python scripts/hw_menus.py pram # PRAM options against the comments python scripts/hw_menus.py map MENU,ITEM[,SUB] # print one stall map (menu path) python scripts/hw_menus.py lyc --bios "$BIOS" # destoer lyc_midline's numbers ``lyc`` reads destoer lyc_midline's printed numbers (destoer gba_tests, MIT; its BG0 map holds ASCII - 32) against its expected.jpg, a photograph of a DS-family console in GBA mode, which runs Nintendo's BIOS (so only the retail BIOS gives the photograph's phase): start 7, end 3F, vcount 24; rapid toggle start DC0B, end E0AA, lyc count 6. The judged lines are vcount, lyc count and the rapid toggle's length (end - start = 49F); the absolute start and end are reported (they carry the CPU time of the printing between the two parts). """ from __future__ import annotations import argparse import json import os import sys import tempfile from concurrent.futures import ProcessPoolExecutor 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"))) from board_screens import screen_text from gba_python.board import GBA from gba_python.cartridge.rom import GamePakROM PPU = ROOT / "reference" / "src" / "hw-test" / "ppu" KEY_A, KEY_B, KEY_RIGHT, KEY_LEFT, KEY_UP, KEY_DOWN = 1, 2, 16, 32, 64, 128 STATUS_TESTS = ("DISPSTAT", "VCOUNT", "IRQ (IF)", "DMA") # The PRAM menu's options whose 4-cycle stall pattern the ROM's author wrote beside them # (main.c, test_pram_accesses: hardware observations in a comment; TEST ROM prose). Options # 5 and 7 depend on whether the dots are opaque ("1000 ... OR 1010"); BG0's map and tiles are # the console font's, so both patterns occur and either is accepted per dot. PRAM_EXPECTED = { 0: ("1000",), 1: ("1000",), 2: ("1000",), 3: ("1000",), 4: ("1000",), 5: ("1000", "1010"), 6: ("1000",), 7: ("1000", "1010"), 8: ("1000",), 9: ("0000",), 10: ("0010",), } class Driver: def __init__(self, rom: Path, bios, boot_frames: int) -> None: self.board = GBA(GamePakROM.from_path(str(rom)), bios=bios, save_type="sram") self.board.run_frames(boot_frames) # The menus act on a key's release seen by a later scan; the very first press after # boot is not seen (observed on the board): spend it on B, which the main menus ignore. self.press(KEY_B) def frames(self, n: int) -> None: self.board.run_frames(n) def press(self, key: int) -> None: """Hold a key for 4 frames and let go for 4: the menus act on the release (keysUp).""" self.board.set_keys(key) self.frames(4) self.board.set_keys(0) self.frames(4) def choose(self, index: int) -> None: for _ in range(index): self.press(KEY_DOWN) self.press(KEY_A) def wait_text(self, done, limit_frames: int, step: int = 30) -> list[str]: lines = screen_text(self.board) spent = 0 while not done(lines) and spent < limit_frames: self.frames(step) spent += step lines = screen_text(self.board) return lines def boot_frames(bios) -> int: """Frames to the cartridge's menu: the free BIOS boots at once, Nintendo's in ~270.""" return 60 if "cult" in str(bios).lower() or bios == "free" else 330 def run_status(job) -> dict: index, bios = job driver = Driver(PPU / "status-irq-dma" / "status-irq-dma.gba", bios, boot_frames(bios)) driver.choose(index) want = 3 if index == 3 else None def done(lines): results = [line for line in lines if ": PASS" in line or ": FAIL" in line] if want is not None: return len(results) >= want return any("congratulations" in line or "total:" in line for line in lines) lines = driver.wait_text(done, 12000) results = [line.strip() for line in lines if ": PASS" in line or ": FAIL" in line] expected = [line.strip() for line in lines if "expected" in line] return {"test": STATUS_TESTS[index], "results": results, "expected": expected} def stall_map(path: tuple[int, ...], bios) -> list[int]: driver = Driver(PPU / "ram-access-timing" / "ram-access-timing.gba", bios, boot_frames(bios)) for i, index in enumerate(path): driver.choose(index) if path[0] == 0 and i == 1: driver.press(KEY_A) # the BGHOFS selector: keep 0 sram = driver.board.backup # Wait until the ROM has written the map (the bitmap view's first row appears). driver.wait_text(lambda lines: any(line.startswith("0000:") for line in lines), 20000) data = sram.save_data() return [data[i] & 1 for i in range(1231)] def pattern_of(bits: list[int], start: int, end: int, phase: int) -> dict[str, int]: """Count the 4-cycle groups of bits[start:end] whose first cycle is ``phase`` mod 4.""" counts: dict[str, int] = {} for i in range(start + ((phase - start) % 4), end - 3, 4): key = "".join(str(b) for b in bits[i : i + 4]) counts[key] = counts.get(key, 0) + 1 return counts def run_pram(job) -> dict: option, bios = job return {"option": option, "bits": stall_map((5, option), bios)} # The drawing part of line 1: the map starts at line 0's H-blank IRQ, so line 1's 960 drawing # cycles lie roughly 230-1190 cycles into it; cycles 300-1100 are judged. JUDGED = (300, 1100) def judge_pram(maps: list[dict]) -> list[dict]: """The comments' patterns share one 4-cycle grid: every map is taken from the same H-blank IRQ, and "1000" (option 0, every dot's one read) fixes where a group starts; the other options are read on that grid ("0010" is a read in the third cycle of a dot).""" first = maps[0]["bits"] start, end = JUDGED phase = next((i for i in range(start, end) if first[i]), start) % 4 out = [] for item in maps: counts = pattern_of(item["bits"], start, end, phase) allowed = PRAM_EXPECTED[item["option"]] ok = bool(counts) and all(key in allowed for key in counts) out.append({"option": item["option"], "pass": ok, "counts": counts, "expected": allowed}) return out LYC_EXPECTED = { "start": 0x7, "end": 0x3F, "vcount": 0x24, "start2": 0xDC0B, "end2": 0xE0AA, "count": 6, } def run_lyc(bios) -> dict: rom = ROOT / "reference" / "src" / "gba_tests-destoer" / "lyc_midline" / "lyc_midline.gba" board = GBA(GamePakROM.from_path(str(rom)), bios=bios) board.run_frames(boot_frames(bios) + 70) regs = board.ppu.regs base = ((regs[4] >> 8) & 0x1F) * 0x800 vram = board.bus.vram lines = [] for row in range(20): cells = [ vram[base + (row * 32 + c) * 2] | vram[base + (row * 32 + c) * 2 + 1] << 8 for c in range(30) ] lines.append("".join(chr((t & 0x3FF) + 32) if t else " " for t in cells).strip()) values = [] for line in lines: if ":" in line: values.append(int(line.split(":")[1].strip() or "0", 16)) names = ("start", "end", "vcount", "start2", "end2", "count") got = dict(zip(names, values, strict=False)) judged = { "vcount": got.get("vcount") == LYC_EXPECTED["vcount"], "count": got.get("count") == LYC_EXPECTED["count"], "length": got.get("end2", 0) - got.get("start2", 0) == 0xE0AA - 0xDC0B, "first part": (got.get("start"), got.get("end")) == (0x7, 0x3F), } return { "values": {k: hex(v) for k, v in got.items()}, "judged": judged, "passes": sum(judged.values()), "total": len(judged), } def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("what", choices=("status", "pram", "map", "lyc")) parser.add_argument("path", nargs="?", help="map: menu indices, e.g. 6,1") parser.add_argument("--bios", default="free") parser.add_argument("--jobs", type=int, default=4) parser.add_argument("--json", type=Path) args = parser.parse_args() os.environ.setdefault("PYPY_GC_NURSERY", "1M") with tempfile.TemporaryDirectory() as scratch: import referee_run bios_args = referee_run.bios_args(args.bios, Path(scratch)) bios = bios_args[1] if bios_args else "free" out: object if args.what == "status": with ProcessPoolExecutor(max_workers=args.jobs) as pool: tests = [int(t) for t in args.path.split(",")] if args.path else range(4) out = list(pool.map(run_status, [(i, bios) for i in tests])) passes = total = 0 for item in out: print(item["test"]) for line in item["results"]: print(" ", line) total += 1 passes += ": PASS" in line for line in item["expected"]: print(" ", line) print(f"{passes}/{total} status-irq-dma lines pass") out = {"passes": passes, "total": total, "tests": out} elif args.what == "pram": with ProcessPoolExecutor(max_workers=args.jobs) as pool: maps = list(pool.map(run_pram, [(o, bios) for o in PRAM_EXPECTED])) out = judge_pram(maps) for item in out: print( f"{'pass' if item['pass'] else 'FAIL':5} option {item['option']:2} " f"{item['counts']} expected {item['expected']}" ) print(f"{sum(i['pass'] for i in out)}/{len(out)} PRAM patterns as the comments say") elif args.what == "lyc": out = run_lyc(bios) print(out["values"]) print( out["judged"], f"{out['passes']}/{out['total']} lyc_midline lines as the photograph" ) else: path = tuple(int(p) for p in args.path.split(",")) bits = stall_map(path, bios) for row in range(0, 1231, 64): print(f"{row:4}: " + "".join(str(b) for b in bits[row : row + 64])) out = bits if args.json: args.json.write_text(json.dumps(out, indent=1) + "\n", encoding="utf-8") return 0 if __name__ == "__main__": sys.exit(main())