# SPDX-License-Identifier: GPL-3.0-or-later """Controller input scripts (emu-tools contract, section 4) as Mesen2 Lua. A script is JSON Lines, ``{"frame": 120, "port": 1, "buttons": ["start"]}``: from the moment ``frame`` frames have completed, the port's buttons are exactly those listed (an empty list releases them), until the port's next record. Ports count from 1. Button names are the console's own, as Mesen2's Lua API spells them. """ from __future__ import annotations import json from pathlib import Path BUTTONS = { "nes": ("a", "b", "select", "start", "up", "down", "left", "right"), "snes": ("a", "b", "x", "y", "l", "r", "select", "start", "up", "down", "left", "right"), "pce": ("i", "ii", "select", "run", "up", "down", "left", "right"), } class InputError(ValueError): pass def read(path: Path, console: str) -> list[tuple[int, int, tuple[str, ...]]]: """(frame, port, buttons) records, checked against the console's button names.""" allowed = set(BUTTONS[console]) records = [] for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1): if not line.strip(): continue try: row = json.loads(line) frame, port, buttons = int(row["frame"]), int(row.get("port", 1)), row["buttons"] except (ValueError, KeyError, TypeError) as error: raise InputError(f"{path}:{number}: {error}") from None if frame < 0 or not 1 <= port <= 2 or not set(buttons) <= allowed: raise InputError( f"{path}:{number}: frame >= 0, port 1 or 2, buttons among {sorted(allowed)}" ) records.append((frame, port, tuple(sorted(set(buttons))))) return sorted(records) def lua(records: list[tuple[int, int, tuple[str, ...]]]) -> str: """Lua that counts completed frames itself and sets each port at every input poll.""" if not records: return "" rows = ", ".join( "{" + f"{frame}, {port - 1}, " + "{" + ", ".join(f"{b} = true" for b in buttons) + "}}" for frame, port, buttons in records ) return ( f"local input_rows = {{{rows}}}\n" "local input_frames = 0\n" "emu.addEventCallback(function() input_frames = input_frames + 1 end," " emu.eventType.endFrame)\n" "emu.addEventCallback(function()\n" " local state = {}\n" " for _, r in ipairs(input_rows) do\n" " if input_frames >= r[1] then state[r[2]] = r[3] end\n" " end\n" " for port, buttons in pairs(state) do emu.setInput(buttons, port, 0) end\n" "end, emu.eventType.inputPolled)\n" )