#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """The whole board against Sim2600's 6507: every TIA write, at the die's half clock. Sim2600 simulates the 6507's netlist as well as the TIA's, so a die trace also records *when the CPU wrote*: each write lands on the record where CLK2 falls. This runs the board (6502-python, RDY, the cycle grid, the cartridge) on the cartridge the trace was recorded from and compares the two sequences of TIA writes, (step in the line, address, value), from the first RSYNC on (RSYNC sets the line's phase from the bus, so the board's power-on phase drops out). The trace's step in the line comes from replaying it through the board's TIA, which matches the die on every pin (``scripts/die_trace.py``). python scripts/die_board.py TRACE CARTRIDGE.bin A mismatch means the board runs the CPU at a different half clock from the die: RDY's sampling, the cycle grid, or a cycle count. **Sim2600's 6507 never sees TIA read data.** Its console code starts a TIA read at 0 and ORs in the die's D7/D6 drivers as they stand when it samples (``Sim2600/sim2600Console.py`` ``readMemory``), which is before the die enables them: the ``collisions`` cartridge reads INPT5 with the die driving D7 high (the trace's drive pins say so, and the board's TIA matches them) and then stores $00. So in Sim2600 every TIA read returns 0, where a console's 6507 gets D7/D6 from the TIA and the rest from the floating bus (docs/undocumented-behavior.md C23). The board here reads TIA registers as 0, for this comparison only; the die's drive pins are judged by die_trace.py. **Sim2600's RIOT is not a die.** ``emuPIA.py`` is a fifty-line behavioural model, driven by ``sim2600Console.py``: the timer's first decrement comes a whole interval after the write, after underflow it counts down to 0 and stops there, a read clears nothing, port registers read back what was written, and SWCHB holds $0B. :class:`Sim2600Riot` reproduces that, for this comparison only, so a cartridge that waits on the timer (Donkey Kong) can be compared at all; the board's own RIOT follows the data sheet (riot.py). """ from __future__ import annotations import argparse import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) sys.path.insert(0, str(ROOT / "scripts")) from die_trace import console_wiring, load # noqa: E402 from a2600_python import System # noqa: E402 from a2600_python.cartridge import load as load_cartridge # noqa: E402 from a2600_python.tia import RSYNC, TIA # noqa: E402 def trace_writes(records) -> list[tuple[int, int, int]]: console = console_wiring(records) tia = TIA() tia.rising = records[0][0] == 1 bus = records[0] out = [] for k, rec in enumerate(records): if not console or rec[1]: bus = rec write = None if k and records[k - 1][1] and not rec[1] and bus[3] == 0 and bus[4] == 0 and bus[2] == 0: write = (bus[5], bus[6]) tia.inputs = rec[7] tia.step(write) if write is not None: out.append((tia.step_in_line, write[0] & 0x3F, write[1])) return out class Sim2600Riot: """The RIOT as Sim2600's console code runs it (emuPIA.py, sim2600Console.py).""" def __init__(self) -> None: self.ram = bytearray(128) self.io = bytearray(0x18) self.io[0x00] = 0xFF # SWCHA: no joystick motion self.io[0x02] = 0x0B # SWCHB: colour, select and reset released self.period = 0 self.loaded = 0 self.loaded_at = 0 def timer(self, cycle: int) -> int: """One tick per CPU cycle after the write's; a decrement every period ticks; past zero, $FF and one a tick, stopping at 0.""" if not self.period: return self.loaded ticks = cycle - self.loaded_at steps = ticks // self.period if steps <= self.loaded: return self.loaded - steps wrapped_at = (self.loaded + 1) * self.period return max(0xFF - (ticks - wrapped_at), 0) def read(self, address: int, cycle: int) -> int: if not address & 0x200: return self.ram[address & 0x7F] if address == 0x284: return self.timer(cycle) return self.io[address - 0x280] if 0x280 <= address <= 0x297 else 0 def write(self, address: int, value: int, cycle: int) -> None: if not address & 0x200: self.ram[address & 0x7F] = value elif 0x280 <= address <= 0x297: self.io[address - 0x280] = value if address in (0x294, 0x295, 0x296, 0x297): self.period = (1, 8, 64, 1024)[address - 0x294] self.loaded, self.loaded_at = value, cycle def board_writes(cartridge: Path, limit: int) -> list[tuple[int, int, int]]: system = System(load_cartridge(cartridge.read_bytes(), scheme="4K").cartridge) board = system.board board.riot = Sim2600Riot() tia = board.tia board_read = board.read_byte def read_like_sim2600(address: int) -> int: value = board_read(address) if not address & 0x1080: # a TIA read: Sim2600's glue returns 0 value = 0 board.data_bus = value return value board.read_byte = read_like_sim2600 system.cpu = type(system.cpu)(read_like_sim2600, board.write_byte) system.cpu.a, system.cpu.x, system.cpu.y, system.cpu.s, system.cpu.p = 0, 0, 0, 0, 0x24 system.cpu.request_reset() out = [] step = tia.step def stepping(write=None): step(write) if write is not None: out.append((tia.step_in_line, write[0] & 0x3F, write[1])) tia.step = stepping while len(out) < limit: system.step() return out def after_rsync(writes): for i, (_, address, _) in enumerate(writes): if address == RSYNC: return writes[i + 1 :] raise SystemExit("no RSYNC in the writes") def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("trace", type=Path) parser.add_argument("cartridge", type=Path) parser.add_argument("--context", type=int, default=5) args = parser.parse_args() die = after_rsync(trace_writes(load(args.trace))) board = after_rsync(board_writes(args.cartridge, len(die) + 400))[: len(die)] for i, (theirs, ours) in enumerate(zip(die, board, strict=False)): if theirs != ours: print(f"{args.trace.name}: DIFFER at TIA write {i:,} of {len(die):,}") for k in range(max(0, i - args.context), i): print(f" both step {die[k][0]:3d} ${die[k][1]:02X} <- ${die[k][2]:02X}") print(f" die step {theirs[0]:3d} ${theirs[1]:02X} <- ${theirs[2]:02X}") print(f" board step {ours[0]:3d} ${ours[1]:02X} <- ${ours[2]:02X}") return 1 print( f"{args.trace.name}: all {len(die):,} TIA writes after RSYNC agree in step, address and value" ) return 0 if __name__ == "__main__": sys.exit(main())