<?phpnamespace App\Scene;use App\Alis\Machine;use App\Alis\SysVars;use JumPHP\Renderer\Renderer;use JumPHP\Scene\AbstractScene;/** * Runs an ALIS game: feeds the keyboard / mouse to the VM, advances it in real time and draws its screen. * Pause key (or F10): back to the game list. */final class PlayScene extends AbstractScene{ private Machine $machine; private string $dir = ''; private int $shownFrame = -1; private float $time = 0.0; private int $cursorVersion = -1; /** output frames of sound owed to real time when nothing can play them (the music must keep its pace) */ private float $audioDue = 0.0; /** quick clicks kept down until the next VM cycle */ private bool $latchL = false; private bool $latchR = false; /** original, source (scripts compiled from data/<game>/src/*.als), hd, special or php (GameLibrary::EDITIONS) */ private string $edition = 'original'; /** source editions: the VM starts once the main script's source is here (downloaded on demand) */ private bool $bootPending = false; /** HD edition: the picture scaled by the GPU with an edge-directed filter (App\Hd\HdRenderer) */ private ?\App\Hd\HdRenderer $hd = null; /** the "CRT 1995" option (App\Hd\CrtRenderer): the picture as a monitor of the time showed it, by the GPU */ private ?\App\Hd\CrtRenderer $crt = null; /** the "FPS" option: the frames per second, small, top left (measured over the last second) */ private bool $fps = false; private float $fpsSince = 0.0; private int $fpsFrames = 0; private string $fpsText = ''; /** the "Skip intro" button (the films and credits of the introduction) */ private \App\Alis\IntroSkip $skip; /** the engine's messages (LOADING..., errors) in a real font at the window's resolution */ private ?\App\Hd\ScreenText $text = null; /** 'editor': the pause key goes back to the ALIS editor (EditorScene), on the script being edited */ private string $back = ''; private string $backScript = ''; private string $gameId = ''; /** @var list<array{0: float, 1: int, 2: int}> tests and shots: left clicks [seconds, x, y] (game pixels), oldest first */ private array $clicks = []; private const AUDIO_RATE = 22050; /** frames mixed per push: 1/30 s */ private const AUDIO_BLOCK = 735; /** the playground's externals (jumphp/externals): where the big files of the games come from (alis/<game>/) */ public function __construct(private \JumPHP\Externals\Externals $externals) { } public function enter(array $params = []): void { // 'dir' = folder of the game data, or 'game' = a folder name in data/ (tests: {"game":"robinson"}) $this->dir = (string) ($params['dir'] ?? (isset($params['game']) ? $this->engine->config->path('data/' . $params['game']) : '')); $this->time = 0.0; $this->back = (string) ($params['back'] ?? ''); $this->backScript = (string) ($params['script'] ?? ''); $this->clicks = array_map(static fn (array $c) => [(float) $c[0], (int) $c[1], (int) $c[2]], $params['clicks'] ?? []); $this->shownFrame = -1; $this->cursorVersion = -1; $this->machine = new Machine(); SysVars::$storage = $this->engine->storage; // the big files of the game (films, maps) are downloaded when the VM opens them (catalog/<game>.json) $id = (string) ($params['game'] ?? basename($this->dir)); $this->gameId = $id; $catalog = \App\Alis\GameLibrary::catalog($this->engine->config->path('catalog'), $id); SysVars::$lazy = $catalog['lazy'] ?? []; // the playground serves them at /<project>/play/private/lazy/<game>/ (same origin as the game's page) SysVars::$lazyBase = '/' . rawurlencode($this->engine->config->id()) . '/play/private/lazy/' . rawurlencode($id) . '/'; $dev = $this->engine->config->path('../../.alis-data/' . $id); // a developer's full copy (desktop) SysVars::$lazyDev = is_dir($dev) ? $dev : ''; SysVars::$http = $this->engine->http(); SysVars::$externals = $this->externals->isAvailable() ? $this->externals : null; SysVars::$externalsDir = 'alis/' . $id; SysVars::$externalsOff = false; // one list of the game's folder: the files opened later need no round trip each (Externals::open()) SysVars::$externals?->list(SysVars::$externalsDir, false); \App\Alis\Prefetch::start($id); // the small files in the background, into the browser's cache SysVars::$fetching = SysVars::$lazyFailed = SysVars::$lazyLoaded = []; $this->audioDue = 0.0; $this->edition = (string) ($params['edition'] ?? 'original'); SysVars::$sourceDir = in_array($this->edition, ['source', 'hd', 'special', 'phphd'], true) && $this->dir !== '' ? $this->dir . '/src' : ''; // the PHP code edition: each script turned into PHP when it is loaded (App\Alis\Compiled\Compiler), no VM loop \App\Alis\Compiled\Compiler::$on = $this->edition === 'php' || $this->edition === 'phphd'; SysVars::$sourceCache = SysVars::$sourcePack = []; SysVars::$sourceGame = SysVars::$sourceDir !== '' ? $id : ''; $this->bootPending = false; $this->hd?->disable(); $this->hd = null; $this->skip = new \App\Alis\IntroSkip(); // debugging a real session (desktop): var/trace.on makes var/trace/<time>/ (App\Alis\Trace) \App\Alis\Trace::start($this->engine->config->path('var')); \App\Alis\Trace::line('enter edition=' . (string) ($params['edition'] ?? 'original') . ' dir=' . basename($this->dir)); $this->text ??= new \App\Hd\ScreenText($this->engine->config->path('assets/fonts/hd.ttf')); $this->text->attach($this->sdl()->getRenderer()); if ($this->edition === 'hd' || $this->edition === 'special' || $this->edition === 'phphd') { $this->hd = new \App\Hd\HdRenderer($this->engine->gl(), $this->sdl(), $this->engine->config->path('assets/fonts/hd.ttf')); $this->hd->enable(); $this->hd->enableText(); $this->hd->enable3d(); // "NO DOWNSCALE": the HD land at every frame even when the computer cannot keep up (no fall back to the // game's own land while the view moves: App\Alis\Hd3d::spent()) \App\Alis\Hd3d::$budget = (bool) ($params['nodownscale'] ?? false) ? 0.0 : 0.75; if ($this->edition === 'special' && ($params['hdSprites'] ?? true)) { $this->hd->enableSprites($this->dir); // the sprite pack (params hdSprites: false = without, to compare) } } $this->fps = (bool) ($params['fps'] ?? false); $this->fpsSince = \JumPHP\Util\Time::now(); $this->fpsFrames = 0; $this->fpsText = ''; $this->crt?->disable(); $this->crt = null; if ((bool) ($params['crt'] ?? false)) { $this->crt = new \App\Hd\CrtRenderer($this->engine->gl()); if (!$this->crt->enable()) { $this->crt = null; } } // the engine's texts (and the FPS) over everything: the HD overlay (its land, its texts) was added after them $this->text->detach(); $this->text->attach($this->sdl()->getRenderer()); if ($this->dir === '') { $this->machine->error = 'No game selected'; } elseif (SysVars::$sourceDir !== '') { $this->bootPending = true; $this->bootWhenReady(); } else { $this->bootMachine(); } } public function exit(): void { \App\Alis\Trace::stop(); \App\Alis\Prefetch::stop(); $this->hd?->disable(); $this->hd = null; $this->crt?->disable(); $this->crt = null; $this->text?->detach(); } private function bootMachine(): void { if ($this->machine->boot($this->dir)) { \App\Alis\audio_output_init(self::AUDIO_RATE, 2); } } /** Source editions: asks for the main script's source (a download in the browser), boots when it is here. */ private function bootWhenReady(): void { $ready = true; foreach (['main.als', 'main.res'] as $file) { if (\App\Alis\sys_find_file(SysVars::$sourceDir . '/' . $file) === null) { $ready = false; if (isset(SysVars::$lazyFailed[$file]) || (!isset(SysVars::$fetching[$file]) && !isset(SysVars::$lazy[$file]))) { $this->bootPending = false; $this->machine->error = "The ALIS source $file is missing"; return; } } } if ($ready) { $this->bootPending = false; $this->bootMachine(); } } public function update(float $dt): void { $this->time += $dt; $kb = $this->engine->input->getKeyboard(); if ($kb->isKeyPressed(\SDLK_PAUSE) || $kb->isKeyPressed(\SDLK_F10)) { if ($this->back === 'editor') { $this->scenes()->switchTo(EditorScene::class, ['game' => $this->gameId] + ($this->backScript !== '' ? ['script' => $this->backScript] : [])); } else { $this->scenes()->switchTo(TitleScene::class); } return; } if ($this->bootPending) { $this->bootWhenReady(); return; } $this->feedInput(); $this->skip->update($dt); \App\Alis\Prefetch::tick($dt); $msec = (int) fmod($this->time * 1000, 2147483647.0); $trace = null; if (\App\Alis\Trace::on()) { $mouse = SysVars::$mouse; $trace = (['dt' => round($dt, 6), 'ms' => $msec, 'held' => array_keys(SysVars::$held), 'btn' => SysVars::$button, 'mx' => $mouse->x, 'my' => $mouse->y, 'lb' => $mouse->lb, 'rb' => $mouse->rb, 'lbc' => $mouse->lb_clicked, 'rbc' => $mouse->rb_clicked, 'pad' => SysVars::$pad, 'frame' => SysVars::$frameCount]); } if ($this->machine->advance($dt, $msec)) { $this->latchL = $this->latchR = false; // the VM saw the click } $mixed = $this->mixAudio($dt); if ($trace !== null) { \App\Alis\Trace::input($trace + ['au' => $mixed]); } } /** * The sound of the VM (C: the SDL audio callback calling the mixer): mixed in PHP, streamed to the speakers * through $engine->pcm() a little ahead; without it (an older engine, no device) the mixer still runs at * the pace of real time so that the music routines tick (scripts wait for the end of a tune). * Returns the audio frames mixed (the trace: a replay mixes as many). */ private function mixAudio(float $dt): int { if (!$this->machine->running) { return 0; } // @phpstan-ignore function.alreadyNarrowedType (the playground may serve an engine older than PcmStream) $pcm = method_exists($this->engine, 'pcm') ? $this->engine->pcm() : null; if ($pcm !== null && $pcm->isAvailable()) { for ($i = 0; $i < 6 && $pcm->buffered() < 0.12; $i++) { $pcm->push(\App\Alis\audio_mix(self::AUDIO_BLOCK), self::AUDIO_RATE, 2); } return $i * self::AUDIO_BLOCK; } $this->audioDue = min($this->audioDue + $dt * self::AUDIO_RATE, self::AUDIO_RATE * 0.25); $frames = (int) $this->audioDue; if ($frames > 0) { \App\Alis\audio_mix($frames); $this->audioDue -= $frames; } return max(0, $frames); } /** The JumPHP input of this frame → the C host variables read by io_inkey(), io_keyon(), sys_get_mouse()... */ private function feedInput(): void { $kb = $this->engine->input->getKeyboard(); foreach ($kb->getTyped() as $sym) { SysVars::$held[$sym] = true; if ($sym !== \SDLK_F11 && $sym !== \SDLK_F12 && !\App\Alis\sys_is_modifier($sym)) { // C: button = event.key.keysym; a modifier (Shift to run, Ctrl...) pressed while walking does not // replace the direction key (inkey() would answer 0 and Robinson would stop) SysVars::$button = $sym; } } foreach (SysVars::$held as $sym => $_) { if (!$kb->isKeyHeld($sym)) { unset(SysVars::$held[$sym]); } } // F11 / F12: save / load the state, like the C SDL backend if ($kb->isKeyReleased(\SDLK_F11)) { \App\Alis\Alis::$state = \App\Alis\C::eAlisStateSave; } elseif ($kb->isKeyReleased(\SDLK_F12)) { \App\Alis\Alis::$state = \App\Alis\C::eAlisStateLoad; } // mouse: view pixels → game pixels (the frame is stretched over the whole view) $m = $this->engine->input->getMouse(); $w = max(1, SysVars::$frameW ?: 320); $h = max(1, SysVars::$frameH ?: 200); $mouse = SysVars::$mouse; $mouse->x = (int) max(0, min($w - 1, $m->x * $w / $this->width())); $mouse->y = (int) max(0, min($h - 1, $m->y * $h / $this->height())); // a quick click (down and up within one frame: touch pads, phones) stays down until the VM has run a // cycle: the scripts read the button state, and the VM only runs every 2 or 3 frames $onSkip = $this->skip->offered() && !$this->skip->skipping && $this->onSkipButton($m->x, $m->y); if ($m->isPressed(1) && $onSkip) { $this->skip->skipping = true; // the click is the button's, not the game's } elseif ($m->isPressed(1)) { $mouse->lb_clicked = 1; $this->latchL = true; } if ($m->isPressed(3)) { $mouse->rb_clicked = 1; $this->latchR = true; } $mouse->lb = ($m->isHeld(1) && !$onSkip) || $this->latchL ? 1 : 0; // scripted clicks (tests, shots): the button down for 0.1 s at that point if ($this->clicks !== [] && $this->time >= $this->clicks[0][0]) { [$at, $mouse->x, $mouse->y] = $this->clicks[0]; $mouse->lb = 1; $mouse->lb_clicked = 1; if ($this->time >= $at + 0.1) { array_shift($this->clicks); } } $mouse->rb = $m->isHeld(3) || $this->latchR ? 1 : 0; // gamepad: Atari joystick bits $actions = $this->actions(); $pad = 0; $pad |= $actions->isHeld('up') ? 0x01 : 0; $pad |= $actions->isHeld('down') ? 0x02 : 0; $pad |= $actions->isHeld('left') ? 0x04 : 0; $pad |= $actions->isHeld('right') ? 0x08 : 0; // Shift held while moving = run: the joystick's fire button with a direction (yoda.als: mw[0x1a10] > 127 // sets the button, and a direction with it makes Robinson run while his stamina lasts) if ($pad !== 0 && ($kb->isKeyHeld(\SDLK_LSHIFT) || $kb->isKeyHeld(\SDLK_RSHIFT))) { $pad |= 0x80; } $pad |= $actions->isHeld('fire') ? 0x80 : 0; SysVars::$pad = $pad; } public function render(Renderer $r): void { $r->clear([0, 0, 0]); if (SysVars::$frameBmp !== '' && SysVars::$frameCount !== $this->shownFrame) { $this->shownFrame = SysVars::$frameCount; $this->uploadFrame(); } $this->hd?->source(SysVars::$frameW, SysVars::$frameH); $this->crt?->source(SysVars::$frameW, SysVars::$frameH); if ($this->sdl()->hasTexture('alis-frame')) { $r->copy($this->sdl()->getTexture('alis-frame')['texture'], null, 0, 0, $this->width(), $this->height()); } if ($this->fps) { $this->fpsFrames++; $now = \JumPHP\Util\Time::now(); if ($now - $this->fpsSince >= 1.0) { $this->fpsText = (string) (int) round($this->fpsFrames / ($now - $this->fpsSince)) . ' FPS'; $this->fpsSince = $now; $this->fpsFrames = 0; } if ($this->fpsText !== '' && $this->text !== null) { // a real font at the window's resolution (over the HD / CRT filters), white outlined in black: // readable over any picture foreach ([[-0.5, 0], [0.5, 0], [0, -0.5], [0, 0.5], [0.5, 0.5]] as [$ox, $oy]) { $this->text->show($this->fpsText, 3 + $ox, 2 + $oy, 7, [0, 0, 0]); } $this->text->show($this->fpsText, 3, 2, 7, [255, 255, 255]); } } if ($this->skip->offered() && !$this->skip->skipping) { [$bx, $by, $bw, $bh] = self::SKIP_BUTTON; $hover = $this->onSkipButton($this->engine->input->getMouse()->x, $this->engine->input->getMouse()->y); $r->fillRect($bx, $by, $bw, $bh, $hover ? [90, 70, 30, 230] : [20, 16, 10, 190]); $r->drawRect($bx, $by, $bw, $bh, [216, 178, 90]); $this->say('Skip intro »', $bx + $bw / 2, $by + 3, 9, $hover ? [255, 240, 200] : [216, 178, 90], 'center'); } $this->drawCursor($r); if (SysVars::$fetching !== []) { $this->say('Loading ' . array_key_first(SysVars::$fetching) . '…', $this->width() / 2, $this->height() - 14, 9, [255, 230, 150], 'center'); } if ($this->machine->error !== null) { $this->say(wordwrap($this->machine->error, 60, "\n", true), 6, 6, 9, [255, 140, 120]); $this->say('F10: ' . ($this->back === 'editor' ? 'editor' : 'menu'), 6, $this->height() - 14, 9, [255, 230, 150]); } } /** where the "Skip intro" button is (view pixels): bottom right */ private const SKIP_BUTTON = [236, 214, 78, 18]; private function onSkipButton(float $x, float $y): bool { [$bx, $by, $bw, $bh] = self::SKIP_BUTTON; return $x >= $bx && $x < $bx + $bw && $y >= $by && $y < $by + $bh; } /** A message of the engine: sharp (ScreenText) when the font is there, else the built-in pixel font. */ private function say(string $text, float $x, float $y, float $size, array $colour, string $align = 'left'): void { if ($this->text !== null && is_file($this->engine->config->path('assets/fonts/hd.ttf'))) { $this->text->show($text, $x, $y, $size, $colour, $align); return; } $this->font()->draw($this->sdl()->getRenderer(), strtoupper($text), $x, $y, 1, $colour, $align, [0, 0, 0]); } private function uploadFrame(): void { $bmp = SysVars::$frameBmp; $rw = \SDL_RWFromConstMem($bmp, strlen($bmp)); $surface = \SDL_LoadBMP_RW($rw, 1); if ($surface) { $this->sdl()->createTextureFromSurface('alis-frame', $surface); \SDL_FreeSurface($surface); } } /** The game's mouse cursor (C: an SDL cursor made from alis.desmouse), drawn in software. */ private function drawCursor(Renderer $r): void { $cursor = SysVars::$cursor; if ($cursor === null || !SysVars::$mouse->enabled) { return; } if (SysVars::$cursorVersion !== $this->cursorVersion) { $this->cursorVersion = SysVars::$cursorVersion; $palette = []; foreach ($cursor['palette'] as $i => $c) { $palette[chr(33 + $i)] = sprintf('#%06x', $c); } $rows = []; foreach ($cursor['rows'] as $row) { $line = ''; foreach ($row as $px) { $line .= $px < 0 ? '.' : chr(33 + $px); } $rows[] = $line; } $this->sdl()->createTextureFromPixels('alis-cursor', $rows, $palette); } $w = max(1, SysVars::$frameW); $h = max(1, SysVars::$frameH); $sx = $this->width() / $w; $sy = $this->height() / $h; $tex = $this->sdl()->getTexture('alis-cursor'); $r->copy($tex['texture'], null, (SysVars::$mouse->x - $cursor['hotx']) * $sx, (SysVars::$mouse->y - $cursor['hoty']) * $sy, $tex['width'] * $sx, $tex['height'] * $sy); }}