#!/usr/bin/env python3 """Census of the CPS-1 family from MAME's machine list and the local ROM sets. No emulator runs a game here. Two inputs, both under the git-ignored ``reference/``: - ``reference/census/mame0285-listxml.xml``: the output of ``mame -listxml`` (made on demand; about 300 MB). - ``reference/src/mame/src/mame/capcom/cps1_v.cpp``: the pinned MAME source, for ``cps1_config_table`` (set name -> CPS-B variant and graphics mapper). Output: a tab-separated table of every set and a summary, written to ``tests/detectors/`` (committed: they are our own counts, not third-party data). python -I scripts/census.py """ from __future__ import annotations import os import re import subprocess import sys import xml.etree.ElementTree as ET from collections import Counter from pathlib import Path ROOT = Path(__file__).resolve().parents[1] LISTXML = ROOT / "reference" / "census" / "mame0285-listxml.xml" VIDEO = ROOT / "reference" / "src" / "mame" / "src" / "mame" / "capcom" / "cps1_v.cpp" OUT = ROOT / "tests" / "detectors" # MAME source files that hold CPS-1 hardware. Everything outside cps1.cpp is a # bootleg board with changed hardware. SOURCES = { "capcom/cps1.cpp": "cps1", "capcom/cps1bl_5205.cpp": "bootleg-5205", "capcom/cps1bl_pic.cpp": "bootleg-pic", "capcom/fcrash.cpp": "bootleg-fcrash", } def local(variable: str, *parts: str) -> Path: """A local ROM folder from an environment variable (no machine path lives here). Unset, it is a path that does not exist, so the folder counts as absent: MAME_ROMPATH (MAME non-merged), MAME_MERGED_ROMPATH, MAME_CHDS (MAME CHDs, merged), FBNEO_DIR (FinalBurn Neo arcade), CURATED_ROMS (a frontend library with mame/ and fbneo/). """ value = os.environ.get(variable) if not value: print(f"{variable} is unset: its folder counts as absent", file=sys.stderr) return Path(value or f"${variable}", *parts) LOCATIONS = { "retrobat-mame": local("CURATED_ROMS", "mame"), "retrobat-fbneo": local("CURATED_ROMS", "fbneo"), "mame-merged": local("MAME_MERGED_ROMPATH"), "mame-nonmerged": local("MAME_ROMPATH"), "fbneo-arcade": local("FBNEO_DIR"), } CHANGER = {"wofch", "sfzch", "sfach", "sfzbch"} def config_table() -> dict[str, tuple[str, str]]: """Set name -> (CPS-B variant, mapper) from MAME's cps1_config_table.""" text = VIDEO.read_text(encoding="utf-8", errors="replace") start = text.index("static const struct CPS1config cps1_config_table[]") table: dict[str, tuple[str, str]] = {} for match in re.finditer(r'\{"(\w+)",\s*(\w+),\s*mapper_(\w+)', text[start:]): table[match.group(1)] = (match.group(2), match.group(3)) return table def machines() -> list[ET.Element]: if not LISTXML.exists(): LISTXML.parent.mkdir(parents=True, exist_ok=True) with LISTXML.open("wb") as handle: subprocess.run(["mame", "-listxml"], stdout=handle, check=True) found = [] for _, element in ET.iterparse(LISTXML, events=("end",)): if element.tag != "machine": continue if element.get("sourcefile") in SOURCES: found.append(element) else: element.clear() return found def region_sizes(machine: ET.Element) -> dict[str, int]: sizes: Counter[str] = Counter() for rom in machine.findall("rom"): if rom.get("status") == "nodump": continue sizes[rom.get("region", "?")] += int(rom.get("size", "0")) return sizes def pal_dumps(machine: ET.Element) -> tuple[str, str]: """The B-board PAL fuse maps in the set: (dumped names, undumped names). MAME's sets carry the PALs as 279-byte GAL16V8 fuse maps. The graphics mapper is the PAL that is not one of the fixed I/O or program-decode PALs. """ good, missing = [], [] for rom in machine.findall("rom"): if rom.get("region") != "bboardplds": continue (missing if rom.get("status") in ("nodump", "baddump") else good).append(rom.get("name", "")) return " ".join(good), " ".join(missing) def sound(machine: ET.Element) -> str: chips = {chip.get("name", "") for chip in machine.findall("chip")} names = " ".join(sorted(chips)).lower() if "q-sound" in names or "qsound" in names: return "qsound" if "ym2151" in names and "msm6295" in names.replace("oki ", "").replace("okim", "msm"): return "ym2151+oki" parts = [n for n in sorted(chips) if "speaker" not in n.lower() and "68000" not in n and "Z80" not in n] return "other:" + "/".join(parts) if parts else "none" def clock(machine: ET.Element, tag: str) -> str: for chip in machine.findall("chip"): if chip.get("tag") == tag: return f"{int(chip.get('clock', '0')) / 1e6:g}" return "" def is_bootleg(machine: ET.Element, kind: str) -> bool: maker = (machine.findtext("manufacturer") or "").lower() return kind != "cps1" or "bootleg" in maker or "hack" in maker def main() -> int: table = config_table() present = {key: {p.stem for p in path.iterdir()} if path.is_dir() else set() for key, path in LOCATIONS.items()} rows = [] for machine in machines(): name = machine.get("name", "") kind = SOURCES[machine.get("sourcefile", "")] cpsb, mapper = table.get(name, ("(none)", "(none)")) sizes = region_sizes(machine) driver = machine.find("driver") pals_good, pals_missing = pal_dumps(machine) rows.append( { "set": name, "parent": machine.get("cloneof", ""), "year": machine.findtext("year") or "", "maker": machine.findtext("manufacturer") or "", "title": machine.findtext("description") or "", "source": kind, "class": "changer" if name in CHANGER else "bootleg" if is_bootleg(machine, kind) else "capcom", "cpsb": cpsb, "mapper": mapper, "sound": sound(machine), "m68k_mhz": clock(machine, "maincpu"), "z80_mhz": clock(machine, "audiocpu"), "prg": sizes.get("maincpu", 0), "gfx": sizes.get("gfx", 0), "z80": sizes.get("audiocpu", 0), "oki": sizes.get("oki", 0), "qsound": sizes.get("qsound", 0), "status": driver.get("status", "") if driver is not None else "", "bboard_pals": pals_good, "bboard_pals_undumped": pals_missing, **{key: "y" if name in names else "" for key, names in present.items()}, } ) rows.sort(key=lambda r: (r["class"], r["parent"] or r["set"], r["parent"] != "", r["set"])) OUT.mkdir(parents=True, exist_ok=True) columns = list(rows[0]) with (OUT / "census-mame0285-sets.tsv").open("w", encoding="utf-8") as handle: handle.write("\t".join(columns) + "\n") for row in rows: handle.write("\t".join(str(row[c]) for c in columns) + "\n") lines = ["CPS-1 census from `mame -listxml` (MAME 0.285) and the local sets; no emulator ran a game.", ""] for cls in ("capcom", "changer", "bootleg"): group = [r for r in rows if r["class"] == cls] parents = [r for r in group if not r["parent"]] lines.append(f"{cls}: {len(group)} sets, {len(parents)} parents, {len(group) - len(parents)} clones") for key in LOCATIONS: have = sum(1 for r in group if r[key]) have_parents = sum(1 for r in parents if r[key]) lines.append(f" present in {key}: {have} sets ({have_parents} parents)") lines.append("") official = [r for r in rows if r["class"] != "bootleg"] lines.append("sound hardware (capcom + changer): " + ", ".join(f"{k} {v}" for k, v in sorted(Counter(r["sound"] for r in official).items()))) lines.append("68000 clock MHz (capcom + changer): " + ", ".join(f"{k} MHz {v}" for k, v in sorted(Counter(r["m68k_mhz"] for r in official).items()))) lines.append("CPS-B variant (capcom + changer sets): " + ", ".join(f"{k} {v}" for k, v in sorted(Counter(r["cpsb"] for r in official).items()))) lines.append("distinct graphics mappers (capcom + changer): " + str(len({r["mapper"] for r in official}))) lines.append("MAME driver status (capcom + changer): " + ", ".join(f"{k} {v}" for k, v in sorted(Counter(r["status"] for r in official).items()))) undumped = [r for r in official if r["bboard_pals_undumped"]] lines.append( f"B-board PAL fuse maps (capcom + changer): {sum(1 for r in official if r['bboard_pals'])} sets carry at least one, " f"{len(undumped)} sets list an undumped one: " + ", ".join(f"{r['set']} ({r['bboard_pals_undumped']})" for r in undumped) ) lines.append("bootleg sets by MAME source: " + ", ".join(f"{k} {v}" for k, v in sorted(Counter(r["source"] for r in rows if r["class"] == "bootleg").items()))) lines.append("") lines.append("capcom + changer parents (set, year, CPS-B, mapper, sound, 68000 MHz, program/graphics/Z80/OKI/QSound ROM bytes, clones):") for row in official: if row["parent"]: continue clones = sum(1 for r in official if r["parent"] == row["set"]) lines.append( f" {row['set']:<10} {row['year']} {row['cpsb']:<13} {row['mapper']:<9} {row['sound']:<11} {row['m68k_mhz']:>2} " f"{row['prg']:>8} {row['gfx']:>8} {row['z80']:>7} {row['oki']:>7} {row['qsound']:>8} clones {clones:>2} {row['title']}" ) (OUT / "census-mame0285-summary.txt").write_text("\n".join(lines) + "\n", encoding="utf-8") print("\n".join(lines)) return 0 if __name__ == "__main__": sys.exit(main())