#!/usr/bin/env python3 """Census of the CPS-2 sets: MAME 0.285 -listxml against the local ROM trees. Reads the XML that ``mame -listxml`` prints for the machines of ``capcom/cps2.cpp`` (regenerated into reference/mame-listxml/ when missing) and looks for each set's zip in the local trees. Nothing is run and no ROM is copied; zips are opened read-only to list their members and CRCs. python -I scripts/census.py # summary on stdout python -I scripts/census.py --table # one row per set (tab separated) python -I scripts/census.py --pairs # encrypted/decrypted pairs to test the cipher on """ from __future__ import annotations import argparse import os import re import subprocess import sys import xml.etree.ElementTree as ET import zipfile from collections import Counter from pathlib import Path ROOT = Path(__file__).resolve().parents[1] XML = ROOT / "reference" / "mame-listxml" / "cps2.xml" 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) TREES = { "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"), } SOURCE = "capcom/cps2.cpp" def listxml() -> ET.Element: if not XML.exists(): XML.parent.mkdir(parents=True, exist_ok=True) source = subprocess.run( ["mame", "-listsource"], capture_output=True, text=True, check=True ).stdout names = [line.split()[0] for line in source.splitlines() if line.endswith(SOURCE)] XML.write_bytes( subprocess.run(["mame", "-listxml", *names], capture_output=True, check=True).stdout ) return ET.parse(XML).getroot() def region_of(description: str) -> str: for word in ("bootleg", "Phoenix Edition", "decrypted"): if word in description: return word # The region is the first word of the parenthesised group holding the # six-digit build date: "(USA 960620)", "(CPS2, USA 951006, SAMPLE Version)", # "(Japan 980123) (Single PCB)". for group in re.findall(r"\(([^()]*)\)", description): if re.search(r"\b\d{6}\b", group): return group.removeprefix("CPS2, ").split(" ")[0] return "?" def kind_of(machine: ET.Element) -> str: description = machine.findtext("description", "") has_key = any(rom.get("region") == "key" for rom in machine.findall("rom")) if "Phoenix Edition" in description: return "phoenix" if "bootleg" in description.lower() or machine.findtext("manufacturer", "") == "bootleg": return "bootleg-keyed" if has_key else "bootleg-decrypted" if not has_key: return "no-key" return "original" def zip_crcs(path: Path) -> dict[str, int]: try: with zipfile.ZipFile(path) as archive: return {info.filename: info.CRC for info in archive.infolist()} except (OSError, zipfile.BadZipFile): return {} def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--table", action="store_true") parser.add_argument("--pairs", action="store_true") args = parser.parse_args() machines = [ m for m in listxml().findall("machine") if m.get("sourcefile") == SOURCE and m.get("isdevice") != "yes" ] # fmt: skip by_name = {m.get("name"): m for m in machines} rows = [] for m in machines: name = m.get("name") roms = m.findall("rom") size = lambda region: sum( # noqa: E731 int(r.get("size")) for r in roms if r.get("region") == region ) keys = [r for r in roms if r.get("region") == "key"] present = {tree: (path / f"{name}.zip").exists() for tree, path in TREES.items()} rows.append( { "name": name, "parent": m.get("cloneof") or "", "year": m.findtext("year", ""), "kind": kind_of(m), "region": region_of(m.findtext("description", "")), "maincpu": size("maincpu"), "gfx": size("gfx"), "audiocpu": size("audiocpu"), "qsound": size("qsound"), "key": keys[0].get("name") if keys else "", "key_sha1": keys[0].get("sha1") if keys else "", "status": m.find("driver").get("status") if m.find("driver") is not None else "", "present": present, "description": m.findtext("description", ""), } ) if args.table: print("name\tparent\tyear\tkind\tregion\tmaincpu\tgfx\taudiocpu\tqsound\tkey\tstatus\t" + "\t".join(TREES) + "\tdescription") # fmt: skip for row in sorted(rows, key=lambda r: (r["parent"] or r["name"], r["parent"] != "", r["name"])): print("\t".join( [row["name"], row["parent"], row["year"], row["kind"], row["region"], str(row["maincpu"]), str(row["gfx"]), str(row["audiocpu"]), str(row["qsound"]), row["key"], row["status"]] + ["y" if row["present"][tree] else "-" for tree in TREES] + [row["description"]] )) # fmt: skip return 0 if args.pairs: # A decrypted set (no key, or the dead-board key) whose parent family holds a keyed # set with program ROMs of the same sizes at the same offsets. tree = TREES["mame-nonmerged"] for row in sorted(rows, key=lambda r: r["name"]): if row["kind"] not in ("phoenix", "bootleg-decrypted", "no-key"): continue family = row["parent"] or row["name"] layout = lambda m: [ # noqa: E731 (r.get("offset"), r.get("size")) for r in m.findall("rom") if r.get("region") == "maincpu" ] # fmt: skip mine = layout(by_name[row["name"]]) partners = [ other["name"] for other in rows if other["kind"] == "original" and (other["parent"] or other["name"]) == family and layout(by_name[other["name"]]) == mine and (tree / f"{other['name']}.zip").exists() ] # fmt: skip here = "y" if (tree / f"{row['name']}.zip").exists() else "-" print(f"{row['name']}\t{row['kind']}\t{here}\t{','.join(partners)}") return 0 parents = [r for r in rows if not r["parent"]] print(f"machines in {SOURCE}: {len(rows)} ({len(parents)} parents, {len(rows) - len(parents)} clones)") print("by kind:", dict(Counter(r["kind"] for r in rows))) print("parents by kind:", dict(Counter(r["kind"] for r in parents))) print("by year:", dict(sorted(Counter(r["year"] for r in rows).items()))) print("parents by year:", dict(sorted(Counter(r["year"] for r in parents).items()))) print("originals by region:", dict(Counter(r["region"] for r in rows if r["kind"] == "original").most_common())) print("driver status:", dict(Counter(r["status"] for r in rows))) print("distinct key files:", len({r["key_sha1"] for r in rows if r["key"]}), "sets with a key:", sum(1 for r in rows if r["key"])) for tree in TREES: have = [r for r in rows if r["present"][tree]] print(f"{tree}: {len(have)} of {len(rows)} sets, " f"{sum(1 for r in have if not r['parent'])} of {len(parents)} parents") for region in ("maincpu", "gfx", "audiocpu", "qsound"): sizes = [r[region] for r in parents] print(f"{region} bytes over parents: min {min(sizes)}, max {max(sizes)}") # Key files inside the non-merged zips: present, and matching MAME's CRC? tree = TREES["mame-nonmerged"] good = bad = missing = 0 for m in machines: for rom in m.findall("rom"): if rom.get("region") != "key": continue crcs = zip_crcs(tree / f"{m.get('name')}.zip") crc = crcs.get(rom.get("name")) if crc is None: missing += 1 elif crc == int(rom.get("crc"), 16): good += 1 else: bad += 1 print(f"key files in mame-nonmerged zips: {good} match MAME's CRC, {bad} differ, {missing} missing") return 0 if __name__ == "__main__": sys.exit(main())