TR
games/dmmotor / src / Service / WadCatalog.php · commit 9d248a4
<?php/* * dmmotor — the WADs the player can choose: Freedoom (published with the game, assets/wads/) and every WAD put in * the wads/ folder of the game (kept out of git: never published). Each one is analysed: a whole game (IWAD) or a * mod (PWAD, played over an IWAD of the same kind), its maps, what the engine does not support. * Written for dmmotor (GPL v2, see LICENSE). */namespace App\Service;use App\Dm\WadFile;use JumPHP\Async\Task;use JumPHP\Externals\Entry;use JumPHP\Externals\Externals;use JumPHP\Externals\RemoteFile;final class WadCatalog{    /** the folders searched, relative to the game */    public const FOLDERS = ['assets/wads', 'wads'];    private const NAMES = ['freedoom1' => 'FREEDOOM PHASE 1', 'freedoom2' => 'FREEDOOM PHASE 2'];    /** @var array<string,WadFile> id => file */    private array $files = [];    /** @var array<string,array<string,mixed>> id => analysis */    private array $analyses = [];    /** @var array<string,int> id => 0 the game's own WADs (the first folder: Freedoom), 1 the wads/ folder */    private array $sources = [];    /** the folder of the server's externals shared with dmmotor (Administration of the playground) */    public const REMOTE_FOLDER = 'dmmotor/wads';    /** @var array<string,Entry> id => a WAD of the server, not inspected yet or not downloaded */    private array $remote = [];    /** @var array<string,string> id => new, inspecting, ready, error */    private array $remoteState = [];    /** @var array<string,string> id => the whole WAD, downloaded */    private array $data = [];    /** @param list<string> $folders absolute paths (searched with their sub-folders) */    public function scan(array $folders): void    {        $this->files = [];        $this->analyses = [];        $this->sources = [];        foreach ($folders as $n => $folder) {            $folder = rtrim($folder, '/');            if (!is_dir($folder)) {                continue;            }            $ignore = self::ignored($folder);            $found = [];            $it = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($folder, \FilesystemIterator::SKIP_DOTS));            foreach ($it as $file) {                $relative = ltrim(substr($file->getPathname(), strlen($folder)), '/');                if (!self::isIgnored($relative, $ignore)) {                    $found[] = $file->getPathname();                }            }            sort($found);            foreach ($found as $file) {                if (!preg_match('~^(.+)\.wad(\.0)?$~i', $file, $m)) {                    continue;                }                $base = ($m[2] ?? '') === '.0' ? substr($file, 0, -2) : $file;                // the id: the path under the folder, without ".wad" ("freedoom1", "megawads/scythe")                $id = strtolower(ltrim(substr($m[1], strlen($folder)), '/'));                if (isset($this->files[$id])) {                    continue;   // the first folder wins (Freedoom)                }                $wad = new WadFile($base);                if ($wad->isWad()) {                    $this->files[$id] = $wad;                    $this->sources[$id] = $n === 0 ? 0 : 1;                }            }        }        // the WADs of the server keep what is known of them: downloaded ones stay, inspected ones are read again (cached)        foreach ($this->data as $id => $data) {            $this->files[$id] = WadFile::fromReader(basename($this->remote[$id]->path ?? $id), fn (int $p, int $l): string => (string) substr($data, $p, $l), strlen($data));        }        foreach ($this->remoteState as $id => $state) {            if (!isset($this->data[$id]) && $state !== 'error') {                $this->remoteState[$id] = 'new';            }        }    }    /** The patterns of the folder's .syncignore (also used by tools/push-wads.sh). @return list<string> */    private static function ignored(string $folder): array    {        $patterns = [];        foreach (@file("$folder/.syncignore", FILE_IGNORE_NEW_LINES) ?: [] as $line) {            $line = trim($line);            if ($line !== '' && $line[0] !== '#') {                $patterns[] = $line;            }        }        return $patterns;    }    /** rsync-like: "name/" = a folder of that name at any depth, "/x" = from the top, else a file name pattern. */    private static function isIgnored(string $relative, array $patterns): bool    {        $parts = explode('/', $relative);        foreach ($patterns as $p) {            $dir = str_ends_with($p, '/');            $p = rtrim($p, '/');            if (str_starts_with($p, '/')) {                if (fnmatch(ltrim($p, '/'), $parts[0]) && ($dir ? count($parts) > 1 : true)) {                    return true;                }                continue;            }            $candidates = $dir ? array_slice($parts, 0, -1) : $parts;            foreach ($candidates as $part) {                if (fnmatch($p, $part)) {                    return true;                }            }        }        return false;    }    /** the order of the sources in the list: the wads/ folder first, then the game's own WADs, then the server */    private const ORDER = [1 => 0, 0 => 1, 2 => 2];    /** The WADs grouped by source (the wads/ folder, the game's own, the server), each group by name. @return list<string> */    public function ids(): array    {        $ids = array_values(array_unique([...array_keys($this->files), ...array_keys($this->remote)]));        usort($ids, fn (string $a, string $b): int => [self::ORDER[$this->source($a)], $this->name($a), $a] <=> [self::ORDER[$this->source($b)], $this->name($b), $b]);        return $ids;    }    /** Where a WAD comes from: 0 the game's own (Freedoom), 1 the wads/ folder, 2 the server. */    public function source(string $id): int    {        return isset($this->remote[$id]) || str_starts_with($id, 'net/') ? 2 : ($this->sources[$id] ?? 1);    }    // ================================================================ WADs of the server (jumphp/externals)    /** The WADs of the server's shared folder join the list (ids "net/<path>"). @param list<Entry> $entries */    public function addRemote(array $entries): void    {        $prefix = self::REMOTE_FOLDER . '/';        foreach ($entries as $e) {            if ($e->isDir() || !str_starts_with($e->path, $prefix) || !preg_match('~\.wad$~i', $e->path)) {                continue;            }            $id = 'net/' . strtolower(substr($e->path, strlen($prefix), -4));            if (isset($this->files[$id]) && !isset($this->remote[$id])) {                continue;            }            $this->remote[$id] = $e;            $this->remoteState[$id] ??= 'new';        }    }    public function isRemote(string $id): bool    {        return isset($this->remote[$id]);    }    /** new, inspecting, ready, error; '' for a local WAD */    public function remoteState(string $id): string    {        return $this->remoteState[$id] ?? '';    }    public function isDownloaded(string $id): bool    {        return isset($this->data[$id]);    }    /** The whole WAD once downloaded. */    public function data(string $id): ?string    {        return $this->data[$id] ?? null;    }    public function remoteSize(string $id): int    {        return $this->remote[$id]->size ?? 0;    }    /**     * Looks into a WAD of the server by packets: its header, its directory, then only the lumps the choice screen     * shows (title picture, palette, the lines of 8 maps). The blocks stay in the cache for the download.     */    public function inspect(string $id, Externals $externals): void    {        if (($this->remoteState[$id] ?? '') !== 'new') {            return;        }        $this->remoteState[$id] = 'inspecting';        $fail = function () use ($id): void {            $this->remoteState[$id] = 'error';        };        $externals->open($this->remote[$id]->path)->then(function (RemoteFile $f) use ($id, $fail): void {            $f->read(0, 12)->then(function (string $head) use ($id, $f, $fail): void {                $range = WadFile::directoryRange($head);                if ($range === null) {                    $fail();                    return;                }                $f->read($range[0], $range[1])->then(function () use ($id, $f, $fail): void {                    $wad = WadFile::fromReader(basename($f->path()), fn (int $p, int $l): string => $f->readNow($p, $l) ?? '', $f->size());                    $ranges = $wad->rangesToInspect();                    $left = count($ranges);                    $done = function () use ($id, $wad): void {                        $this->files[$id] = $wad;                        unset($this->analyses[$id]);                        $this->remoteState[$id] = 'ready';                    };                    if ($left === 0) {                        $done();                        return;                    }                    foreach ($ranges as [$pos, $size]) {                        $f->read($pos, $size)->then(function () use (&$left, $done): void {                            if (--$left === 0) {                                $done();                            }                        }, $fail);                    }                }, $fail);            }, $fail);        }, $fail);    }    /** Downloads a WAD of the server, block by block ($progress 0..1); Task of true. */    public function download(string $id, Externals $externals, ?callable $progress = null): Task    {        $task = new Task();        if (isset($this->data[$id])) {            $task->settle(true);            return $task;        }        $externals->open($this->remote[$id]->path)->then(            function (RemoteFile $f) use ($id, $task, $progress): void {                $f->readAll($progress)->then(function (string $data) use ($id, $task, $f): void {                    $this->data[$id] = $data;                    $this->files[$id] = WadFile::fromReader(basename($f->path()), fn (int $p, int $l): string => (string) substr($data, $p, $l), strlen($data));                    $task->settle(true);                }, fn (\Throwable $e) => $task->settle(null, $e));            },            fn (\Throwable $e) => $task->settle(null, $e),        );        return $task;    }    /**     * Commercial games, never played whatever their form (some are distributed as PWADs): the games of id Software,     * Raven, Rogue, and Chex Quest.     */    // private const COMMERCIAL = '~^(doom|doom1|doom2|doom2f|doomu|doom64|plutonia|tnt|heretic|heretic1|hexen|hexendemo|hexdd|strife|strife0|strife1|voices|chex|chex2|chex3|hacx|sigil|sigil2|nerve|masterlevels)$~';    private const COMMERCIAL = '~^(chlouababa)$~';        /** What dmmotor plays: a free base game (with the FREEDOOM lump) or a mod, never a commercial game. */    public function isFree(string $id): bool    {        return true ;        $file = $this->files[$id] ?? null;        if ($file === null || preg_match(self::COMMERCIAL, strtolower(pathinfo($file->name, PATHINFO_FILENAME)))) {            return false;        }        return $file->isFree();    }    public function file(string $id): ?WadFile    {        return $this->files[$id] ?? null;    }    public function name(string $id): string    {        return self::NAMES[$id] ?? strtoupper(str_starts_with($id, 'net/') ? substr($id, 4) : $id);    }    /** @return array<string,mixed> */    public function analysis(string $id): array    {        if (!isset($this->files[$id])) {            // a WAD of the server not inspected yet            return ['maps' => [], 'commercial' => false, 'problems' => [], 'things' => 0, 'sprites' => 0, 'flats' => 0,                'textures' => false, 'music' => 0, 'sounds' => 0, 'dehacked' => false];        }        return $this->analyses[$id] ??= $this->files[$id]->analyse();    }    public function isMod(string $id): bool    {        return ($this->files[$id] ?? null)?->type === 'PWAD';    }    /** IWAD files of the catalog (local, or downloaded). */    private function isLocalIwad(string $id): bool    {        return ($this->files[$id] ?? null)?->type === 'IWAD' && !isset($this->remote[$id]);    }    /** The IWAD a mod is played over: one with the same kind of maps (Freedoom first). */    public function baseFor(string $id): ?string    {        $commercial = (bool) $this->analysis($id)['commercial'];        $best = null;        foreach ($this->files as $other => $file) {            // a base game: a free IWAD of this computer (Freedoom), with the same kind of maps            if (!$this->isLocalIwad($other) || !$file->isFree() || $file->has('MAP01') !== $commercial) {                continue;            }            if ($best === null || isset(self::NAMES[$other])) {                $best = $other;                if (isset(self::NAMES[$other])) {                    break;                }            }        }        return $best;    }    /** One line about it, for the choice screen. */    public function summary(string $id): string    {        if ($this->isRemote($id) && ($this->remoteState[$id] ?? '') !== 'ready' && !isset($this->data[$id])) {            $mb = number_format($this->remoteSize($id) / 1048576, 1);            return ($this->remoteState[$id] ?? '') === 'error' ? 'SERVER - CANNOT BE READ' : "SERVER - $mb MB - READING...";        }        if (isset($this->files[$id]) && !$this->isFree($id)) {            return 'NOT A FREE GAME: NOT PLAYED';        }        $a = $this->analysis($id);        $count = count($a['maps']);        $kind = $this->isMod($id) ? 'MOD' : 'GAME';        $text = "$kind - $count " . ($count === 1 ? 'MAP' : 'MAPS');        if ($this->isMod($id)) {            $base = $this->baseFor($id);            $text .= $base === null ? ' - NO BASE GAME!' : ' - OVER ' . str_replace('FREEDOOM ', '', $this->name($base));        }        return $text;    }}