# SPDX-License-Identifier: GPL-3.0-or-later """The PC Engine adapter: Mesen2's PcEngineConfig, pad presses, and a run that logs a frame. From pcengine-python's ``scripts/mesen_run.py`` and ``scripts/presses.py`` (MIT, alewman, first published in pcengine-python; ``notices/MIT-emulator-family.txt``), parked 2026-11-21 and regrouped here 2026-11-23 without changing what they do. Cartridge games need no BIOS; CD games need the System Card, which the player supplies. """ from __future__ import annotations import ctypes import struct import time from pathlib import Path from . import api from .lua import DONE PCE_CONFIG_SIZE = 8080 #: Count frames; at frame ``{frames}`` log the screen buffer as hex, then ``{done}``. LUA = """\ local frames = 0 emu.addEventCallback(function() frames = frames + 1 if frames == {frames} then local buf = emu.getScreenBuffer() local parts = {{}} for i = 1, #buf do parts[i] = string.format("%06x", buf[i]) end emu.log("PIXELS " .. #buf .. " " .. table.concat(parts)) emu.log("{done}") end end, emu.eventType.endFrame) """ class PceConfig(ctypes.Structure): """Mesen2's ``PcEngineConfig`` by value: 8,080 bytes of opaque storage. Its layout was measured by compiling ``offsetof`` against the pinned settings header with g++ (pcengine-python, 2026-10-23). The library has no default palette (the UI sets one, an RGB333 -> RGB table), so without this call every PC Engine frame is black; and at maximum speed the core skips rendering frames unless frame skipping is disabled. """ _fields_ = [("raw", ctypes.c_ubyte * PCE_CONFIG_SIZE)] def pce_config_bytes(no_sprites: bool = False, pad: bool = False, ram: int = 1) -> bytes: """``ram``: RamPowerOnState, 1 all zeros (deterministic; the default here), 2 all ones, 0 random (Mesen2's default).""" raw = bytearray(PCE_CONFIG_SIZE) if pad: # Port1.Type = ControllerType::PceController (39; offset 988 measured 2026-11-12) struct.pack_into("> 6) & 7, (i >> 3) & 7, i & 7 rgb = (r * 255 // 7) << 16 | (g * 255 // 7) << 8 | (b * 255 // 7) struct.pack_into(" PceConfig: return PceConfig.from_buffer_copy(pce_config_bytes(no_sprites, pad, ram)) # -- pad presses (pcengine-python's scripts/presses.py, the parts a Mesen2 run needs) ------- # A press is ``BUTTONS@FRAME+HOLD``: the buttons (joined with ``-``) are held on pad 1 while # the count of completed frames is in FRAME .. FRAME+HOLD-1 (``+HOLD`` omitted = 1 frame). NAMES = ("up", "down", "left", "right", "i", "ii", "select", "run") Press = tuple[frozenset[str], int, int] # buttons, first frame, frames held def parse_presses(specs: list[str]) -> list[Press]: out = [] for spec in specs: buttons, _, when = spec.partition("@") start, _, hold = when.partition("+") names = frozenset(buttons.lower().split("-")) if not names <= set(NAMES) or not start.isdigit() or (hold and not hold.isdigit()): raise SystemExit(f"bad press {spec!r}: BUTTONS@FRAME+HOLD, buttons {', '.join(NAMES)}") out.append((names, int(start), int(hold or 1))) return out def presses_lua(presses: list[Press]) -> str: """Lua that sets pad 1 at every input poll; it reads the main script's ``frames``.""" if not presses: return "" rows = ", ".join( "{" + f"{start}, {start + hold}, " + "{" + ", ".join(f"{n} = true" for n in sorted(names)) + "}}" for names, start, hold in presses ) # fmt: skip return ( f"local presses = {{{rows}}}\n" "emu.addEventCallback(function()\n" " local down = {}\n" " for _, p in ipairs(presses) do\n" " if frames >= p[1] and frames < p[2] then\n" " for k, v in pairs(p[3]) do down[k] = v end\n" " end\n" " end\n" " emu.setInput(down, 0, 0)\n" "end, emu.eventType.inputPolled)\n" ) def run( lib: Path, rom: Path, frames: int, home: Path, timeout: float, no_sprites: bool = False, presses: list[Press] | None = None, extra_lua: str = "", pad: bool | None = None, lua: str | None = None, done: str = DONE, ram: int = 1, script_io: bool | None = None, ) -> tuple[str, float]: """Run ``rom`` and log frame ``frames`` as hex; a pad is connected only with presses (or ``pad``). ``extra_lua`` is appended to the script (after the presses). ``lua`` replaces the whole script, which then ends the run by logging ``done``; ``ram`` is the power-on RAM setting (``pce_config_bytes``); ``script_io`` (None: as Mesen2 has it) allows Lua's io and os libraries.""" m = api.load(lib) home.mkdir(parents=True, exist_ok=True) api.start(m, home) m.SetPcEngineConfig.argtypes = [PceConfig] m.SetPcEngineConfig(pce_config(no_sprites, pad=bool(presses) if pad is None else pad, ram=ram)) m.Pause() m.SetEmulationFlag(api.CONSOLE_MODE, True) if script_io is not None: m.SetDebugConfig(api.debug_config(script_io)) if not m.LoadRom(str(rom.resolve()).encode(), b""): raise SystemExit("LoadRom failed") m.InitializeDebugger() if lua is None: lua = LUA.format(frames=frames, done=DONE) + presses_lua(presses or []) + extra_lua script = m.LoadScript(b"frame.lua", str(home.resolve()).encode(), lua.encode(), -1) m.SetEmulationFlag(api.MAXIMUM_SPEED, True) began = time.monotonic() m.Resume() buf = ctypes.create_string_buffer(1 << 24) log = "" while time.monotonic() - began < timeout: time.sleep(0.05) m.GetScriptLog(script, buf, len(buf)) log = buf.value.decode(errors="replace") if done in log: break api.finish(m) return log, time.monotonic() - began def frame_size(count: int, width: int = 0) -> tuple[int, int]: """The frame is as wide as the VCE's dot clock makes it (OBSERVED: 70,664 pixels = 292 x 242 for pcengine-python's CPU test); take the widest width with a plausible height, or ``width`` if given. (0, 0) when nothing fits.""" fits = [w for w in range(200, 1400) if count % w == 0 and 200 <= count // w <= 300] width = width or (fits[-1] if fits else 0) if not width: return 0, 0 return width, count // width def ambiguous_widths(count: int) -> list[int]: return [w for w in range(200, 1400) if count % w == 0 and 200 <= count // w <= 300]