UK
games/alis / src / Alis / Prefetch.php · commit 9c722cf
<?phpnamespace App\Alis;/** * Background prefetch of the files a game loads on demand (catalog "lazy"), from the playground's externals, into * the browser's own HTTP cache (on disk: not the page's IndexedDB, which lives in the engine's memory): later, the * game finds them there at once, even in a new visit. Only while the game waits for nothing (its own downloads * first), one part at a time, the bytes dropped as they come. A game of PREFETCH_ALL bytes at most is prefetched * whole; a bigger one, its files of PREFETCH_SMALL bytes at most (the scripts' sources first). The files done are * remembered in the player's storage (alis-prefetch-<game>.json, name => version): never asked again. */final class Prefetch{    public const PREFETCH_ALL = 64 * 1048576;    public const PREFETCH_SMALL = 1048576;    /** @var list<string> the files still to prefetch */    private static array $queue = [];    /** @var array<string, string> name => version, the files done */    private static array $done = [];    private static string $game = '';    private static mixed $file = null;    private static string $name = '';    private static int $next = 0;    private static bool $busy = false;    private static int $since = 0;    private static float $idle = 0.0;    public static function start(string $game): void    {        self::stop();        if (SysVars::$externals === null || SysVars::$lazyDev !== '' || SysVars::$lazy === []) {            return;        }        self::$game = $game;        self::$done = [];        $saved = SysVars::$storage?->read(self::key());        if ($saved !== null) {            self::$done = (array) json_decode($saved, true);        }        $total = 0;        foreach (SysVars::$lazy as [$size]) {            $total += (int) $size;        }        $names = [];        foreach (SysVars::$lazy as $name => [$size, $hash]) {            if (str_starts_with($name, 'hd-') && $name !== 'hd-sprites.json') {                continue;          // the HD edition's pictures: loaded when shown (App\Alis\HdSprites)            }            if (($total <= self::PREFETCH_ALL || $size <= self::PREFETCH_SMALL) && (self::$done[$name] ?? null) !== $hash) {                $names[$name] = (int) $size;            }        }        // the scripts' sources first (each new place opens some), then the smallest        uksort($names, static fn ($a, $b) => [!preg_match('/\.(als|res)$/', $a), $names[$a]] <=> [!preg_match('/\.(als|res)$/', $b), $names[$b]]);        self::$queue = array_keys($names);    }    public static function stop(): void    {        self::$queue = [];        self::$file = null;        self::$busy = false;        self::$idle = 0.0;    }    /** @return int the files left (tests, the trace) */    public static function left(): int    {        return count(self::$queue) + (self::$file !== null ? 1 : 0);    }    private static function key(): string    {        return 'alis-prefetch-' . self::$game . '.json';    }    /** Each frame (PlayScene): one part asked at a time, only after the game waited for nothing for a second. */    public static function tick(float $dt): void    {        if (self::$busy || (self::$queue === [] && self::$file === null) || SysVars::$externalsOff || SysVars::$externals === null) {            return;        }        if (SysVars::$fetching !== [] || SysVars::$externals->pending() > 0) {            self::$idle = 0.0;            // the game's own downloads first            return;        }        self::$idle += $dt;        if (self::$idle < 1.0) {            return;        }        if (self::$file === null) {            $name = (string) array_shift(self::$queue);            $loaded = array_flip(array_map('basename', array_keys(SysVars::$lazyLoaded)));            if (isset($loaded[$name])) {                return;                   // the game has it already            }            self::$busy = true;            self::$name = $name;            SysVars::$externals->open(SysVars::$externalsDir . '/' . $name)->then(                static function ($file): void {                    self::$busy = false;                    self::$file = $file;                    self::$next = 0;                },                static function (): void {                    self::$busy = false;  // not there: the next one                },            );            return;        }        $file = self::$file;        $total = $file->size();        if (self::$next >= $total) {            self::finished();            return;        }        $from = self::$next;        $want = min(SysVars::LAZY_PART, $total - $from);        self::$busy = true;        $file->read($from, $want)->then(            static function (string $bytes): void {                self::$busy = false;                self::$next += strlen($bytes) ?: SysVars::LAZY_PART;                unset($bytes);            // only the browser's cache keeps them            },            static function (): void {                self::$busy = false;                self::$file = null;       // a failure: the next file            },        );    }    private static function finished(): void    {        self::$done[self::$name] = (string) (SysVars::$lazy[self::$name][1] ?? '');        self::$file = null;        if (++self::$since >= 10 || self::$queue === []) {            self::$since = 0;            SysVars::$storage?->write(self::key(), (string) json_encode(self::$done));        }    }}