UK
games/alis / src / Alis / HdSprites.php · commit 9c722cf
<?phpnamespace App\Alis;/** * HD edition: the game's pictures drawn again from bigger versions (made once by an upscaler, Real-ESRGAN: the * "sprite pack", private files hd/<key>.png + hd/sprites.json, tools/hd/). * * destofen() tells drawn() each bitmap it puts on the screen (which one, where, flipped or not). At each frame shown, * shown() looks at the screen's pixels: where they are still those of a bitmap (its opaque pixels, the same colours), * the bigger version can replace them. The screen is cut in tiles of TILE pixels per bitmap: a tile is drawn when every * opaque pixel of the bitmap in it is still on the screen, or covered by a later bitmap that is drawn too (so a figure * over a background keeps the background whole under it). Whatever else changed the pixels (the 3D, a film, a fill) * stays as it is. The palette must be the one of the pack's picture for the colours of the bitmap (a fade shows the * original pixels until it ends). * * The key of a bitmap: its bytes (header, palette offset, pixels) and type, hashed: the same picture in any script. */final class HdSprites{    public const TILE = 8;    private const MAX_RECORDS = 256;    public static bool $on = false;    /** the game's data folder (lazy files: hd-sprites.json, hd-<key>.png; a developer's copy: <data>/hd/) */    public static string $dir = '';    /** tools/run.php --hd-capture=<dir>: every new bitmap written there (1x PNG + its palette, the brightest seen) */    public static ?string $capture = null;    /** @var array<string, array{w: int, h: int, pal: array<int, int>}>|null the pack's list (hd/sprites.json) */    public static ?array $pack = null;    /** @var array<string, array{0: string, 1: int, 2: int, 3: int, 4: int, 5: int, 6: int, 7: int}> key|x|y|flip => [key, x, y, flip, cx1, cy1, cx2, cy2] */    public static array $records = [];    /** @var list<array{key: string, x: int, y: int, w: int, h: int, flip: int, tiles: list<array{0: int, 1: int, 2: int, 3: int}>}> what HdRenderer draws (screen pixels of the frame) */    public static array $shown = [];    /** @var array<string, array{w: int, h: int, rows: list<string>, runs: list<list<array{0: int, 1: int}>>, used: string}> decoded bitmaps */    private static array $images = [];    /** @var array<int, string> bitmap address|type|w|h => key (the hash is computed once per address and content) */    private static array $keys = [];    private static int $scratch = 0;    private static string $lastPixels = '';    private static string $lastState = '';    /** @var array<string, int> capture: key => brightness of the saved picture */    private static array $captured = [];    /**     * A file of the pack: the developer's copy (<data>/hd/<name>), else the playground's private files (lazy     * hd-<name>, downloaded in the background: null until it is here). The VM never waits for it.     */    public static function file(string $name): ?string    {        if (SysVars::$lazyDev !== '' && is_file(SysVars::$lazyDev . '/hd/' . $name)) {            return SysVars::$lazyDev . '/hd/' . $name;        }        if (is_file(self::$dir . '/hd-' . $name)) {            return self::$dir . '/hd-' . $name;     // downloaded already (sys_lazy_file() only starts downloads)        }        if (isset(SysVars::$fetching['hd-' . $name])) {            return null;        }        $pending = SysVars::$lazyPending;        $path = sys_lazy_file(self::$dir, 'hd-' . $name);        SysVars::$lazyPending = $pending;        return $path;    }    /** Loads the pack's list when it is here (true = loaded). */    public static function loadPack(): bool    {        if (self::$pack !== null) {            return true;        }        $path = self::file('sprites.json');        if ($path === null) {            return false;        }        $list = json_decode((string) file_get_contents($path), true);        self::$pack = [];        foreach (is_array($list) ? $list : [] as $key => $m) {            $pal = [];            foreach ($m['pal'] ?? [] as $c => $v) {                $pal[(int) $c] = (int) $v;            }            self::$pack[(string) $key] = ['w' => (int) $m['w'], 'h' => (int) $m['h'], 'pal' => $pal];        }        return true;    }    public static function reset(): void    {        self::$records = self::$shown = self::$images = self::$keys = [];        self::$lastPixels = self::$lastState = '';    }    /**     * destofen() put a bitmap: $type 0x10 / 0x12 (4 bits + palette offset) or 0x14 / 0x16 (8 bits), its top left at     * ($x, $y), $width x $height, the part drawn = screen pixels [cx1, cx2) x [cy1, cy2).     */    public static function drawn(int $bitmap, int $type, int $x, int $y, int $width, int $height, int $flip, int $cx1, int $cy1, int $cx2, int $cy2): void    {        if ($cx2 <= $cx1 || $cy2 <= $cy1 || $width <= 0 || $height <= 0) {            return;        }        $key = self::key($bitmap, $type, $width, $height);        if ($key === null) {            return;        }        if (self::$capture !== null) {            self::capture($key, $bitmap, $type, $width, $height);            return;        }        if (self::$pack === null || !isset(self::$pack[$key])) {            return;          // not in the pack: nothing to draw instead        }        self::image($key, $bitmap, $type, $width, $height);        $id = $key . '|' . $x . '|' . $y . '|' . ($flip ? 1 : 0);        unset(self::$records[$id]);           // most recent last: the drawing order        self::$records[$id] = [$key, $x, $y, $flip ? 1 : 0, $cx1, $cy1, $cx2, $cy2];        if (count(self::$records) > self::MAX_RECORDS) {            unset(self::$records[array_key_first(self::$records)]);        }    }    /**     * tools/hd/extract.php: a bitmap read from a script's resources (not drawn by the game), written like capture()     * in the current Img::$mpalet. $overwrite = false keeps a picture already in the folder (a capture made while     * playing has the true palette). Returns the key, null when the bitmap is not usable.     */    public static function captureBitmap(int $bitmap, int $type, int $width, int $height, bool $overwrite): ?string    {        $key = self::key($bitmap, $type, $width, $height);        if ($key === null || self::$capture === null) {            return null;        }        if (!$overwrite && is_file(self::$capture . "/$key.png")) {            return $key;        }        self::capture($key, $bitmap, $type, $width, $height);        return $key;    }    /** the colour indexes a bitmap's opaque pixels use (after captureBitmap() or image()) */    public static function usedColours(int $bitmap, int $type, int $width, int $height): array    {        $key = self::key($bitmap, $type, $width, $height);        return $key === null ? [] : array_map('ord', str_split(self::image($key, $bitmap, $type, $width, $height)['used']));    }    private static function key(int $bitmap, int $type, int $width, int $height): ?string    {        $len = ($type === 0x14 || $type === 0x16) ? $width * $height : ($width >> 1) * $height;        if ($len <= 0 || $width > Host::$pixelbuf->w || $height > 480) {            return null;        }        $bytes = substr(Alis::$mem, $bitmap, 8 + $len);        $cache = $bitmap . '|' . $type . '|' . $width . '|' . $height;        $sum = hash('crc32b', $bytes);        $known = self::$keys[$cache] ?? null;        if ($known !== null && $known[0] === $sum) {            return $known[1];        }        $key = substr(md5($type . '|' . $width . '|' . $height . '|' . $bytes), 0, 16);        self::$keys[$cache] = [$sum, $key];        if (count(self::$keys) > 4096) {            self::$keys = [];        }        return $key;    }    /**     * The bitmap alone, decoded by the game's own blitters into a scratch buffer: its rows (colour indexes) and the     * runs of opaque pixels of each row (drawn twice, over 0x00 and over 0xff: what changes is transparent).     */    private static function image(string $key, int $bitmap, int $type, int $width, int $height): array    {        if (isset(self::$images[$key])) {            return self::$images[$key];        }        $pw = Host::$pixelbuf->w;        if (self::$scratch === 0) {            self::$scratch = host_alloc($pw * 480);        }        $draw = static function (string $fill) use ($bitmap, $type, $width, $height, $pw): array {            $s = self::$scratch;            for ($r = 0; $r < $height; $r++) {                mem_write($s + $r * $pw, str_repeat($fill, $width));            }            $keep = Img::$wdraw;            Img::$wdraw = $s;            $at = $bitmap + 6;            $pos = image_rect(0, 0, $width, $height);            $bmp = image_rect(0, 0, $width, $height);            match ($type) {                0x10 => draw_4to8bit_0($at + 2, $pos, $bmp, $width, 0, xread8($at)),                0x12 => draw_4to8bit_2($at + 2, $pos, $bmp, $width, 0, xread8($at)),                0x14 => draw_8bit_0($at, $pos, $bmp, $width, 0),                default => draw_8bit_2($at, $pos, $bmp, $width, 0),            };            Img::$wdraw = $keep;            $rows = [];            for ($r = 0; $r < $height; $r++) {                $rows[] = substr(Alis::$mem, $s + $r * $pw, $width);            }            return $rows;        };        $a = $draw("\0");        $b = ($type === 0x10 || $type === 0x14) ? $draw("\xff") : $a;        $runs = [];        $used = [];        foreach ($a as $r => $row) {            $list = [];            $start = -1;            for ($i = 0; $i <= $width; $i++) {                $opaque = $i < $width && $row[$i] === $b[$r][$i];                if ($opaque) {                    $used[$row[$i]] = true;                    if ($start < 0) {                        $start = $i;                    }                } elseif ($start >= 0) {                    $list[] = [$start, $i - $start];                    $start = -1;                }            }            $runs[] = $list;        }        $img = ['w' => $width, 'h' => $height, 'rows' => $a, 'runs' => $runs, 'used' => implode('', array_keys($used))];        if (count(self::$images) > 512) {            self::$images = [];        }        return self::$images[$key] = $img;    }    /** capture: the bitmap as a PNG in the current palette (kept when brighter than the one saved: not mid-fade) */    private static function capture(string $key, int $bitmap, int $type, int $width, int $height): void    {        $img = self::image($key, $bitmap, $type, $width, $height);        $pal = Img::$mpalet;        $light = 0;        foreach (str_split($img['used']) as $c) {            $v = $pal[\ord($c)] ?? 0;            $light += ($v >> 16 & 0xff) + ($v >> 8 & 0xff) + ($v & 0xff);        }        $dir = (string) self::$capture;        if (!isset(self::$captured[$key]) && is_file("$dir/$key.json")) {            self::$captured[$key] = (int) (json_decode((string) file_get_contents("$dir/$key.json"), true)['light'] ?? 0);        }        if (isset(self::$captured[$key]) && $light <= self::$captured[$key]) {            return;        }        self::$captured[$key] = $light;        $gd = imagecreatetruecolor($width, $height);        imagealphablending($gd, false);        imagesavealpha($gd, true);        $clear = imagecolorallocatealpha($gd, 0, 0, 0, 127);        imagefill($gd, 0, 0, $clear);        $colors = [];        foreach ($img['runs'] as $r => $runs) {            foreach ($runs as [$s, $n]) {                for ($i = $s; $i < $s + $n; $i++) {                    $c = \ord($img['rows'][$r][$i]);                    $v = $pal[$c] ?? 0;                    imagesetpixel($gd, $i, $r, $colors[$c] ??= imagecolorallocatealpha($gd, $v >> 16 & 0xff, $v >> 8 & 0xff, $v & 0xff, 0));                }            }        }        imagepng($gd, "$dir/$key.png");        $used = [];        foreach (str_split($img['used']) as $c) {            $used[\ord($c)] = $pal[\ord($c)] ?? 0;        }        ksort($used);        file_put_contents("$dir/$key.json", json_encode(['w' => $width, 'h' => $height, 'light' => $light, 'pal' => $used]));    }    /**     * sys_render(): which tiles of which recorded bitmaps are still on the screen ($pixels = the frame shown).     * Fills self::$shown for HdRenderer.     */    public static function shown(string $pixels, int $w, int $h, array $palette): void    {        if (self::$pack === null || self::$records === []) {            self::$shown = [];            return;        }        $state = md5(serialize(array_keys(self::$records)) . serialize($palette));        if ($pixels === self::$lastPixels && $state === self::$lastState) {            return;        }        self::$lastPixels = $pixels;        self::$lastState = $state;        $T = self::TILE;        $list = [];            // per record still worth looking at: [record, image, bad pixels "x,y" => true]        foreach (self::$records as $id => $rec) {            [$key, $x, $y, $flip, $cx1, $cy1, $cx2, $cy2] = $rec;            $img = self::$images[$key] ?? null;            $meta = self::$pack[$key] ?? null;            if ($img === null || $meta === null) {                continue;            }            // the palette of the pack's picture, for this bitmap's colours            $palOk = true;            foreach ($meta['pal'] as $c => $v) {                if ((($palette[$c] ?? 0) & 0xffffff) !== $v) {                    $palOk = false;                    break;                }            }            if (!$palOk) {                continue;            }            $good = 0;            $bad = [];            $cx1 = max($cx1, 0);            $cy1 = max($cy1, 0);            $cx2 = min($cx2, $w);            $cy2 = min($cy2, $h);            for ($sy = $cy1; $sy < $cy2; $sy++) {                $r = $sy - $y;                $row = $img['rows'][$r];                foreach ($img['runs'][$r] as [$s, $n]) {                    // the run on the screen: columns x + s .. (flipped: mirrored in the bitmap's width)                    $a = $flip ? $x + $img['w'] - $s - $n : $x + $s;                    $from = max($a, $cx1);                    $to = min($a + $n, $cx2);                    if ($to <= $from) {                        continue;                    }                    $part = $flip ? strrev(substr($row, $s, $n)) : substr($row, $s, $n);                    $part = substr($part, $from - $a, $to - $from);                    $screen = substr($pixels, $sy * $w + $from, $to - $from);                    if ($screen === $part) {                        $good += $to - $from;                        continue;                    }                    for ($i = 0, $k = $to - $from; $i < $k; $i++) {                        if ($screen[$i] === $part[$i]) {                            $good++;                        } else {                            $bad[($from + $i) . ',' . $sy] = true;                        }                    }                }            }            if ($good === 0) {                unset(self::$records[$id]);        // nothing of it on the screen any more                continue;            }            $list[] = [$rec, $img, $bad, [$cx1, $cy1, $cx2, $cy2]];        }        // a bad pixel is fine when a later bitmap in the list shows its own pixel there (drawn over it)        $n = count($list);        $out = [];        for ($k = 0; $k < $n; $k++) {            [$rec, $img, $bad, $clip] = $list[$k];            [$key, $x, $y, $flip] = $rec;            $badTiles = [];            foreach ($bad as $p => $_) {                [$px, $py] = explode(',', $p);                $px = (int) $px;                $py = (int) $py;                $covered = false;                for ($j = $k + 1; $j < $n && !$covered; $j++) {                    [$r2, $i2, $b2, $c2] = $list[$j];                    if ($px < $c2[0] || $px >= $c2[2] || $py < $c2[1] || $py >= $c2[3] || isset($b2[$p])) {                        continue;                    }                    $u = $r2[3] ? $r2[1] + $i2['w'] - 1 - $px : $px - $r2[1];                    foreach ($i2['runs'][$py - $r2[2]] as [$s, $len]) {                        if ($u >= $s && $u < $s + $len) {                            $covered = true;                            break;                        }                    }                }                if (!$covered) {                    $badTiles[intdiv($px - $x, $T) . ',' . intdiv($py - $y, $T)] = true;                }            }            // the tiles (screen rectangles, clipped), whole rows of good tiles merged            [$cx1, $cy1, $cx2, $cy2] = $clip;            $tiles = [];            for ($ty = intdiv($cy1 - $y, $T); $y + $ty * $T < $cy2; $ty++) {                $y1 = max($y + $ty * $T, $cy1);                $y2 = min($y + ($ty + 1) * $T, $cy2);                $runStart = null;                for ($tx = intdiv($cx1 - $x, $T); ; $tx++) {                    $inside = $x + $tx * $T < $cx2;                    $ok = $inside && !isset($badTiles[$tx . ',' . $ty]);                    if ($ok && $runStart === null) {                        $runStart = max($x + $tx * $T, $cx1);                    } elseif (!$ok && $runStart !== null) {                        $tiles[] = [$runStart, $y1, min($x + $tx * $T, $cx2), $y2];                        $runStart = null;                    }                    if (!$inside) {                        break;                    }                }            }            if ($tiles !== []) {                $out[] = ['key' => $key, 'x' => $x, 'y' => $y, 'w' => $img['w'], 'h' => $img['h'], 'flip' => $flip, 'tiles' => $tiles];            }        }        self::$shown = $out;    }}