UK
games/dmmotor / src / Scene / TitleScene.php · commit 9d248a4
<?php/* * dmmotor — the choice of the game (Freedoom Phase 1 or Phase 2), the title picture and the menus: new game, * episode, skill, help (after d_main.c / m_menu.c of linuxdoom-1.10). * Copyright (C) 1993-1996 by id Software, Inc.; PHP port for dmmotor. GPL v2 (see LICENSE). */namespace App\Scene;use App\Dm\MenuScreen;use App\Service\DmGame;use App\Service\WadCatalog;use JumPHP\Externals\Externals;use App\Service\SaveGames;use JumPHP\Kernel\Platform;use JumPHP\Renderer\Renderer;use JumPHP\Scene\AbstractScene;final class TitleScene extends AbstractScene{    /** choose, title, menu, help */    private string $mode = 'choose';    private ?MenuScreen $menu = null;    private int $tic = 0;    private float $time = 0;    private int $episode = 1;    /** the game highlighted on the choice screen */    private int $choice = 0;    /** the download of a WAD of the server: 0..1, -1 = none running */    private float $downloading = -1;    private string $downloadError = '';    public function __construct(private DmGame $game, private Externals $externals)    {    }    /** The WADs of the server's shared folder (jumphp/externals), added to the list when they arrive. */    private function listRemote(): void    {        if (!$this->externals->isAvailable()) {            return;        }        // the administrator may share dmmotor/wads itself, a folder above it, or only sub-folders of it        // (dmmotor/wads/idsoftwads): ask what is shared, then list each shared folder that holds WADs of ours        $folder = WadCatalog::REMOTE_FOLDER;        $this->externals->list()->then(function (array $roots) use ($folder): void {            $listed = [];            foreach ($roots as $root) {                $path = trim($root->path, '/');                $dir = match (true) {                    $path === $folder, str_starts_with($path, "$folder/") => $path,   // the folder, or one under it                    $path === '', str_starts_with($folder, "$path/") => $folder,      // a folder above it                    default => null,                                                    // another game's                };                if ($dir !== null && !isset($listed[$dir])) {                    $listed[$dir] = true;                    $this->externals->list($dir, true)->then(fn (array $entries) => $this->addRemote($entries), fn () => null);                }            }        }, fn () => null);   // not shared with this game, no network: only the local WADs    }    /** @param list<\JumPHP\Externals\Entry> $entries */    private function addRemote(array $entries): void    {        $current = $this->ids[$this->choice] ?? null;        $this->game->catalog->addRemote($entries);        $this->ids = $this->game->catalog->ids();        $this->choice = max(0, (int) array_search($current, $this->ids, true));    }    /** @var list<string> the WADs to choose from */    private array $ids = [];    /** the first one shown in the list (it scrolls) */    private int $top = 0;    public function enter(array $params = []): void    {        // the wads/ folder is read again each time: a WAD put there shows up        $this->game->scan(fn (string $p) => $this->engine->config->path($p));        $this->ids = $this->game->catalog->ids();        $this->downloading = -1;        $this->downloadError = '';        $this->listRemote();        $saved = (string) $this->engine->options->get('iwad', 'freedoom1');        $this->choice = max(0, (int) array_search($saved, $this->ids, true));        $this->tic = 0;        $this->time = 0;        $this->menu = null;        $this->mode = 'choose';        if (($params['menu'] ?? false) && $this->game->loaded) {            $this->mode = 'menu';            $this->menu = $this->mainMenu();        }    }    private function loadChoice(): void    {        $id = $this->ids[$this->choice];        $this->engine->options->set('iwad', $id);        $this->game->load(fn (string $p) => $this->engine->config->path($p), $this->sound(), $id);    }    private function mainMenu(): MenuScreen    {        $items = [['M_NGAME', 'new'], ['M_LOADG', 'load'], ['M_RDTHIS', 'help']];        if (Platform::isDesktop()) {            $items[] = ['M_QUITG', 'quit'];        }        return new MenuScreen('main', $items, 97, 64, [['M_DOOM', 94, 2]]);    }    private function episodeMenu(): MenuScreen    {        $items = [];        for ($e = 1; $e <= 4; $e++) {            if ($this->game->wad->has("E{$e}M1")) {                $items[] = ["M_EPI$e", "ep$e"];            }        }        return new MenuScreen('episode', $items, 48, 63, [['M_EPISOD', 54, 38]]);    }    private function skillMenu(): MenuScreen    {        return new MenuScreen('skill', [            ['M_JKILL', 'sk0'], ['M_ROUGH', 'sk1'], ['M_HURT', 'sk2'], ['M_ULTRA', 'sk3'], ['M_NMARE', 'sk4'],        ], 48, 63, [['M_NEWG', 96, 14], ['M_SKILL', 54, 38]], 2);    }    public function update(float $dt): void    {        $this->time += $dt;        $this->tic = (int) ($this->time * 35);        if ($this->game->loaded) {            if ($this->mode !== 'choose') {                $this->game->changeMusic($this->engine->pcm(), 'title');            }            $this->game->pumpMusic($this->engine->pcm());        }        $a = $this->actions();        $go = $a->isPressed('confirm') || $a->isPressed('fire') || $a->isPressed('use');        if ($this->mode === 'choose') {            if ($this->downloading >= 0) {                return;   // a WAD of the server is coming            }            $catalog = $this->game->catalog;            $selected = $this->ids[$this->choice] ?? '';            if ($catalog->isRemote($selected)) {                $catalog->inspect($selected, $this->externals);   // its header, directory and title picture only            }            $n = max(1, count($this->ids));            if ($a->isPressed('left') || $a->isPressed('up') || $a->isPressed('strafe_left')) {                $this->choice = ($this->choice + $n - 1) % $n;            } elseif ($a->isPressed('right') || $a->isPressed('down') || $a->isPressed('strafe_right')) {                $this->choice = ($this->choice + 1) % $n;            } elseif ($go && $this->ids !== [] && $catalog->isRemote($selected) && !$catalog->isDownloaded($selected)                && $this->playable($selected)) {                // the whole WAD, block by block (cached: a second time is instant)                $this->downloading = 0;                $catalog->download($selected, $this->externals, fn (float $p) => $this->downloading = $p)->then(                    function (): void {                        $this->downloading = -1;                        $this->loadChoice();                        $this->mode = 'title';                        $this->game->changeMusic($this->engine->pcm(), 'title');                    },                    function (\Throwable $e): void {                        $this->downloading = -1;                        $this->downloadError = strtoupper($e->getMessage());                    },                );            } elseif ($go && $this->ids !== [] && $this->playable($this->ids[$this->choice])) {                $this->loadChoice();                $this->game->sounds?->menu('pistol');                $this->mode = 'title';                $this->game->changeMusic($this->engine->pcm(), 'title');            } elseif ($a->isPressed('back') && Platform::isDesktop()) {                $this->engine->quit();            }            return;        }        if ($this->mode === 'title') {            if ($a->isPressed('back')) {                $this->mode = 'choose';            } elseif ($go) {                $this->mode = 'menu';                $this->menu = $this->mainMenu();                $this->game->sounds?->menu('swtchn');            }            return;        }        if ($this->mode === 'help') {            if ($go || $a->isPressed('back')) {                $this->mode = 'menu';                $this->game->sounds?->menu('swtchx');            }            return;        }        $menu = $this->menu;        if ($a->isPressed('up')) {            $menu->move(-1);            $this->game->sounds?->menu('pstop');        } elseif ($a->isPressed('down')) {            $menu->move(1);            $this->game->sounds?->menu('pstop');        } elseif ($a->isPressed('back')) {            $this->game->sounds?->menu('swtchx');            $this->menu = match ($menu->id) {                'skill' => $this->game->commercial ? $this->mainMenu() : $this->episodeMenu(),                'episode', 'load' => $this->mainMenu(),                default => null,            };            if ($this->menu === null) {                $this->mode = 'title';            }        } elseif ($go) {            $this->game->sounds?->menu('pistol');            $this->choose($menu->selectedId());        }    }    private function choose(string $id): void    {        if ($id === 'new') {            if ($this->game->commercial || $this->game->catalog->isMod($this->game->iwad)) {                $this->episode = 0;   // the WAD's first map                $this->menu = $this->skillMenu();            } else {                $this->menu = $this->episodeMenu();            }        } elseif ($id === 'load') {            $this->menu = SaveGames::menu($this->engine->storage, $this->game->iwad, 'load');        } elseif (str_starts_with($id, 'slot')) {            $data = SaveGames::read($this->engine->storage, $this->game->iwad, (int) substr($id, 4));            if ($data !== null) {                $this->scenes()->switchTo(PlayScene::class, ['load' => $data]);            }        } elseif ($id === 'help') {            $this->mode = 'help';        } elseif ($id === 'quit') {            $this->engine->quit();        } elseif (str_starts_with($id, 'ep')) {            $this->episode = (int) substr($id, 2);            $this->menu = $this->skillMenu();        } elseif (str_starts_with($id, 'sk')) {            $this->game->skill = (int) substr($id, 2);            [$episode, $map] = $this->episode === 0 ? $this->game->firstMap : [$this->episode, 1];            $this->scenes()->switchTo(PlayScene::class, [                'episode' => $episode, 'map' => $map, 'skill' => $this->game->skill, 'newGame' => true,            ]);        }    }    public function render(Renderer $r): void    {        if ($this->mode === 'choose') {            $this->renderChoice($r);            return;        }        $g = $this->game;        $g->fb->clear(0);        if ($this->mode === 'help') {            MenuScreen::fullPicture($g->gfx, $g->fb, $g->wad->has('HELP1') ? 'HELP1' : 'HELP');        } else {            MenuScreen::fullPicture($g->gfx, $g->fb, 'TITLEPIC');            $this->menu?->draw($g->gfx, $g->fb, $this->tic);        }        $g->present($r, $this->sdl());    }    /** A WAD the engine can start: it has maps, and a mod has a base game. */    private function playable(string $id): bool    {        $catalog = $this->game->catalog;        if ($catalog->isRemote($id) && $catalog->remoteState($id) !== 'ready' && !$catalog->isDownloaded($id)) {            return false;   // not looked into yet        }        return $catalog->isFree($id) && $catalog->analysis($id)['maps'] !== []            && (!$catalog->isMod($id) || $catalog->baseFor($id) !== null);    }    /** The texture of a WAD's title picture (made once from its TITLEPIC), null when it has none. */    private function titleTexture(string $id): mixed    {        $name = "launch-$id";        if (!$this->sdl()->hasTexture($name)) {            $catalog = $this->game->catalog;            $base = $catalog->isMod($id) ? $catalog->baseFor($id) : null;            $palette = $base !== null ? $catalog->file($base)?->lump('PLAYPAL') : null;            $bmp = $catalog->file($id)?->titleBmp($palette);            if ($bmp === null && $base !== null) {                $bmp = $catalog->file($base)?->titleBmp();            }            if ($bmp === null) {                return null;            }            $rw = \SDL_RWFromConstMem($bmp, strlen($bmp));            $surface = \SDL_LoadBMP_RW($rw, 1);            if (!$surface) {                return null;            }            $this->sdl()->createTextureFromSurface($name, $surface);            \SDL_FreeSurface($surface);        }        return $this->sdl()->getTexture($name)['texture'];    }    /** The WADs found (assets/wads and wads/): a list, the title picture and the analysis of the one selected. */    private function renderChoice(Renderer $r): void    {        $r->clear([18, 8, 6]);        $font = $this->font();        $font->draw($r, 'DMMOTOR', 160, 6, 2, [216, 42, 30], 'center', [0, 0, 0]);        $font->draw($r, 'CHOOSE YOUR GAME', 160, 24, 1, [242, 178, 51], 'center');        $catalog = $this->game->catalog;        if ($this->ids === []) {            $font->draw($r, "NO WAD FOUND\nPUT SOME IN THE WADS FOLDER", 160, 100, 1, [255, 255, 255], 'center');            return;        }        // the list, 12 lines, scrolling with the choice: the WADs by source, each with its title (the game's own WADs have none when they come first)        $rows = [];        $last = 0;        foreach ($this->ids as $i => $id) {            $source = $catalog->source($id);            if ($source !== $last) {                $rows[] = ['- FREEDOOM -', '- WADS FOLDER -', '- SERVER -'][$source];                $last = $source;            }            $rows[] = $i;        }        $lines = 12;        $at = (int) array_search($this->choice, $rows, true);        $first = $at > 0 && is_string($rows[$at - 1]) ? $at - 1 : $at;   // a group's title stays above its first WAD        if ($first < $this->top) {            $this->top = $first;        } elseif ($at >= $this->top + $lines) {            $this->top = $at - $lines + 1;        }        for ($k = $this->top; $k < min(count($rows), $this->top + $lines); $k++) {            $y = 42 + ($k - $this->top) * 13;            if (is_string($rows[$k])) {                $font->draw($r, $rows[$k], 70, $y, 1, [150, 130, 110], 'center');                continue;            }            $i = $rows[$k];            $id = $this->ids[$i];            $selected = $i === $this->choice;            $playable = $this->playable($id);            if ($selected) {                // the bar is red for a game that can be played, grey for one that is only shown                $r->fillRect(6, $y - 3, 128, 12, $playable ? [216, 42, 30] : [70, 66, 64]);            }            $color = !$playable ? [110, 90, 80] : ($selected ? [255, 255, 255] : [210, 190, 170]);            $label = $catalog->name($id);            $font->draw($r, strlen($label) > 18 ? substr($label, 0, 17) . '.' : $label, 10, $y, 1, $color);            if ($catalog->isMod($id)) {                $font->draw($r, 'MOD', 130, $y, 1, [242, 178, 51], 'right');            } elseif ($catalog->isRemote($id)) {                $font->draw($r, 'NET', 130, $y, 1, [120, 190, 255], 'right');            }        }        // the selected one: picture and analysis        $id = $this->ids[$this->choice];        $tex = $this->titleTexture($id);        if ($tex !== null) {            $r->copy($tex, null, 144, 40, 168, 105);            if (!$this->playable($id)) {                // a game shown but not played: its picture is dimmed                $r->fillRect(144, 40, 168, 105, [0, 0, 0, 170]);            }        } else {            $r->fillRect(144, 40, 168, 105, [40, 20, 16]);            $font->draw($r, 'NO TITLE PICTURE', 228, 90, 1, [167, 140, 120], 'center');        }        $a = $catalog->analysis($id);        $font->draw($r, $catalog->summary($id), 228, 152, 1, $this->playable($id) ? [242, 178, 51] : [150, 130, 110], 'center');        $maps = $a['maps'];        $list = count($maps) > 6 ? $maps[0] . ' ... ' . $maps[count($maps) - 1] : implode(' ', $maps);        $font->draw($r, $list, 228, 164, 1, [210, 190, 170], 'center');        if ($this->downloading >= 0) {            // the WAD of the server coming block by block            $r->fillRect(150, 174, 156, 8, [40, 20, 16]);            $r->fillRect(150, 174, 156 * $this->downloading, 8, [120, 190, 255]);            $font->draw($r, 'DOWNLOADING ' . (int) round($this->downloading * 100) . '%', 228, 186, 1, [120, 190, 255], 'center');        } elseif ($this->downloadError !== '') {            $font->draw($r, substr($this->downloadError, 0, 30), 228, 176, 1, [255, 120, 90], 'center');        } else {            $notes = $a['problems'] !== [] ? count($a['problems']) . ' UNSUPPORTED FEATURE(S)' : 'FULLY SUPPORTED';            $font->draw($r, $notes, 228, 176, 1, $a['problems'] !== [] ? [255, 140, 90] : [140, 220, 120], 'center');        }        if ((int) ($this->time * 2) % 2 === 0) {            $font->draw($r, 'UP / DOWN: CHOOSE - FIRE / ENTER: PLAY', 160, 214, 1, [242, 178, 51], 'center');        }        $font->draw($r, 'PUT YOUR OWN WADS IN THE WADS FOLDER', 160, 228, 1, [120, 100, 90], 'center');    }}