KO
games/dmmotor / src / Service / SaveGames.php · commit 9d248a4
<?php/* * dmmotor — save games (after p_saveg.c / G_DoSaveGame of linuxdoom-1.10): the whole level state is kept * (every sector, line, thing and mover), compressed, in the player's storage (IndexedDB in the browser). * Copyright (C) 1993-1996 by id Software, Inc.; PHP port for dmmotor. GPL v2 (see LICENSE). */namespace App\Service;use App\Dm\MenuScreen;use App\Dm\Play\Random;use App\Dm\Play\World;use JumPHP\Save\Storage;final class SaveGames{    public const SLOTS = 6;    private static function file(string $iwad, int $slot): string    {        return "save-$iwad-$slot.dat";    }    /** @return array<string,mixed>|null the header of a slot (name, map) */    public static function info(Storage $storage, string $iwad, int $slot): ?array    {        $info = $storage->readJson("save-$iwad-$slot.json");        return is_array($info) ? $info : null;    }    public static function write(Storage $storage, string $iwad, int $slot, World $world, int $episode, int $map): bool    {        $data = serialize(['world' => $world, 'random' => Random::state(), 'episode' => $episode, 'map' => $map]);        $ok = $storage->write(self::file($iwad, $slot), function_exists('gzcompress') ? 'Z' . gzcompress($data, 6) : 'S' . $data);        $storage->writeJson("save-$iwad-$slot.json", [            'name' => $world->mapName($episode, $map) . '  ' . date('d/m H:i'),            'map' => $map, 'episode' => $episode,        ]);        return $ok;    }    /** @return array<string,mixed>|null ['world' => World, 'random' => ..., 'episode' => int, 'map' => int] */    public static function read(Storage $storage, string $iwad, int $slot): ?array    {        $raw = $storage->read(self::file($iwad, $slot));        if ($raw === null || $raw === '') {            return null;        }        $data = $raw[0] === 'Z' ? gzuncompress(substr($raw, 1)) : substr($raw, 1);        if ($data === false) {            return null;        }        $state = unserialize($data);        return is_array($state) && ($state['world'] ?? null) instanceof World ? $state : null;    }    /** The menu of the slots (M_LOADG / M_SAVEG), each its level and date. */    public static function menu(Storage $storage, string $iwad, string $id): MenuScreen    {        $items = [];        for ($i = 0; $i < self::SLOTS; $i++) {            $info = self::info($storage, $iwad, $i);            $items[] = ['@' . ($info['name'] ?? 'EMPTY SLOT'), "slot$i"];        }        return new MenuScreen($id, $items, 80, 54, [[$id === 'load' ? 'M_LOADG' : 'M_SAVEG', 72, 28]]);    }}