# SPDX-License-Identifier: MIT """Which name-table entry a plane shows for every setting of register 16, at the pins. Register 16 sets the planes' width and height: 32, 64 or 128 cells, and a fourth setting CMD's ``genvdp.txt`` calls invalid ("the first row of the name table is shown for every line of the display", for the width only). Nothing hardware-captured says what the invalid height does, or what a size over the 8 KB a name table may hold does. This measures it on the referee, Nuked-MD @ 594ca2a, run as a closed box: only its RGB output pins are looked at (``NMD_PLOT``), rows counted in the order its /HSYNC gives them and pixels from the first non-black sample, so nothing inside the model is consulted. What it gives is ``OBSERVED``, and a hardware result that disagrees overrules it. The cartridge, hand-assembled, fills all of VRAM so that every word of it, read as a name table entry, names a different picture. Tile t (0-1023) draws, on each of its rows y, the four groups of t's bits (3, 3, 3 and 1 bits, each plus 1) in pixels 0-3, y + 1 in pixel 4 and colour 15 in pixels 5-7; the entry's palette (bits 13-14) gives two more bits and its horizontal flip one more, so an entry is decoded from the eight pixels it puts on screen. CRAM entry i is its own colour (red i & 7, green i >> 3, blue 7; entry 0 black, the only black). VRAM $0000-$7FFF holds the tiles, $8000-$BFFF zeros (plane B, the sprite table at $A000 and the scroll table at $AC00), $C000-$DFFF plane A's table with entry e = t | p << 10 for word e, and $E000-$FFFF the same codes with the flip set, so a fetch outside the 8 KB from plane A's base shows as such. For each of the 16 values of register 16 and five scroll settings it records the code each screen cell shows, then runs the same cartridge on the board and compares the pictures pixel for pixel. python scripts/run_plane_sizes.py [--jobs 8] [--json OUT.json] [--board-only REF.json] """ from __future__ import annotations import argparse import json import os import subprocess import sys import tempfile from concurrent.futures import ProcessPoolExecutor from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path[:0] = [str(ROOT / "src"), str(ROOT / "scripts")] import nuked_md # noqa: E402 FRAME_MCLK = 262 * 3420 # NTSC PLOT_FRAME = 12 # counted in /VSYNC falls; the load takes about seven frames BOARD_FRAME = 12 WIDTH, HEIGHT = 320, 224 #: (horizontal scroll, vertical scroll) in pixels: together they put plane columns #: 0-151 and rows 0-139 (before any wrap) on screen. SCROLLS = ((0, 0), (0x2C0, 0x0E0), (0x200, 0x1C0), (0x140, 0x2A0), (0x080, 0x380)) SIZES = tuple(v << 4 | h for v in range(4) for h in range(4)) def _w(*words: int) -> bytes: return b"".join(x.to_bytes(2, "big") for x in words) def _vram_command(address: int) -> tuple[int, int]: value = 0x40000000 | (address & 0x3FFF) << 16 | address >> 14 return value >> 16, value & 0xFFFF def colour(i: int) -> int: """CRAM entry i's 9-bit colour word.""" return 0 if i == 0 else (i & 7) << 1 | (i >> 3 & 7) << 5 | 7 << 9 def tile(t: int) -> bytes: out = bytearray() groups = [(t >> 0) & 7, (t >> 3) & 7, (t >> 6) & 7, (t >> 9) & 1] for y in range(8): pixels = [g + 1 for g in groups] + [y + 1, 15, 15, 15] for x in range(0, 8, 2): out.append(pixels[x] << 4 | pixels[x + 1]) return bytes(out) def vram() -> bytes: data = bytearray() for t in range(1024): data += tile(t) data += bytes(0x4000) # $8000-$BFFF for flip in (0, 1): for e in range(4096): data += ((e & 0x3FF) | (e >> 10) << 13 | flip << 11).to_bytes(2, "big") assert len(data) == 0x10000 return bytes(data) def cartridge(size: int, hs: int, vs: int) -> bytes: """The test cartridge; each encoding is in its comment.""" code = bytearray() code += _w(0x46FC, 0x2700) # move.w #$2700,sr code += bytes.fromhex("23fc5345474100a14000") # move.l #'SEGA',$A14000 code += _w(0x41F9, 0x00C0, 0x0000) # lea $C00000,a0 (data) code += _w(0x43F9, 0x00C0, 0x0004) # lea $C00004,a1 (control) for reg, value in ((0x00, 0x04), (0x01, 0x04), (0x02, 0x30), (0x03, 0x00), (0x04, 0x04), (0x05, 0x50), (0x07, 0x00), (0x0A, 0xFF), (0x0B, 0x00), (0x0C, 0x81), (0x0D, 0x2B), (0x0F, 0x02), (0x10, size), (0x11, 0x00), (0x12, 0x00)): # fmt: skip code += _w(0x32BC, 0x8000 | reg << 8 | value) # move.w #$8rvv,(a1) code += _w(0x47F9, 0x0001, 0x0000) # lea $10000,a3: the data code += _w(0x22BC, *_vram_command(0)) # move.l #cmd,(a1): VRAM write 0 code += _w(0x303C, 0x7FFF) # move.w #$7FFF,d0 code += _w(0x309B, 0x51C8, 0xFFFC) # copy: move.w (a3)+,(a0); dbra d0,copy code += _w(0x22BC, 0xC000, 0x0000) # CRAM write 0 code += _w(0x303C, 0x003F) # move.w #63,d0 code += _w(0x309B, 0x51C8, 0xFFFC) # the 64 colours code += _w(0x22BC, *_vram_command(0xAC00)) # the scroll table code += _w(0x30BC, hs & 0x3FF, 0x30BC, 0x0000) # plane A, plane B code += _w(0x22BC, 0x4000, 0x0010) # VSRAM write 0 code += _w(0x30BC, vs & 0x3FF, 0x30BC, 0x0000) code += _w(0x32BC, 0x8144) # display on, V28 code += _w(0x60FE) # bra.s * rom = bytearray(0x20000) rom[0:4] = (0x00FFFE00).to_bytes(4, "big") rom[4:8] = (0x00000200).to_bytes(4, "big") for vector in range(2, 64): # every exception halts, so a fault is loud rom[vector * 4 : vector * 4 + 4] = (0x000001F0).to_bytes(4, "big") rom[0x1F0:0x1F4] = bytes.fromhex("4e722700") # stop #$2700 rom[0x100:0x110] = b"SEGA GENESIS " rom[0x200 : 0x200 + len(code)] = code rom[0x10000:0x20000] = vram() palette = b"".join(colour(i).to_bytes(2, "big") for i in range(64)) return bytes(rom) + palette + bytes(0x20000 - len(palette)) def _step(level: int) -> int: return round(level * 14 / 255) def referee_picture(rom: bytes, width: int = WIDTH, frame: int = PLOT_FRAME ) -> list[list[tuple[int, int, int]]]: # fmt: skip """The referee's picture as 224 rows of ``width`` (r, g, b) ramp steps: rows that show anything but black, in /HSYNC order; pixels from the row's first non-black sample, at the samples a pixel the longest lit row gives (two in H40). The cartridge must light every pixel of the picture (no black in it).""" nuked_md.ensure_built() with tempfile.TemporaryDirectory() as tmp: work = Path(tmp) (work / "rom.bin").write_bytes(rom) env = dict(os.environ, NMD_STOP=str((frame + 1) * FRAME_MCLK * 2), NMD_PLOT=str(work / "plot.bin"), NMD_PLOT_FRAME=str(frame)) # fmt: skip subprocess.run(["nice", str(nuked_md.BINARY), str(work / "rom.bin")], env=env, cwd=work, check=True, capture_output=True) # fmt: skip plot = (work / "plot.bin").read_bytes() lines, samples = int.from_bytes(plot[4:8], "little"), int.from_bytes(plot[8:12], "little") counts = [int.from_bytes(plot[12 + 2 * i : 14 + 2 * i], "little") for i in range(lines)] base = 12 + 2 * lines lit_rows = [] for i in range(lines): row = plot[base + i * samples * 3 : base + (i * samples + counts[i]) * 3] lit = [x for x in range(counts[i]) if any(row[3 * x : 3 * x + 3])] if lit: lit_rows.append((row, lit)) per = round(max(len(lit) for _, lit in lit_rows) / width) rows = [] for row, lit in lit_rows: first = lit[0] rows.append([tuple(_step(v) for v in row[3 * (first + per * x) : 3 * (first + per * x) + 3]) for x in range(width)]) # fmt: skip return rows[:HEIGHT] def board_picture(rom: bytes, width: int = WIDTH, frame: int = BOARD_FRAME ) -> list[list[tuple[int, int, int]]]: # fmt: skip from megadrive_python.cartridge import Cartridge from megadrive_python.machine import MACHINES from megadrive_python.render import RAMP from megadrive_python.system import System step = {level: i for i, level in enumerate(RAMP)} system = System(MACHINES["nuked-md"], Cartridge(rom)) system.board.fm.enabled = False for _ in range(frame): system.run_frame() return [[(step[p >> 16 & 255], step[p >> 8 & 255], step[p & 255]) for p in row[:width]] for row in system.vdp.renderer.frame_rgb()[:HEIGHT]] # fmt: skip def decode(picture) -> list[list[int | None]]: """The code each 8-pixel cell shows: t | p << 10 | flip << 12, or None.""" out = [] for row in picture: cells = [] for cx in range(WIDTH // 8): values = [] for r, g, b in row[8 * cx : 8 * cx + 8]: i = (g // 2) << 3 | r // 2 values.append((i >> 4, i & 15)) p = values[0][0] colours = [c for _, c in values] flip = colours[0] == 15 if flip: colours = colours[::-1] groups = [c - 1 for c in colours[:4]] if colours[5:] != [15, 15, 15] or not all(0 <= g < 8 for g in groups): cells.append(None) continue t = groups[0] | groups[1] << 3 | groups[2] << 6 | (groups[3] & 1) << 9 cells.append(t | p << 10 | flip << 12) out.append(cells) return out def case(args: tuple[int, int, int, bool]) -> dict: size, hs, vs, referee = args rom = cartridge(size, hs, vs) picture = referee_picture(rom) if referee else board_picture(rom) return {"size": size, "hs": hs, "vs": vs, "rows": len(picture), "picture": picture, "cells": decode(picture)} # fmt: skip def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--jobs", type=int, default=8) parser.add_argument("--json", type=Path, help="write the referee's results here") parser.add_argument("--board-only", type=Path, help="referee results from --json") args = parser.parse_args() tasks = [(s, hs, vs) for s in SIZES for hs, vs in SCROLLS] with ProcessPoolExecutor(args.jobs) as pool: if args.board_only: ref = json.loads(args.board_only.read_text()) else: ref = list(pool.map(case, [(*t, True) for t in tasks])) if args.json: args.json.write_text(json.dumps(ref)) ours = list(pool.map(case, [(*t, False) for t in tasks])) failed = 0 for theirs, mine in zip(ref, ours, strict=True): same = sum(1 for a, b in zip(theirs["picture"], mine["picture"], strict=False) for x, y in zip(a, b, strict=False) if tuple(x) == tuple(y)) # fmt: skip ok = same == WIDTH * HEIGHT failed += not ok print(f"reg16 ${theirs['size']:02X} scroll ({theirs['hs']:#05x}, {theirs['vs']:#05x}): " f"{same} of {WIDTH * HEIGHT} pixels {'identical' if ok else 'DIFFERENT'}") # fmt: skip print(f"{len(tasks) - failed} of {len(tasks)} pictures identical") return 1 if failed else 0 if __name__ == "__main__": raise SystemExit(main())