"""The cartridge slot and the boards that plug into it (docs/cartridge.md). The slot carries A0-A14, D0-D7 and four 8K chip selects, and no /RD, /WR or clock: a cartridge sees an address and cannot tell a read from a write (two tracings agree). So every board here is driven by *accesses*; :meth:`Cartridge.write` exists for boards the emulators model as decoding writes (the Activision board) and is an access for the rest. :meth:`Cartridge.peek` reads without side effects, for the board's own look at the instruction bytes and for tools. """ from __future__ import annotations from typing import ClassVar, Protocol class Cartridge(Protocol): """What the board calls for ``$8000-$FFFF``.""" def read(self, address: int) -> int: ... def write(self, address: int, value: int) -> None: ... def peek(self, address: int) -> int: ... class NoCartridge: """An empty slot: every select reads open bus (U5).""" def __init__(self, open_bus: int = 0xFF) -> None: self.open_bus = open_bus def read(self, address: int) -> int: return self.open_bus def write(self, address: int, value: int) -> None: pass def peek(self, address: int) -> int: return self.open_bus class PlainCartridge: """The 1982 board: ROM from ``$8000``, up to 32K, no banking [TM]. Bytes past the image's end read open bus (U5; MAME's ``std.cpp`` returns ``$FF``). An odd-sized dump (12K, 20K) may on the real board be a smaller chip mirrored inside its 8K select; nothing in hand says, so the image is taken as it is. """ def __init__(self, image: bytes, open_bus: int = 0xFF) -> None: if len(image) > 0x8000: raise ValueError(f"a plain cartridge holds at most 32K, not {len(image)} bytes") self.image = bytes(image) self.open_bus = open_bus # 32K table so a read is one index (the board passes $8000-$FFFF). self._rom = self.image + bytes((open_bus,)) * (0x8000 - len(self.image)) def read(self, address: int) -> int: return self._rom[address & 0x7FFF] def write(self, address: int, value: int) -> None: pass def peek(self, address: int) -> int: return self._rom[address & 0x7FFF] # --------------------------------------------------------------------------------------- # Banked boards: a clean-room rewrite (2026-11-26, docs/provenance.md "Mapper rewrite"). # # Written only from the documents named below; no emulator's source was opened, and the # earlier mapper code was not read. Evidence tags: DOC (a document says it), HYPOTHESIS # (the documents are silent; the choice is ours and is marked to be checked on hardware). # # [TM] Coleco Technical Manual: the slot (A0-A14, D0-D7, four 8K selects; no /RD, # /WR, clock or reset) and the BIOS's header test at $8000. # [EDW] colecovision.dk, the MegaCart page (Bryan Edewaard's board): "two chunks of # 16K, and one of these chunks can be switched"; 128K, 256K, 512K and 1024K; "no # 64K variation". # [CVB] CVBasic (Oscar Toledo G., BSD-2-Clause; manual.txt, cvbasic.c, cvbasic_prologue.asm # at the 2026-11-26 master): a MegaCart program's fixed bank is assembled at file # offset size - 16K and runs at $8000; bank n (n = 0..banks-1, from the image's # start) is assembled for $C000 and selected by reading $FFC0 | n (the address # masked to the bank count: $FFF8 | n at 128K, $FFC0 | n at 1M); each bank's # top 64 bytes ($FFC0-$FFFF) are left unused; at start-up the runtime reads $FFC0. # [RC2014] ezod/rc2014-cv-megacart-ram README (no licence; facts only): "bank switching # is always enabled on the upper 16KB (bank 0 at boot)", the lower 16K fixed on # the last bank, the switch made by a read of the window's top addresses. # [CVA] cvaddict.com, Eric Chartre's open MegaCart PCB: "For 64K rom, just copy them # twice in the image file". # [AA-ACT] AtariAge topic 327053 "Activision PCB - Bank Switching and EEPROM": kevtris's # register list (read FF80 "returns data in bank 2 or 3 depending on if SDA is low # or high"; writes FF90/FFA0/FFB0 select banks 1/2/3 at $C000; FFC0/FFD0 clear/set # SCL; FFE0/FFF0 clear/set SDA; bank 0 fixed at $8000-$BFFF; and, as his guess, # unchecked: the last 128 bytes come from bank 2 or 3 by SDA). AtariAge refuses # scripted fetches (403): these facts reached us through search-engine extracts # of the thread, not a reading of it, so each is DOC (second-hand). # [AA-SAVE] AtariAge threads on Team Pixelboy's saves (Pixelboy: Black Onyx, Boxxle, # Arcomage and Jewel Panic each have "a savegame chip"; up to 64K; a developer: # Black Onyx "a very small 256B EE", Boxxle "a 32KB EE"), the same second-hand route. # [24C02] Microchip 24AA02/24LC02B data sheet DS21709J (256 x 8, one block, 8-byte page, # the control byte's three block bits "don't care", one word-address byte). # [24C256] Microchip 24AA256/24LC256 data sheet DS20001203W (32K x 8, 64-byte page, two # word-address bytes, chip-select bits A2-A0 matched to the pins, reads roll over # at the end of the array, page writes wrap within the page). # --------------------------------------------------------------------------------------- _HEADERS = (b"\xaa\x55", b"\x55\xaa") # [TM] the BIOS's test of $8000-$8001 _BANK = 0x4000 def _banks(image: bytes, open_bus: int) -> list[bytes]: """The image cut into 16K banks; a short last bank is padded with open bus.""" count = max(1, -(-len(image) // _BANK)) padded = bytes(image) + bytes((open_bus,)) * (count * _BANK - len(image)) return [padded[i * _BANK : (i + 1) * _BANK] for i in range(count)] def _mask_for(count: int) -> int: """Bank-number mask: the bank count rounded up to a power of two, minus one.""" return (1 << (count - 1).bit_length()) - 1 class MegaCart: """The MegaCart: 16K banks, the last one fixed at ``$8000``, any one at ``$C000``. - ``$8000-$BFFF`` is the image's last 16K, where the header must be for the BIOS to start it [CVB: the fixed bank is assembled at size - 16K; TM: the header is read at $8000] [RC2014]. - ``$C000-$FFFF`` is the selected bank, counted from the image's start [CVB]. - An access to ``$FFC0-$FFFF`` selects bank ``address & (banks - 1)`` [CVB: ``$FFC0 | n``, masked to the size; the runtime's start-up read of $FFC0 at every size]. The slot has no /WR [TM], so a write is the same access (``switch_on_write=False`` gives the reads-only reading, for comparison). - At power-on the window holds bank 0 [RC2014: "bank 0 at boot"]. HYPOTHESIS for the real board: the slot carries no reset [TM], and CVBasic selects a bank before use. - The byte a hotspot read returns is the newly selected bank's: HYPOTHESIS (no source says on which edge the latch takes the address; CVBasic leaves those bytes $FF). - Sizes: 128K-1M [EDW]; a 64K image is taken as itself, which reads the same as the doubled 128K image a 64K game is built into [CVA]. A size that is not a power of two keeps the mask of the next one up and reads open bus in the missing banks: HYPOTHESIS. """ def __init__(self, image: bytes, switch_on_write: bool = True, open_bus: int = 0xFF) -> None: if len(image) <= 0x8000: raise ValueError(f"a MegaCart image is larger than 32K, not {len(image)} bytes") self.image = bytes(image) self.switch_on_write = switch_on_write self.open_bus = open_bus self._banks = _banks(self.image, open_bus) self._mask = _mask_for(len(self._banks)) self._fixed = self._banks[-1] self._missing = bytes((open_bus,)) * _BANK self.bank = 0 self._window = self._banks[0] def _select(self, address: int) -> None: bank = address & self._mask self.bank = bank self._window = self._banks[bank] if bank < len(self._banks) else self._missing def read(self, address: int) -> int: if address < 0xC000: return self._fixed[address & 0x3FFF] if address >= 0xFFC0: self._select(address) return self._window[address & 0x3FFF] def write(self, address: int, value: int) -> None: if self.switch_on_write and address >= 0xFFC0: self._select(address) def peek(self, address: int) -> int: if address < 0xC000: return self._fixed[address & 0x3FFF] return self._window[address & 0x3FFF] class SerialEEPROM: """A 24Cxx two-wire EEPROM as the Activision board's save chip: 256 bytes (24C02) or 32K (24C256) [AA-SAVE; 24C02; 24C256]. The bus side follows the data sheets [24C02 s. 4-8; 24C256 s. 4-8]: a start is SDA falling while SCL is high, a stop SDA rising while SCL is high; a bit is taken on SCL's rising edge; the chip acknowledges a byte by pulling SDA low through the ninth clock; the control byte is ``1010`` + three select bits + R/W; then one word-address byte (24C02, whose select bits are don't-care) or two, high first (24C256, whose select bits must match its A2-A0 pins: tied low here, HYPOTHESIS); a write ends at the stop and wraps inside its page (8 or 64 bytes); a read sends bytes while the master acknowledges, the address rolling over at the array's end. SDA is wired-AND: :meth:`read_sda` is the master's level AND the chip's output. Simplification (HYPOTHESIS for timing only): the internal write cycle (3-5 ms) takes no time, so acknowledge polling succeeds at once. """ # size: (word-address bytes, page) [24C02; 24C256] _PARTS: ClassVar[dict[int, tuple[int, int]]] = {0x100: (1, 8), 0x8000: (2, 64)} def __init__(self, size: int = 256, contents: bytes | None = None) -> None: if size not in self._PARTS: raise ValueError(f"a 24C02 (256) or 24C256 (32768) is modelled, not {size} bytes") self.size = size self._address_bytes, self._page = self._PARTS[size] self.memory = bytearray(b"\xff" * size) # an erased part: HYPOTHESIS ($FF) if contents is not None: self.memory[: len(contents)] = contents[:size] self.scl = True self.sda = True # the master's level self._out = True # the chip's output (True = released) self.pointer = 0 self._state = "idle" # idle, control, address, write, read self._shift = 0 self._bits = 0 self._acking = False self._sending = False self._address_left = 0 self._new_pointer = 0 self._pending: list[tuple[int, int]] = [] # The two lines, as the board's latch drives them. def read_sda(self) -> int: return 1 if (self.sda and self._out) else 0 def write_scl(self, level: bool) -> None: level = bool(level) if level == self.scl: return self.scl = level if level: self._rising() else: self._falling() def write_sda(self, level: bool) -> None: level = bool(level) if level == self.sda: return line_before = self.sda and self._out self.sda = level if self.scl and line_before != (self.sda and self._out): if level: self._stop() else: self._start() # Conditions. def _start(self) -> None: if self._state == "write": self._pending.clear() # a write needs a stop to be committed [24C256 s. 6] self._state = "control" self._shift = self._bits = 0 self._acking = self._sending = False self._out = True def _stop(self) -> None: if self._state == "write": for address, value in self._pending: self.memory[address] = value self._pending.clear() self._state = "idle" self._acking = self._sending = False self._out = True # Clock edges. def _rising(self) -> None: if self._state == "idle": return line = self.sda and self._out if self._acking: return # the chip is driving its acknowledge if self._sending: self._bits += 1 if self._bits == 9: # the master's acknowledge bit # The counter moves past the byte sent either way [24C256 s. 8.2]. self.pointer = (self.pointer + 1) % self.size if line: # no acknowledge: the read ends, wait for a stop [s. 8] self._state = "idle" self._sending = False return self._shift = ((self._shift << 1) | (1 if line else 0)) & 0xFF self._bits += 1 if self._bits == 8: self._acking = self._take(self._shift) if not self._acking: self._state = "idle" def _falling(self) -> None: if self._state == "idle": self._out = True return if self._acking: if self._bits == 8: self._out = False # acknowledge through the ninth clock self._bits = 9 return # The ninth clock is over: release, then start sending if reading. self._acking = False self._out = True self._shift = self._bits = 0 if self._state == "read": self._sending = True self._bits = 0 self._load_bit() return if self._sending: if self._bits == 9: # acknowledged: next byte self._bits = 0 if self._bits < 8: self._load_bit() else: self._out = True # released for the master's acknowledge return self._out = True def _load_bit(self) -> None: value = self.memory[self.pointer] self._out = bool((value >> (7 - self._bits)) & 1) def _take(self, byte: int) -> bool: """A received byte; True if the chip acknowledges it.""" if self._state == "control": if byte >> 4 != 0b1010: return False if self._address_bytes == 2 and (byte >> 1) & 0b111: return False # A2-A0 tied low: HYPOTHESIS if byte & 1: self._state = "read" return True self._state = "address" self._address_left = self._address_bytes self._new_pointer = 0 return True if self._state == "address": self._new_pointer = (self._new_pointer << 8) | byte self._address_left -= 1 if self._address_left == 0: self.pointer = self._new_pointer % self.size self._state = "write" self._pending.clear() return True if self._state == "write": self._pending.append((self.pointer, byte)) page = self.pointer - self.pointer % self._page self.pointer = page + (self.pointer + 1) % self._page return True return False class ActivisionCartridge: """The "Activision PCB" (Team Pixelboy's name): up to 64K in 16K banks and a 24Cxx save chip [AA-SAVE]. - ``$8000-$BFFF``: bank 0, fixed [AA-ACT]. - ``$C000-$FFFF``: the selected bank; ``$FF90``, ``$FFA0``, ``$FFB0`` select banks 1, 2, 3 [AA-ACT: "writes"]. The slot has no /WR [TM]: the board sees accesses, so with ``decode_reads=True`` (the default) a read of those addresses selects too; ``decode_reads=False`` is the writes-only reading of [AA-ACT]. - EEPROM lines: ``$FFC0``/``$FFD0`` clear/set SCL, ``$FFE0``/``$FFF0`` clear/set SDA [AA-ACT]. A read of ``$FF80`` returns the byte of bank 2 or 3 at that address as SDA is low or high [AA-ACT], so a game keeps 0 and 1 there. The whole of ``$FF80-$FFFF`` reads that way: kevtris's stated guess in [AA-ACT], so HYPOTHESIS. - HYPOTHESIS: each register decodes its 16-byte row (``address & $FFF0``), as the documented addresses are spaced; no bank-0 select exists in the list (``$FF80`` is the SDA read); the window holds bank 0 at power-on, as the MegaCart's does [RC2014] (the slot has no reset [TM], so on the real board it is whatever the latch powers up with); with fewer than four banks the number is masked. - ``eeprom=None`` fits a 256-byte part: every documented game on this board carries a save chip [AA-SAVE], and 256 bytes is the smaller (Black Onyx; Boxxle wants ``SerialEEPROM(32768)``). HYPOTHESIS as a default. """ def __init__( self, image: bytes, eeprom: SerialEEPROM | None = None, decode_reads: bool = True, open_bus: int = 0xFF, ) -> None: if len(image) > 0x10000: raise ValueError(f"the Activision board holds at most 64K, not {len(image)} bytes") self.image = bytes(image) self.eeprom = eeprom if eeprom is not None else SerialEEPROM(256) self.decode_reads = decode_reads self._banks = _banks(self.image, open_bus) while len(self._banks) < 2: self._banks.append(bytes((open_bus,)) * _BANK) self._mask = _mask_for(len(self._banks)) self._missing = bytes((open_bus,)) * _BANK self.bank = 0 self._window = self._banks[0] def _bank_bytes(self, bank: int) -> bytes: bank &= self._mask return self._banks[bank] if bank < len(self._banks) else self._missing def _access(self, address: int) -> None: row = address & 0xFFF0 if row in (0xFF90, 0xFFA0, 0xFFB0): self.bank = (row - 0xFF80) >> 4 self._window = self._bank_bytes(self.bank) elif row == 0xFFC0: self.eeprom.write_scl(False) elif row == 0xFFD0: self.eeprom.write_scl(True) elif row == 0xFFE0: self.eeprom.write_sda(False) elif row == 0xFFF0: self.eeprom.write_sda(True) def read(self, address: int) -> int: if address < 0xC000: return self._banks[0][address & 0x3FFF] if address >= 0xFF80: if self.decode_reads: self._access(address) return self._bank_bytes(2 | self.eeprom.read_sda())[address & 0x3FFF] return self._window[address & 0x3FFF] def write(self, address: int, value: int) -> None: if address >= 0xFF80: self._access(address) def peek(self, address: int) -> int: if address < 0xC000: return self._banks[0][address & 0x3FFF] if address >= 0xFF80: return self._bank_bytes(2 | self.eeprom.read_sda())[address & 0x3FFF] return self._window[address & 0x3FFF] BOARDS = ("plain", "megacart", "activision") def cartridge_for(image: bytes, board: str | None = None) -> Cartridge: """The board for an image: by ``board`` (one of :data:`BOARDS`), else by layout. - 32K or less: the plain board [TM]. - Larger: the header ($AA55/$55AA, [TM]) is where each board puts its fixed bank at ``$8000``: in the last 16K for a MegaCart [CVB], in the first for the Activision board [AA-ACT]. So a header in the last 16K means a MegaCart; else a header at the start of an image of 64K or less means the Activision board; anything else is taken as a MegaCart (HYPOTHESIS: the common board; such an image does not start on either). An image with both headers is a MegaCart unless ``board`` says otherwise. The "X-in-1" multicart board of the earlier code is not modelled: no document in hand describes it (docs/cartridge.md). """ if board is not None: if board == "plain": return PlainCartridge(image) if board == "megacart": return MegaCart(image) if board == "activision": return ActivisionCartridge(image) raise ValueError(f"unknown board {board!r}: one of {', '.join(BOARDS)}") if len(image) <= 0x8000: return PlainCartridge(image) last = (-(-len(image) // _BANK) - 1) * _BANK # where MegaCart._fixed starts if bytes(image[last : last + 2]) in _HEADERS: return MegaCart(image) if len(image) <= 0x10000 and bytes(image[0:2]) in _HEADERS: return ActivisionCartridge(image) return MegaCart(image)