"""Cartridges: ROM images, their boards (mappers), and board detection. Sources: the wiki's Mappers.pmwiki ("the wiki" below); MAME 0.285 ``src/devices/bus/sega8/rom.cpp`` for the power-on banks and the mirroring of small ROMs (a detector, used where the wiki is silent); MAME's software lists (``/usr/share/games/mame/hash/{sg1000,sms,gamegear}.xml``) to identify boards by SHA-1. A cartridge answers :meth:`read` and :meth:`write` for $0000-$BFFF. The Sega mapper's registers sit at $FFFC-$FFFF, in the console's RAM mirror, so the *board* forwards those writes to :meth:`Cartridge.write_register` (the wiki: "the control registers overlap in the memory map with a RAM mirror"). """ from __future__ import annotations import hashlib import zipfile from dataclasses import dataclass, field from functools import cache from pathlib import Path from typing import ClassVar from xml.etree import ElementTree BANK = 0x4000 IMAGE_SUFFIXES = (".sms", ".sg", ".gg", ".sc", ".sf", ".sf7", ".bin") MAME_HASH = Path("/usr/share/games/mame/hash") def load_image(path: Path) -> bytes: """Read a ROM image, from a zip if need be, dropping a 512-byte copier header.""" if zipfile.is_zipfile(path): with zipfile.ZipFile(path) as archive: names = [n for n in archive.namelist() if n.lower().endswith(IMAGE_SUFFIXES)] names.sort(key=lambda n: IMAGE_SUFFIXES.index("." + n.lower().rsplit(".", 1)[-1])) if not names: raise ValueError(f"{path}: no ROM image inside") data = archive.read(names[0]) else: data = path.read_bytes() if len(data) % BANK == 512: data = data[512:] return data def _banked(image: bytes) -> bytes: """Pad to a whole number of 16 KB banks. Smaller than one bank: mirrored, as an 8 KB ROM with its upper address lines unconnected would be. Otherwise rounded up to whole banks with zeros, as MAME 0.285's loader does (sega8_slot.cpp: ``len = ((len >> 14) + 1) << 14``); no source here says what a real 24 KB board returns above its ROM. """ if len(image) < BANK: return (image * (BANK // max(len(image), 1) + 1))[:BANK] remainder = len(image) % BANK return image + bytes(BANK - remainder) if remainder else image @cache def _mame_boards() -> dict[str, tuple[str, str, str]]: """SHA-1 -> (software list, set name, slot feature or "rom"), from MAME's hash files.""" boards: dict[str, tuple[str, str, str]] = {} for listname in ("sg1000", "sms", "gamegear", "sc3000_cart"): path = MAME_HASH / f"{listname}.xml" if not path.exists(): continue for software in ElementTree.parse(path).getroot().iter("software"): slot = "rom" for feature in software.iter("feature"): if feature.get("name") == "slot": slot = feature.get("value", "rom") for rom in software.iter("rom"): sha1 = rom.get("sha1") if sha1: boards[sha1] = (listname, software.get("name", ""), slot) return boards def identify(image: bytes) -> tuple[str, str, str] | None: """MAME's software-list entry for this exact image, or None if it is not listed.""" return _mame_boards().get(hashlib.sha1(image).hexdigest()) def has_codemasters_header(image: bytes) -> bool: """A valid Codemasters header at $7FE0 (the wiki's CodemastersHeader.pmwiki). "$7fea-$7fef are all zero"; the checksum at $7FE6 is the 16-bit little-endian sum of the whole file "except for the Sega header at $7ff0 to $7fff", and the word after it is $10000 minus the checksum. Every Codemasters-mapper image in MAME's software lists carries one and no other image does, except three Korean and prototype boards of that mapper not made by Codemasters. """ if len(image) < 0x8000 or len(image) % 2 or any(image[0x7FEA:0x7FF0]): return False summed = image[:0x7FF0] + image[0x8000:] total = (sum(summed[0::2]) + (sum(summed[1::2]) << 8)) & 0xFFFF checksum = image[0x7FE6] | image[0x7FE7] << 8 complement = image[0x7FE8] | image[0x7FE9] << 8 return total == checksum and (checksum + complement) & 0xFFFF == 0 def board_for(image: bytes) -> str: """The board: MAME's software list, else a Codemasters header, else the Sega board.""" listed = identify(image) if listed: return listed[2] return "codemasters" if has_codemasters_header(image) else "rom" @dataclass class Cartridge: """A ROM on a Sega-mapper board: three 16 KB slots and optional cartridge RAM. Plain SG-1000 and small SMS cartridges are the same board with the registers never written: power-on banks 0, 1, 2 (MAME ``late_bank_setup``), each taken modulo the number of banks, so a 32 KB ROM shows bank 0 again at $8000. """ image: bytes ram: bytearray = field(default_factory=lambda: bytearray(0x8000)) board: str = "sega" banks: list[int] = field(default_factory=lambda: [0, 1, 2]) control: int = 0 # $FFFC #: RAM the board puts at $C000-$FFFF in place of the console's own, if any. work_ram: bytearray | None = field(default=None, init=False, repr=False) def __post_init__(self) -> None: self.rom = _banked(self.image) self.bank_count = len(self.rom) // BANK self.banks = [bank % self.bank_count for bank in self.banks] @classmethod def from_file(cls, path: Path, board: str | None = None) -> Cartridge: return cls.from_file_image(load_image(path), board) @classmethod def from_file_image(cls, image: bytes, board: str | None = None) -> Cartridge: """A cartridge for an image, its board from MAME's software lists if not given.""" return make_cartridge(image, board_for(image) if board is None else board) # -- the bus -------------------------------------------------------------- def read(self, address: int) -> int: slot = address >> 14 if slot == 2 and self.control & 0x08: # $FFFC bit 3: cartridge RAM over slot 2, bank by bit 2 (the wiki). return self.ram[((self.control & 0x04) << 12 | (address & 0x3FFF)) & 0x7FFF] if address < 0x400: return self.rom[address] # "the first 1KB is unaffected" (the wiki) return self.rom[self.banks[slot] * BANK + (address & 0x3FFF)] def write(self, address: int, value: int) -> None: if address >> 14 == 2 and self.control & 0x08: self.ram[((self.control & 0x04) << 12 | (address & 0x3FFF)) & 0x7FFF] = value def write_register(self, address: int, value: int) -> None: """$FFFC-$FFFF (the wiki, "The Sega mapper"). Bank numbers are taken modulo the ROM's bank count: "Provided the ROM is a power-of-two size ... ROM mirroring will nullify the effect". Bank shifting ($FFFC bits 1-0) is documented but "no known software uses this feature"; it is not modelled. """ if address == 0xFFFC: self.control = value elif address >= 0xFFFD: self.banks[address - 0xFFFD] = value % self.bank_count @dataclass class CodemastersCartridge(Cartridge): """The Codemasters board: bank registers at $0000, $4000, $8000 (the wiki). Ernie Els Golf has 8 KB of RAM on the cartridge: "If the byte written to $4000 has the high bit set ($80) then the upper 8KB of slot 2 (from $a000 to $c000) is mapped to this on-cart RAM" (the wiki). Such a write leaves slot 1's bank as it was, as in MAME 0.285 (rom.cpp); the wiki does not say. No other Codemasters game sets that bit, so every board here has the RAM. """ board: str = "codemasters" banks: list[int] = field(default_factory=lambda: [0, 1, 0]) # "banks 0, 1 and 0" ram_enabled: bool = False def read(self, address: int) -> int: if self.ram_enabled and address >> 13 == 5: return self.ram[address & 0x1FFF] return self.rom[self.banks[address >> 14] * BANK + (address & 0x3FFF)] def write(self, address: int, value: int) -> None: if address == 0x4000: self.ram_enabled = bool(value & 0x80) if self.ram_enabled: return if address & 0x3FFF == 0: self.banks[address >> 14] = value % self.bank_count elif self.ram_enabled and address >> 13 == 5: self.ram[address & 0x1FFF] = value def write_register(self, address: int, value: int) -> None: pass # "there is no RAM mirroring of mapper writes" @dataclass class KoreanCartridge(Cartridge): """The "Korean" board: slots 0 and 1 fixed, slot 2 chosen by a write to $A000. "Slots 0 and 1 are fixed to banks 0 and 1 of ROM respectively, while the bank mapped to slot 2 is selected by a byte written to address $a000" (the wiki). """ board: str = "korean" def write(self, address: int, value: int) -> None: if address == 0xA000: self.banks[2] = value % self.bank_count def write_register(self, address: int, value: int) -> None: pass @dataclass class UnbankedCartridge(Cartridge): """A ROM of up to 48 KB with no mapper at all (MAME's ``korean_nb``). These Korean games write to $FFFC-$FFFF as plain RAM; a Sega mapper there would page their ROM away. """ board: str = "korean_nb" def write_register(self, address: int, value: int) -> None: pass @dataclass class MSXCartridge(Cartridge): """The MSX-style board of Zemina's Korean ports: 8 KB banks, registers at $0000-$0003. The wiki ("MSX and Nemesis mappers"): $0000 selects the bank at $8000, $0001 at $A000, $0002 at $4000, $0003 at $6000; "the first 16K of ROM is fixed at $0000-$3fff". The power-on banks are 0 to 5 in order (MAME 0.285, ``late_bank_setup``; the wiki does not say). """ board: str = "zemina" PAGE: ClassVar[int] = 0x2000 REGISTERS: ClassVar[tuple[int, ...]] = (4, 5, 2, 3) # $0000-$0003 -> 8 KB slot def __post_init__(self) -> None: super().__post_init__() self.page_count = len(self.rom) // self.PAGE self.pages = [page % self.page_count for page in range(6)] def read(self, address: int) -> int: return self.rom[self.pages[address >> 13] * self.PAGE + (address & 0x1FFF)] def write(self, address: int, value: int) -> None: if address < 4: self.pages[self.REGISTERS[address]] = value % self.page_count def write_register(self, address: int, value: int) -> None: pass @dataclass class NemesisCartridge(MSXCartridge): """Nemesis: the MSX board with the ROM's last 8 KB at $0000. "The first 8K of address space ($0000-$1fff) will always map to the final 8K page of ROM" (the wiki). """ board: str = "nemesis" def __post_init__(self) -> None: super().__post_init__() self.pages[0] = self.page_count - 1 @dataclass class JanggunCartridge(MSXCartridge): """Janggun-ui Adeul: 8 KB banks at $4000-$A000, 16 KB ones at $FFFE and $FFFF. The wiki's "Janggun Mapper" table. A bank number with bit 7 set reads the bank with each byte's bits reversed: MAME 0.285 (rom.cpp) reads the game as expecting 256 banks, the upper half "with bytes in reverse order probably as a shortcut to get sprite flipping for free". The wiki also speaks of flags set by bit 6 of a write to $FFFE or $FFFF; MAME has none and neither does this. """ board: str = "janggun" REVERSED: ClassVar[bytes] = bytes(int(f"{value:08b}"[::-1], 2) for value in range(256)) def __post_init__(self) -> None: super().__post_init__() self.pages = list(range(6)) def read(self, address: int) -> int: page = self.pages[address >> 13] value = self.rom[(page & 0x3F) % self.page_count * self.PAGE + (address & 0x1FFF)] return self.REVERSED[value] if page & 0x80 else value def write(self, address: int, value: int) -> None: if address in (0x4000, 0x6000, 0x8000, 0xA000): self.pages[address >> 13] = value def write_register(self, address: int, value: int) -> None: if address >= 0xFFFD: slot = (address - 0xFFFD) * 2 bank = value % self.bank_count self.pages[slot : slot + 2] = [bank * 2, bank * 2 + 1] @dataclass class FourPakCartridge(Cartridge): """HES's 4 PAK All Action: registers at $3FFE, $7FFF and $BFFF. No document here describes it; this is MAME 0.285's model (rom.cpp): each register selects its slot's 16 KB bank, and bits 5-4 of the first are added to the third's, which is how the menu puts each game's banks behind its own numbering. All three banks are 0 at power-on. """ board: str = "4pak" banks: list[int] = field(default_factory=lambda: [0, 0, 0]) registers: list[int] = field(default_factory=lambda: [0, 0, 0]) def read(self, address: int) -> int: return self.rom[self.banks[address >> 14] * BANK + (address & 0x3FFF)] def write(self, address: int, value: int) -> None: if address not in (0x3FFE, 0x7FFF, 0xBFFF): return slot = address >> 14 self.registers[slot] = value if slot < 2: self.banks[slot] = value % self.bank_count self.banks[2] = ((self.registers[0] & 0x30) + self.registers[2]) % self.bank_count def write_register(self, address: int, value: int) -> None: pass @dataclass class HiComCartridge(Cartridge): """Hi-Com's 3-in-1 and 8-in-1: $FFFF selects a 32 KB game at $0000-$7FFF. MAME 0.285's model (rom.cpp); no document here describes the board. $8000-$BFFF shows the ROM's first 16 KB. """ board: str = "hicom" game: int = 0 def read(self, address: int) -> int: if address >= 0x8000: return self.rom[address & 0x3FFF] return self.rom[(self.game * 0x8000 + address) % len(self.rom)] def write(self, address: int, value: int) -> None: pass def write_register(self, address: int, value: int) -> None: if address == 0xFFFF: self.game = value @dataclass class Korean188Cartridge(Cartridge): """Game Mo-eumjip 188 Hap: a write to $2000-$3FFF selects 32 KB at $4000-$BFFF. MAME 0.285's model (rom.cpp), which notes that some of the menu's entries do not load under it: the register, inverted in its low five bits, is the 8 KB page that appears at $4000. $0000-$3FFF is the ROM's first 16 KB. """ board: str = "korean_188in1" register: int = 0 def read(self, address: int) -> int: if address < 0x4000: return self.rom[address] page = (self.register ^ 0x1F) % (self.bank_count * 2) return self.rom[(page * 0x2000 + address - 0x4000) % len(self.rom)] def write(self, address: int, value: int) -> None: if address & 0x6000 == 0x2000: self.register = value def write_register(self, address: int, value: int) -> None: pass @dataclass class RAMCartridge(Cartridge): """An unbanked ROM with RAM on the cartridge at fixed addresses (SG-1000 boards). ``RAM_AT`` is the address range the RAM answers in and ``RAM_SIZE`` its size (mirrored through the range). ``WORK_RAM`` is the size of RAM the board puts at $C000-$FFFF in place of the console's 1 KB, or 0. All from MAME 0.285 (rom.cpp), whose own comments mark the mirroring as assumed: - Othello: 2 KB at $8000-$9FFF. The Castle: 8 KB there. - Dahjee's Taiwanese ports of MSX games, sold with a RAM expansion: type A has 8 KB at $2000-$3FFF, type B has 8 KB at $C000-$FFFF. - SC-3000 BASIC Level III A (16 KB at $8000-$BFFF: "two of them have TMS4416 16Kx4 DRAMs, the other two are empty", sc3000h section 3) and Music Editor (8 KB at $8000-$9FFF): programs for the SC-3000's keyboard (machine ``sc3000``). """ RAM_AT: ClassVar[range] = range(0) RAM_SIZE: ClassVar[int] = 0x2000 WORK_RAM: ClassVar[int] = 0 def __post_init__(self) -> None: super().__post_init__() self.work_ram = bytearray(self.WORK_RAM) if self.WORK_RAM else None def read(self, address: int) -> int: if address in self.RAM_AT: return self.ram[address & (self.RAM_SIZE - 1)] return self.rom[address % len(self.rom)] def write(self, address: int, value: int) -> None: if address in self.RAM_AT: self.ram[address & (self.RAM_SIZE - 1)] = value def write_register(self, address: int, value: int) -> None: pass class OthelloCartridge(RAMCartridge): RAM_AT = range(0x8000, 0xA000) RAM_SIZE = 0x800 class CastleCartridge(RAMCartridge): RAM_AT = range(0x8000, 0xA000) class DahjeeACartridge(RAMCartridge): RAM_AT = range(0x2000, 0x4000) class DahjeeBCartridge(RAMCartridge): WORK_RAM = 0x2000 class BasicLevel3Cartridge(RAMCartridge): RAM_AT = range(0x8000, 0xC000) RAM_SIZE = 0x4000 class BasicLevel3BCartridge(BasicLevel3Cartridge): """BASIC Level III B: the same ROM with all four DRAM sockets filled. "$C000-$FFFF : DRAM (latter 16K if work RAM disabled and missing DRAM chips added)" (sc3000h section 3). MAME 0.285 gives every Level III image this board on its SC-3000; the image alone cannot say which cartridge it came from, so it is chosen by name (``level3b``). """ WORK_RAM = 0x4000 class MusicEditorCartridge(RAMCartridge): RAM_AT = range(0x8000, 0xA000) @dataclass class TerebiOekakiCartridge(Cartridge): """Terebi Oekaki: the cartridge of Sega's graphic board (TerebiOekaki-SG.pmwiki). $6000 write, bit 0: "write 1 to select X axis, 0 to select Y axis". $8000 read: bit 7 BUSY, bit 0 PRESS, which "reads 0 when the button on the graphic board is pressed, else 1". $A000 read: the sampled position. ``pen`` is the position on the board, or None with the pen lifted. A sample is taken when the axis is written, X held to 4-251 and Y offset by $20, as MAME 0.285 does (rom.cpp); the board is never busy here. """ board: str = "terebi" pen: tuple[int, int] | None = None position: tuple[int, int] = (0x80, 0x60) sample: int = 0 def read(self, address: int) -> int: if address == 0x8000: return 0 if self.pen is not None else 1 if address == 0xA000: return self.sample return super().read(address) def write(self, address: int, value: int) -> None: if address == 0x6000: x, y = self.pen if self.pen is not None else self.position self.sample = min(max(x, 4), 251) if value & 1 else (y + 0x20) & 0xFF def write_register(self, address: int, value: int) -> None: pass @dataclass class XTerminatorCartridge(Cartridge): """The X-Terminator, a Game Gear cheat cartridge with a slot for the game. Known here only from MAME 0.285 (rom.cpp, "GG X-Terminator"): "When starting up the X-Terminator's ROM is active. In NORMAL mode any read of $38 switches to game ROM", and its RESET button, held at such a read, brings the X-Terminator back. While its own 8 KB ROM is in, 8 KB of RAM sits at $2000-$3FFF and $0007 reads the button (1 = up). ``game`` is the cartridge plugged into it; with none, the game's side reads $FF. The switch's other position is left out: in ACTION mode "any read of $38 switches between game ROM and X-Terminator ROM", and the system looks at each opcode before the CPU fetches it (system.py), which would count as a read. """ board: str = "xterminator" game: Cartridge | None = None reset_held: bool = False active: bool = True def read(self, address: int) -> int: if address == 0x0038: self.active = self.reset_held if not self.active: return self.game.read(address) if self.game is not None else 0xFF if 0x2000 <= address < 0x4000: return self.ram[address & 0x1FFF] if address == 0x0007: return 0 if self.reset_held else 1 return self.image[address % len(self.image)] def write(self, address: int, value: int) -> None: if not self.active: if self.game is not None: self.game.write(address, value) elif 0x2000 <= address < 0x4000: self.ram[address & 0x1FFF] = value def write_register(self, address: int, value: int) -> None: if self.game is not None: self.game.write_register(address, value) @dataclass class EEPROM93C46: """A 93C46 serial EEPROM, 64 words of 16 bits (Microwire: CS, CLK, DI, DO). A command is a start bit, two opcode bits and six address bits, clocked in on CLK's rising edge while CS is high: 10 read, 01 write, 11 erase, and under 00 the address's top two bits choose write-disable, write-all, erase-all and write-enable. A read answers a 0 and then the word, most significant bit first, going on to the next word if clocked further. Programming takes no time here: DO is 1 (ready) as soon as the word is in. """ words: list[int] = field(default_factory=lambda: [0xFFFF] * 64) select: bool = False clock: bool = False data_out: int = 1 writable: bool = False state: str = "idle" # idle, command, read, write, done shift: int = 0 count: int = 0 command: int = 0 def reset(self) -> None: self.select, self.state, self.data_out = False, "idle", 1 def lines(self, select: bool, clock: bool, data_in: bool) -> None: if not select: self.state, self.data_out = "idle", 1 elif clock and not self.clock: self._clock_in(int(data_in)) self.select, self.clock = select, clock def _clock_in(self, bit: int) -> None: if self.state == "idle": if bit: self.state, self.shift, self.count = "command", 0, 0 elif self.state == "command": self.shift = self.shift << 1 | bit self.count += 1 if self.count == 8: self._decode() elif self.state == "read": if self.count == 0: self.shift = self.words[self.command & 0x3F] self.command = self.command & 0xC0 | (self.command + 1) & 0x3F self.data_out = self.shift >> 15 & 1 self.shift = self.shift << 1 & 0xFFFF self.count = (self.count + 1) & 15 elif self.state == "write": self.shift = (self.shift << 1 | bit) & 0xFFFF self.count += 1 if self.count == 16: if self.writable: if self.command >> 6 == 1: self.words[self.command & 0x3F] = self.shift else: self.words = [self.shift] * 64 self.state, self.data_out = "done", 1 def _decode(self) -> None: self.command, self.count, self.shift = self.shift, 0, 0 opcode, address = self.command >> 6, self.command & 0x3F self.state = "done" if opcode == 2: self.state, self.data_out = "read", 0 elif opcode == 1 or (opcode == 0 and address >> 4 == 1): self.state = "write" elif opcode == 3: if self.writable: self.words[address] = 0xFFFF elif address >> 4 == 2: if self.writable: self.words = [0xFFFF] * 64 else: self.writable = address >> 4 == 3 @dataclass class EEPROMCartridge(Cartridge): """A Sega-mapper board with a 93C46 in place of RAM (Game Gear baseball games). MAME 0.285's model (rom.cpp); no document here describes the board. $FFFC bit 3 puts the EEPROM's lines at $8000 and bit 7 resets it. A write there sets DI (bit 0), CLK (bit 1) and CS (bit 2); a read returns the bits last written with bit 1 set and DO in bit 0. """ board: str = "eeprom" eeprom: EEPROM93C46 = field(default_factory=EEPROM93C46) enabled: bool = False written: int = 0 def read(self, address: int) -> int: if address == 0x8000 and self.enabled: return self.written & 0xFC | 0x02 | self.eeprom.data_out if address < 0x400: return self.rom[address] return self.rom[self.banks[address >> 14] * BANK + (address & 0x3FFF)] def write(self, address: int, value: int) -> None: if address == 0x8000 and self.enabled: self.written = value self.eeprom.lines(bool(value & 4), bool(value & 2), bool(value & 1)) def write_register(self, address: int, value: int) -> None: if address == 0xFFFC: if value & 0x80: self.eeprom.reset() self.enabled = bool(value & 0x08) elif address >= 0xFFFD: self.banks[address - 0xFFFD] = value % self.bank_count BOARDS: dict[str, type[Cartridge]] = { "rom": Cartridge, "sega": Cartridge, "codemasters": CodemastersCartridge, "korean": KoreanCartridge, "korean_nb": UnbankedCartridge, "zemina": MSXCartridge, "nemesis": NemesisCartridge, "janggun": JanggunCartridge, "4pak": FourPakCartridge, "hicom": HiComCartridge, "korean_188in1": Korean188Cartridge, "othello": OthelloCartridge, "castle": CastleCartridge, "dahjee_typea": DahjeeACartridge, "dahjee_typeb": DahjeeBCartridge, "level3": BasicLevel3Cartridge, "level3b": BasicLevel3BCartridge, "music_editor": MusicEditorCartridge, "terebi": TerebiOekakiCartridge, "eeprom": EEPROMCartridge, "xterminator": XTerminatorCartridge, } def make_cartridge(image: bytes, board: str = "rom") -> Cartridge: """A cartridge for ``board`` (a MAME slot name); unknown boards raise.""" try: cls = BOARDS[board] except KeyError: raise NotImplementedError(f"cartridge board {board!r} is not modelled yet") from None return cls(image)