PT
games/dmmotor / src / Dm / WadFile.php · commit 9d248a4
<?php/* * dmmotor — a quick look into a WAD file on disk (also split in parts <name>.0, .1...) without reading all of it: * its type, its directory and a few lumps. Used to list and analyse the WADs of the wads/ folder. * Written for dmmotor (GPL v2, see LICENSE). */namespace App\Dm;final class WadFile{    /** @var list<array{0:string,1:int}> [file, size] */    private array $parts = [];    public string $type = '';    /** @var list<array{0:string,1:int,2:int}> [name, offset, size] */    public array $lumps = [];    /** @var (\Closure(int,int):string)|null bytes from elsewhere than a file (a WAD on the server, read by blocks) */    private ?\Closure $reader = null;    private int $readerSize = 0;    /**     * A WAD whose bytes come from $read(offset, length) (a remote file, a string), $size bytes long.     * With $head / $directory given (already read), nothing is read here.     */    public static function fromReader(string $name, callable $read, int $size): self    {        $w = new self('');        $w->reader = \Closure::fromCallable($read);        $w->readerSize = $size;        $w->name = $name;        $w->readDirectory();        return $w;    }    public string $name = '';    public function __construct(public readonly string $base)    {        if ($base === '') {            return;        }        $this->name = basename($base);        if (is_file($base)) {            $this->parts[] = [$base, (int) filesize($base)];        } else {            for ($i = 0; is_file("$base.$i"); $i++) {                $this->parts[] = ["$base.$i", (int) filesize("$base.$i")];            }        }        $this->readDirectory();    }    private function readDirectory(): void    {        $this->type = '';        $this->lumps = [];        $head = $this->read(0, 12);        if (strlen($head) < 12) {            return;        }        $h = unpack('a4id/Vcount/Voffset', $head);        if ($h['id'] !== 'IWAD' && $h['id'] !== 'PWAD') {            return;        }        $this->type = $h['id'];        $dir = $this->read($h['offset'], $h['count'] * 16);        for ($i = 0; $i + 16 <= strlen($dir); $i += 16) {            $e = unpack('Vpos/Vsize/a8name', $dir, $i);            $this->lumps[] = [strtoupper(rtrim($e['name'], "\0")), $e['pos'], $e['size']];        }    }    public function isWad(): bool    {        return $this->type !== '';    }    public function size(): int    {        return $this->reader !== null ? $this->readerSize : array_sum(array_column($this->parts, 1));    }    /** The directory's place: [offset, bytes] (to read it from a remote file first). @return array{0:int,1:int}|null */    public static function directoryRange(string $head): ?array    {        if (strlen($head) < 12) {            return null;        }        $h = unpack('a4id/Vcount/Voffset', $head);        return ($h['id'] === 'IWAD' || $h['id'] === 'PWAD') ? [$h['offset'], $h['count'] * 16] : null;    }    /** The places of the lumps analyse() and titleBmp() read (LINEDEFS of 8 maps, TITLEPIC, PLAYPAL). @return list<array{0:int,1:int}> */    public function rangesToInspect(): array    {        $ranges = [];        $linedefs = 0;        foreach ($this->lumps as [$name, $pos, $size]) {            if ($name === 'LINEDEFS' && $linedefs++ < 8) {                $ranges[] = [$pos, $size];            } elseif ($name === 'TITLEPIC' || $name === 'PLAYPAL') {                $ranges[] = [$pos, $size];            }        }        return $ranges;    }    /** A free game (Freedoom, FreeDM: they carry a FREEDOOM lump), or a mod: what dmmotor plays. */    public function isFree(): bool    {        return $this->type === 'PWAD' || $this->has('FREEDOOM');    }    /** Bytes $pos .. $pos + $len across the parts. */    public function read(int $pos, int $len): string    {        if ($this->reader !== null) {            return ($this->reader)($pos, $len);        }        $out = '';        $start = 0;        foreach ($this->parts as [$file, $size]) {            if ($len > 0 && $pos < $start + $size) {                $from = max(0, $pos - $start);                $take = min($size - $from, $len);                $f = fopen($file, 'rb');                if ($f !== false) {                    fseek($f, $from);                    $out .= (string) fread($f, $take);                    fclose($f);                }                $pos += $take;                $len -= $take;            }            $start += $size;        }        return $out;    }    public function has(string $name): bool    {        return $this->find($name) !== null;    }    /** @return array{0:string,1:int,2:int}|null the last lump of that name */    private function find(string $name): ?array    {        for ($i = count($this->lumps) - 1; $i >= 0; $i--) {            if ($this->lumps[$i][0] === $name) {                return $this->lumps[$i];            }        }        return null;    }    public function lump(string $name): ?string    {        $l = $this->find($name);        return $l === null ? null : $this->read($l[1], $l[2]);    }    /** @return list<string> the maps, in directory order */    public function maps(): array    {        $maps = [];        foreach ($this->lumps as $i => [$name]) {            if (preg_match('~^(E[1-9]M[1-9]|MAP[0-9][0-9])$~', $name) && ($this->lumps[$i + 1][0] ?? '') === 'THINGS') {                $maps[] = $name;            }        }        return $maps;    }    /**     * What the engine can do with it. @return array{maps:list<string>,commercial:bool,problems:list<string>,     * things:int,sprites:int,flats:int,textures:bool,music:int,sounds:int,dehacked:bool}     */    public function analyse(): array    {        $maps = $this->maps();        $problems = [];        $names = array_column($this->lumps, 0);        $things = 0;        foreach ($this->lumps as $i => [$name, , $size]) {            if ($name === 'BEHAVIOR') {                $problems[] = 'Hexen-format levels (BEHAVIOR): not supported';            } elseif ($name === 'TEXTMAP') {                $problems[] = 'UDMF levels (TEXTMAP): not supported';            } elseif (in_array($name, ['DECORATE', 'ZSCRIPT', 'MAPINFO', 'ZMAPINFO', 'GLDEFS'], true)) {                $problems[] = "$name: a lump of ZDoom-family engines, ignored";            } elseif (in_array($name, ['ANIMATED', 'SWITCHES'], true)) {                $problems[] = "$name (Boom): ignored, the original tables are used";            } elseif ($name === 'THINGS') {                $things += intdiv($size, 10);            }        }        // Boom line specials (beyond 141): unknown to this engine        $checked = 0;        foreach ($this->lumps as $i => [$name, $pos, $size]) {            if ($name !== 'LINEDEFS' || $checked++ >= 8) {                continue;            }            $data = $this->read($pos, $size);            for ($o = 0; $o + 14 <= strlen($data); $o += 14) {                $special = unpack('v', $data, $o + 6)[1];                if ($special > 141) {                    $problems[] = "line specials beyond the original's (Boom / MBF, e.g. $special): those lines do nothing";                    break 2;                }            }        }        $between = function (string $start, string $end) use ($names): int {            $n = 0;            $in = false;            foreach ($names as $name) {                if ($name === $start || $name === $start[0] . $start) {                    $in = true;                } elseif ($name === $end || $name === $end[0] . $end) {                    $in = false;                } elseif ($in) {                    $n++;                }            }            return $n;        };        return [            'maps' => $maps,            'commercial' => $maps !== [] ? str_starts_with($maps[0], 'MAP') : $this->has('MAP01'),            'problems' => array_values(array_unique($problems)),            'things' => $things,            'sprites' => $between('S_START', 'S_END'),            'flats' => $between('F_START', 'F_END'),            'textures' => in_array('TEXTURE1', $names, true),            'music' => count(array_filter($names, fn ($n) => str_starts_with($n, 'D_'))),            'sounds' => count(array_filter($names, fn ($n) => str_starts_with($n, 'DS'))),            'dehacked' => in_array('DEHACKED', $names, true),        ];    }    /** Its title picture (TITLEPIC with its PLAYPAL, or the base game's palette) as an 8-bit BMP, or null. */    public function titleBmp(?string $palette = null): ?string    {        $pic = $this->lump('TITLEPIC');        $palette = $this->lump('PLAYPAL') ?? $palette;        if ($pic === null || $palette === null || strlen($pic) < 8) {            return null;        }        $fb = new Render\Framebuffer(320, 200);        if (strlen($pic) === 64000) {            // a raw 320 x 200 picture (some mods)            $fb->pixels = substr(str_pad($pic, 64000, "\0"), 0, 64000);        } else {            $fb->drawPatch(0, 0, Patch::decode($pic));        }        return $fb->toBmp(substr($palette, 0, 768));    }}