"""A desktop window: play a cartridge with picture, sound, keyboard and gamepad. python -m gba_python play "Advance Wars (USA).zip" python -m gba_python play game.gba --skip-bios --scale 4 --save-dir ~/gba-saves The only module that needs a library beyond the cores: pygame-ce (the ``frontend`` extra), for SDL's window, audio and game controllers. Run it on PyPy. This is the reference board, correct before fast (docs/validation.md rung 7): it runs well below real time, so the window shows every frame it makes and the sound plays at the console's pitch with gaps, rather than stretched. Where a machine is fast enough, sound sets the pace (SDL's audio thread drains a short queue and a frame runs when it runs short), as in the family's other frontends. The console boots the retail BIOS when one is found (``bios.find``), else the free one; ``--skip-bios`` starts at the cartridge as the smoke set does. Saves: the cartridge's SRAM, Flash or EEPROM is read from ``NAME.sav`` at power-on and written there on quit and power cycle (the raw chip contents, as mGBA and NanoBoyAdvance write them), beside the image unless ``--save-dir`` names a folder. F2 writes the whole console to ``NAME.state`` in the same folder and F4 reads it back (``state.py``: same revisions only). The cartridge clock, where there is one, starts at the PC's time and counts console time. """ from __future__ import annotations import argparse import sys import threading import time from array import array from collections.abc import Callable from pathlib import Path from gba_python import bios as bios_module from gba_python import keypad, state from gba_python.apu import SAMPLE_RATE from gba_python.board import GBA from gba_python.testrom import read_rom, screen_png WIDTH, HEIGHT = 240, 160 #: Frames of sound kept queued ahead of the speaker when the board keeps up. BUFFER_FRAMES = 3 #: Frames a second: 16,777,216 Hz over 280,896 cycles a frame, 59.73. RATE = 16_777_216 / 280_896 HELP = """\ Arrows D-pad Z B X A A L S R Right Shift Select Enter Start F5 power cycle F3 pause F11 fullscreen F2 save state F4 load state Tab (hold) fast forward (no sound) F12 screenshot (PNG) Esc quit A gamepad plays too: buttons by position (the pad's right face button is A, its lower one B), the shoulders L and R.""" KEYS = ( # (keypad bit, pygame key names) (keypad.UP, ("K_UP",)), (keypad.DOWN, ("K_DOWN",)), (keypad.LEFT, ("K_LEFT",)), (keypad.RIGHT, ("K_RIGHT",)), (keypad.B, ("K_z",)), (keypad.A, ("K_x",)), (keypad.L, ("K_a",)), (keypad.R, ("K_s",)), (keypad.SELECT, ("K_RSHIFT",)), (keypad.START, ("K_RETURN", "K_KP_ENTER")), ) PAD_BUTTONS = ( # (keypad bit, SDL game controller button name) (keypad.UP, "CONTROLLER_BUTTON_DPAD_UP"), (keypad.DOWN, "CONTROLLER_BUTTON_DPAD_DOWN"), (keypad.LEFT, "CONTROLLER_BUTTON_DPAD_LEFT"), (keypad.RIGHT, "CONTROLLER_BUTTON_DPAD_RIGHT"), (keypad.B, "CONTROLLER_BUTTON_A"), (keypad.A, "CONTROLLER_BUTTON_B"), (keypad.L, "CONTROLLER_BUTTON_LEFTSHOULDER"), (keypad.R, "CONTROLLER_BUTTON_RIGHTSHOULDER"), (keypad.SELECT, "CONTROLLER_BUTTON_BACK"), (keypad.START, "CONTROLLER_BUTTON_START"), ) # -- conversions (pure, tested without pygame) -------------------------------------- def _widen(c: int) -> int: return c << 3 | c >> 2 # as testrom.screen_rgb widens five bits #: A colour (BGR555, red in the low five bits) as an opaque BGRA word (0xFFRRGGBB). WORDS = [ 0xFF000000 | _widen(c & 31) << 16 | _widen(c >> 5 & 31) << 8 | _widen(c >> 10 & 31) for c in range(0x8000) ] def frame_image(screen: array) -> bytes: """The PPU's last picture (``ppu.screen``) as 240x160 BGRA bytes.""" pixels = array("I", [WORDS[color & 0x7FFF] for color in screen]) if sys.byteorder == "big": pixels.byteswap() return pixels.tobytes() def save_path(rom: Path, folder: Path | None = None, suffix: str = ".sav") -> Path: """``NAME.sav`` beside the image, or in ``folder``.""" return (folder or rom.parent) / (rom.stem + suffix) class SoundBuffer: """Bytes queued for SDL's audio thread, which calls :meth:`fill`.""" def __init__(self) -> None: self._data = bytearray() self._lock = threading.Lock() def __len__(self) -> int: return len(self._data) def push(self, data: bytes) -> None: with self._lock: self._data += data def clear(self) -> None: with self._lock: self._data.clear() def fill(self, _device: object, stream: memoryview) -> None: """SDL's audio callback: copy what is queued, then silence.""" size = len(stream) with self._lock: chunk = bytes(self._data[:size]) del self._data[:size] stream[: len(chunk)] = chunk if len(chunk) < size: stream[len(chunk) :] = bytes(size - len(chunk)) # -- the console -------------------------------------------------------------------- class Console: """The board and its cartridge; no pygame.""" def __init__( self, rom: Path, bios: str | Path | None = None, skip_bios: bool = False, save_dir: Path | None = None, ) -> None: self.rom, self.save_dir = rom, save_dir save = save_path(rom, save_dir) self.gba = GBA( bios_module.find(bios), read_rom(rom), save.read_bytes() if save.exists() else None, skip_bios=skip_bios, ) self.gba.apu.start_capture() def run_frame(self) -> bytes: """One frame; returns its sound as signed 16-bit stereo at ``SAMPLE_RATE``.""" self.gba.run_frame() samples = self.gba.apu.take_samples() if sys.byteorder == "big": samples.byteswap() return samples.tobytes() def press(self, keys: int) -> None: """Hold exactly ``keys`` (keypad.py's bits).""" if keys != ~self.gba.keypad.input & keypad.ALL: self.gba.keypad.set_pressed(keys) def save(self) -> Path | None: """Write the save chip to ``NAME.sav``; None for a cartridge without one.""" data = self.gba.cartridge.save_data() if data is None: return None path = save_path(self.rom, self.save_dir) path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(data) return path def save_state(self) -> Path: path = save_path(self.rom, self.save_dir, ".state") path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(state.save(self.gba)) return path def load_state(self) -> bool: """Read ``NAME.state`` back; False when there is none, or it is another revision's.""" path = save_path(self.rom, self.save_dir, ".state") if not path.exists(): return False try: self.gba = state.load(path.read_bytes()) except ValueError: return False self.gba.apu.start_capture() self.gba.apu.take_samples() return True def screenshot(self, path: Path) -> None: path.write_bytes(screen_png(self.gba)) # -- the window --------------------------------------------------------------------- class Frontend: """One console in one window. ``pygame`` is imported by :func:`main`.""" def __init__( self, pygame, rom: Path, bios: str | None, skip_bios: bool, save_dir: Path | None, scale: int, audio: bool, fullscreen: bool, ) -> None: # fmt: skip self.pg = pygame self.rom, self.bios, self.skip_bios, self.save_dir = rom, bios, skip_bios, save_dir self.console = self._power_on() self.scale, self.fullscreen = scale, fullscreen self.window = self._open_window() self.sound = SoundBuffer() self.device = self._open_audio() if audio else None self.paused = False self.fast = False self.controllers: dict[int, object] = {} self._frames = 0 self._fps_since = time.perf_counter() self._title() def _power_on(self) -> Console: console = Console(self.rom, self.bios, self.skip_bios, self.save_dir) gba = console.gba cartridge = gba.cartridge print( f"BIOS: {gba.bios.label}; {cartridge.title!r}, save {cartridge.save_type or 'none'}" f"{', clock' if cartridge.gpio is not None else ''}", file=sys.stderr, ) return console def _open_window(self): """A window whose surface is the LCD; SDL scales it on the GPU (SCALED) and presents it at the display's refresh where it can (vsync).""" pg = self.pg flags = pg.SCALED | pg.RESIZABLE | (pg.FULLSCREEN if self.fullscreen else 0) try: surface = pg.display.set_mode((WIDTH, HEIGHT), flags, vsync=1) except pg.error: surface = pg.display.set_mode((WIDTH, HEIGHT), flags) if not self.fullscreen: pg.Window.from_display_module().size = (WIDTH * self.scale, HEIGHT * self.scale) return surface def _open_audio(self): from pygame._sdl2.audio import AUDIO_S16, AudioDevice from pygame._sdl2.sdl2 import INIT_AUDIO, init_subsystem try: init_subsystem(INIT_AUDIO) device = AudioDevice( devicename=None, iscapture=False, frequency=SAMPLE_RATE, audioformat=AUDIO_S16, numchannels=2, chunksize=512, allowed_changes=0, callback=self.sound.fill, ) # fmt: skip except Exception as error: # pygame._sdl2's own error type: no sound print(f"no sound: {error}", file=sys.stderr) return None device.pause(0) return device def run_frame(self) -> None: self._apply_inputs() sound = self.console.run_frame() if self.device is not None and not self.fast: self.sound.push(sound) self._frames += 1 def _apply_inputs(self) -> None: pg = self.pg keys = pg.key.get_pressed() pressed = 0 for bit, names in KEYS: if any(keys[getattr(pg, name)] for name in names): pressed |= bit for controller in self.controllers.values(): for bit, name in PAD_BUTTONS: if controller.get_button(getattr(pg, name)): pressed |= bit x = controller.get_axis(pg.CONTROLLER_AXIS_LEFTX) / 32768 y = controller.get_axis(pg.CONTROLLER_AXIS_LEFTY) / 32768 for bit, held in ((keypad.LEFT, x < -0.5), (keypad.RIGHT, x > 0.5), (keypad.UP, y < -0.5), (keypad.DOWN, y > 0.5)): # fmt: skip if held: pressed |= bit # The pad cannot hold both ends of an axis; a keyboard can. if pressed & keypad.LEFT and pressed & keypad.RIGHT: pressed &= ~(keypad.LEFT | keypad.RIGHT) if pressed & keypad.UP and pressed & keypad.DOWN: pressed &= ~(keypad.UP | keypad.DOWN) self.console.press(pressed) def _handle(self, event) -> bool: """Handle one event; False to quit.""" pg = self.pg if event.type == pg.QUIT: return False if event.type == pg.CONTROLLERDEVICEADDED: controller = pg._sdl2.controller.Controller(event.device_index) self.controllers[controller.id] = controller elif event.type == pg.CONTROLLERDEVICEREMOVED: self.controllers.pop(event.instance_id, None) elif event.type == pg.KEYDOWN: if event.key == pg.K_ESCAPE: return False if event.key == pg.K_F3: self.paused = not self.paused self.sound.clear() elif event.key == pg.K_F5: self.console.save() self.console = self._power_on() self.sound.clear() elif event.key == pg.K_F2: print(f"saved {self.console.save_state()}") elif event.key == pg.K_F4: print("state loaded" if self.console.load_state() else "no state to load") self.sound.clear() elif event.key == pg.K_F11: pg.display.toggle_fullscreen() elif event.key == pg.K_F12: self._screenshot() elif event.key == pg.K_TAB: self.fast = True self.sound.clear() elif event.type == pg.KEYUP and event.key == pg.K_TAB: self.fast = False return True def _screenshot(self) -> None: folder = Path("screenshots") folder.mkdir(exist_ok=True) path = folder / f"{self.rom.stem}-{time.strftime('%Y%m%d-%H%M%S')}.png" self.console.screenshot(path) print(f"saved {path}") def draw(self) -> None: pg = self.pg image = frame_image(self.console.gba.ppu.screen) self.window.blit(pg.image.frombuffer(image, (WIDTH, HEIGHT), "BGRA"), (0, 0)) pg.display.flip() now = time.perf_counter() if now - self._fps_since >= 1.0: self._title(self._frames / (now - self._fps_since)) self._frames, self._fps_since = 0, now def _title(self, fps: float | None = None) -> None: mode = " (paused)" if self.paused else " (fast)" if self.fast else "" rate = f" — {fps:.1f} fps{mode}" if fps is not None else "" self.pg.display.set_caption(f"{self.rom.stem}{rate} — gba-python") def run(self, max_frames: int | None = None, on_frame: Callable | None = None) -> None: pg = self.pg clock = pg.time.Clock() shown = 0 frame_bytes = int(SAMPLE_RATE / RATE) * 4 while True: for event in pg.event.get(): if not self._handle(event): return ran = False target = BUFFER_FRAMES * frame_bytes if not self.paused and (self.device is None or len(self.sound) < target): for _ in range(4 if self.fast else 1): self.run_frame() ran = True if ran: self.draw() shown += 1 if on_frame is not None: on_frame(self) if max_frames is not None and shown >= max_frames: return if self.device is None and not self.fast: clock.tick_busy_loop(RATE) elif not ran: time.sleep(0.002) def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser( prog="python -m gba_python play", description="Play a Game Boy Advance cartridge in a window.", epilog=HELP, formatter_class=argparse.RawDescriptionHelpFormatter, ) parser.add_argument("rom", type=Path, help=".gba, or a .zip holding one") parser.add_argument("--bios", help="a BIOS file or No-Intro .zip (default: retail, found)") parser.add_argument("--skip-bios", action="store_true", help="start at the cartridge") parser.add_argument("--save-dir", type=Path, help="where NAME.sav and NAME.state live") parser.add_argument("--scale", type=int, default=3, help="window scale (default 3)") parser.add_argument("--no-audio", action="store_true") parser.add_argument("--fullscreen", action="store_true") args = parser.parse_args(argv) try: import pygame import pygame._sdl2.controller except ImportError: parser.error("the window needs pygame-ce: pip install 'gba-python[frontend]'") if sys.implementation.name != "pypy": print("note: CPython runs this board several times slower than PyPy.", file=sys.stderr) # Not pygame.init(): its mixer would take the audio device the frontend opens. pygame.display.init() pygame._sdl2.controller.init() print(HELP) frontend = Frontend( pygame, args.rom, args.bios, args.skip_bios, args.save_dir, max(1, args.scale), not args.no_audio, args.fullscreen, ) # fmt: skip try: frontend.run() finally: frontend.console.save() pygame.quit() return 0