# SPDX-License-Identifier: GPL-3.0-or-later """famicom-python's ``mesen_run.py``, as it was (``tools/famicom-python/mesen_run.py`` loads this). Drives a locally built MesenCore.so headless via ctypes and adds the built-in trace logger, which prints the PPU scanline/dot and the CPU cycle count before every instruction. python "$FAMICOM_GPL_TOOLS/mesen_run.py" rom.nes --seconds 2 --trace out.trace --lua script.lua Exit code: the Lua script's emu.stop(code), or -1 on timeout (masked to a byte). Module names kept for famicom-python's scripts, which import them: ``ROOT``, ``LIB``, ``REGIONS``, ``ALPHABET``, ``FRAMES_LUA``, ``decode_frames``, ``run_mesen``, ``configure_for_comparison``, ``load_library``, ``CONSOLE_MODE``, ``MAXIMUM_SPEED`` and the ``NES_CONFIG_*`` offsets. First published under MIT by alewman in famicom-python (``notices/MIT-emulator-family.txt``). """ from __future__ import annotations import argparse import ctypes import os import sys from pathlib import Path from .. import api, nes from ..api import CONSOLE_MODE, MAXIMUM_SPEED, TraceLoggerOptions # noqa: F401 from ..lua import ALPHABET, FRAMES_LUA, decode_frames # noqa: F401 from ..nes import ( # noqa: F401 NES_CONFIG_AUTO_CONFIGURE_INPUT, NES_CONFIG_CHANNEL_VOLUMES, NES_CONFIG_FULL_COLOR_PALETTE, NES_CONFIG_INPUT_SCANLINE, NES_CONFIG_OAM_ROW_CORRUPTION, NES_CONFIG_PORT1_TYPE, NES_CONFIG_PORT2_TYPE, NES_CONFIG_RAM_POWER_ON, NES_CONFIG_REGION, NES_CONFIG_RESTRICT_FIRST_FRAME, NES_CONFIG_SIZE, NES_CONFIG_SPRITES_ENABLED, NES_CONFIG_USER_PALETTE, REGIONS, NesConfig, ) # The checkout comes from FAMICOM_PYTHON_ROOT, which famicom-python's scripts/gpl_tools.py # sets, else the working directory. ROOT = Path(os.environ.get("FAMICOM_PYTHON_ROOT", Path.cwd())).resolve() # The library (from mesen2-runner 0.3.0 as run.py finds it, after the two old places): # MESEN_LIB, else MESEN_CORE, else the checkout's hand build under reference/build-mesen2 if it # exists, else this tool's own build (build.sh). So with neither variable set the shim runs on # the library build.sh made, as run.py does. (MesenCE, Mesen2's successor, has the same # NesConfig layout, measured from the running library.) HAND_BUILD = ROOT / api.CHECKOUT_BUILD def find_lib() -> Path: for name in ("MESEN_LIB", "MESEN_CORE"): if os.environ.get(name): return Path(os.environ[name]) return HAND_BUILD if HAND_BUILD.exists() else api.OWN_BUILD LIB = find_lib() def require_lib() -> None: """Stop with exit status 3 and say what to set when there is no library.""" if not LIB.exists(): print(f"no MesenCore.so at {LIB}: run $EMU_TOOLS_GPL/tools/mesen2/build.sh (the shim then " "finds its build), or set MESEN_CORE (or MESEN_LIB) to a library", file=sys.stderr) raise SystemExit(3) CPU_NES = 8 # CpuType::Nes NES_CONTROLLER = nes.nes_controller(LIB) def load_library() -> ctypes.CDLL: return nes.load(LIB) def configure_for_comparison( m: ctypes.CDLL, region: int = 1, ppu_reset_at_power: bool = True, oam_row_corruption: bool = True, ) -> None: """Make Mesen2's frames comparable with the board's (``nes.configure_for_comparison``).""" nes.configure_for_comparison(m, region, ppu_reset_at_power, oam_row_corruption, NES_CONTROLLER) def run_mesen( rom: Path, *, lua: bytes | None = None, lua_name: str = "script.lua", seconds: float = 2.0, home: Path = Path("mesen-home"), trace: Path | None = None, until: str | None = None, max_speed: bool = True, for_comparison: bool = False, region: int = 1, ppu_reset_at_power: bool = True, collect: dict[str, str] | None = None, oam_row_corruption: bool = True, ) -> tuple[int, str, float]: """``nes.run`` on ``LIB`` (see there).""" return nes.run( LIB, rom, lua=lua, lua_name=lua_name, seconds=seconds, home=home, trace=trace, until=until, max_speed=max_speed, for_comparison=for_comparison, region=region, ppu_reset_at_power=ppu_reset_at_power, collect=collect, oam_row_corruption=oam_row_corruption, ) def main() -> int: p = argparse.ArgumentParser() p.add_argument("rom", type=Path) p.add_argument("--seconds", type=float, default=2.0, help="wall-clock timeout") p.add_argument("--trace", type=Path) p.add_argument("--lua", type=Path) p.add_argument("--home", type=Path, default=Path("mesen-home")) a = p.parse_args() require_lib() result, log, wall = run_mesen( a.rom, lua=a.lua.read_bytes() if a.lua else None, lua_name=a.lua.name if a.lua else "script.lua", seconds=a.seconds, home=a.home, trace=a.trace, ) if log: print(log) print(f"stop code {result} after {wall:.1f} s") return result