KO
apps/winzik / src / Native / NativeTextures.php · commit 6576d6f
<?phpnamespace App\Native;/** * The pictures and texts of one native window: SDL textures belong to the renderer that made them, so each window of * the desktop version loads its own (IMG_Load + SDL_CreateTextureFromSurface) and renders its own texts (SDL_ttf). * Texts are cached by (font, size, colour, text), the oldest dropped past a limit (the scrolling title changes often). */final class NativeTextures{    private const MAX_TEXTS = 400;    private const TEXT_BUDGET = 4 * 1024 * 1024;    private int $textBytes = 0;    /** @var array<string, array{0: mixed, 1: int, 2: int}|false> file => [texture, w, h] */    private array $files = [];    /** @var array<string, array{0: mixed, 1: int, 2: int}> */    private array $texts = [];    /** @var array<string, mixed> font file:px => TTF_Font */    private array $fonts = [];    /** @var array<string, true> texts the graphics card could not take */    private array $failed = [];    public function __construct(private mixed $renderer, private string $root)    {    }    /**     * A picture, drawn at $scale. A whole scale (x2, x3): its pixels as they are. A scale between two (x1.6 at 80 %):     * "sharp bilinear", as the emulators do: the picture made $k times bigger pixel for pixel (k = the whole scale above),     * then smoothed down to its size by the graphics card; with the nearest pixel only, a 1-pixel line was 1 or 2 pixels     * wide by turns: the texts drawn in the skins (MODE EDITION) looked smeared.     * @return array{0: mixed, 1: int, 2: int, 3: int}|null [texture, width, height (the picture's own), k (texture pixels per picture pixel)]     */    public function file(string $file, float $scale = 1.0): ?array    {        // the picture made N times bigger (nearest: crisp pixels), then the card makes it smaller to the scale. x2, x3: drawn        // as they are (k = 1, nearest); x1.5, x2.5: x3, x5 then exactly halved (the edges of the pixels fall right)        $k = match (true) {            $scale < 1 || abs($scale - round($scale)) < 0.01 => 1,            abs($scale * 2 - round($scale * 2)) < 0.01 => (int)round($scale * 2),            default => (int)ceil($scale),        };        $key = $k > 1 ? "$file@$k" : $file;        if (!array_key_exists($key, $this->files)) {            $this->files[$key] = false;            $surface = $k > 1 ? $this->sharpSurface($file, $k) : @\IMG_Load($file);            if ($surface) {                if ($k > 1) {                    \SDL_SetHint(\SDL_HINT_RENDER_SCALE_QUALITY, '1');      // smoothed when it is made smaller                }                $texture = \SDL_CreateTextureFromSurface($this->renderer, $surface);                if ($k > 1) {                    \SDL_SetHint(\SDL_HINT_RENDER_SCALE_QUALITY, '0');                }                $w = $h = 0;                if ($texture) {     // null: too big for the graphics card, or out of memory (not drawn)                    \SDL_QueryTexture($texture, $format, $access, $w, $h);                }                \SDL_FreeSurface($surface);                if ($texture && $w > 0 && $h > 0) {                    $this->files[$key] = [$texture, intdiv((int)$w, $k), intdiv((int)$h, $k), $k];                }            }        }        return $this->files[$key] ?: null;    }    /** The picture $k times bigger, pixel for pixel (GD), as an SDL surface. */    private function sharpSurface(string $file, int $k): mixed    {        if (!function_exists('imagecreatefromstring')) {            return @\IMG_Load($file);        }        $cache = sys_get_temp_dir() . '/winzik-sharp-' . md5($file . '|' . (string)@filemtime($file) . '|' . $k) . '.png';        if (!is_file($cache)) {            $im = @imagecreatefromstring((string)@file_get_contents($file));            if ($im === false) {                return @\IMG_Load($file);            }            imagepalettetotruecolor($im);            imagealphablending($im, false);            imagesavealpha($im, true);            $big = imagescale($im, imagesx($im) * $k, imagesy($im) * $k, IMG_NEAREST_NEIGHBOUR);            if ($big === false) {                return @\IMG_Load($file);            }            imagealphablending($big, false);            imagesavealpha($big, true);            imagepng($big, $cache, 1);        }        return @\IMG_Load($cache);    }    private string $frame = '';    /** A picture of a film: loaded once, the one before it forgotten (a film has thousands). @return array{0: mixed, 1: int, 2: int}|null */    public function frame(string $file): ?array    {        if ($this->frame !== $file) {            if ($this->frame !== '') {                $this->forget($this->frame);            }            $this->frame = $file;        }        return $this->file($file);    }    public function forget(string $file): void    {        foreach ($this->files as $key => $t) {            if ($key === $file || str_starts_with($key, $file . '@')) {                if ($t) {                    \SDL_DestroyTexture($t[0]);                }                unset($this->files[$key]);            }        }    }    private function font(string $file, int $px): mixed    {        $key = "$file:$px";        if (!isset($this->fonts[$key])) {            $path = rtrim($this->root, '/') . '/assets/fonts/' . $file;            $this->fonts[$key] = @\TTF_OpenFont($path, $px) ?: null; // @phpstan-ignore ternary.alwaysTrue (false when the file is missing)        }        return $this->fonts[$key];    }    /** A text SDL_ttf can render: bytes that are not UTF-8 (a tag in Latin-1) made the rendering fail. */    public static function clean(string $text): string    {        return mb_check_encoding($text, 'UTF-8') ? $text : mb_scrub($text, 'UTF-8');    }    /** @return array{0: int, 1: int} the size of a text in pixels */    public function measure(string $text, int $px, string $file): array    {        $text = self::clean($text);        $font = $this->font($file, $px);        if ($font === null || $text === '') {            return [(int)(mb_strlen($text) * $px * 0.55), $px];        }        $w = $h = 0;        \TTF_SizeUTF8($font, $text, $w, $h);        return [(int)$w, (int)$h];    }    /** @param array{0: int, 1: int, 2: int, 3?: int} $rgba @return array{0: mixed, 1: int, 2: int}|null */    public function text(string $text, int $px, array $rgba, string $file): ?array    {        $key = $file . '|' . $px . '|' . implode(',', $rgba) . '|' . $text;        if (isset($this->texts[$key])) {            // used again: the newest (the oldest unused go first)            $hit = $this->texts[$key];            unset($this->texts[$key]);            return $this->texts[$key] = $hit;        }        if (isset($this->failed[$key])) {            return null;        }        $font = $this->font($file, $px);        $text = self::clean($text);        if ($font === null || $text === '') {            return null;        }        $surface = @\TTF_RenderUTF8_Blended($font, $text, new \SDL_Color($rgba[0], $rgba[1], $rgba[2], $rgba[3] ?? 255));        if (!$surface) { // @phpstan-ignore booleanNot.alwaysFalse (false for a glyph the font lacks)            return null;        }        $texture = \SDL_CreateTextureFromSurface($this->renderer, $surface);        $w = $h = 0;        if ($texture) {            \SDL_QueryTexture($texture, $format, $access, $w, $h);        }        \SDL_FreeSurface($surface);        if (!$texture || $w <= 0 || $h <= 0) {            // wider than the biggest texture of the graphics card (a very long line at a big zoom): not drawn, and not            // tried again at every frame            if ($texture) {                \SDL_DestroyTexture($texture);            }            if (count($this->failed) > 100) {                $this->failed = [];            }            $this->failed[$key] = true;            return null;        }        // kept within a memory budget (4 MB of letters a window: a line of the lyrics on the whole screen weighs 360 KB,        // and gliding they came in many sizes), the least used ones go first        $this->textBytes += (int)$w * (int)$h * 4;        foreach ($this->texts as $old => [$t, $ow, $oh]) {            if ($this->textBytes <= self::TEXT_BUDGET && count($this->texts) < self::MAX_TEXTS) {                break;            }            \SDL_DestroyTexture($t);            unset($this->texts[$old]);            $this->textBytes -= $ow * $oh * 4;        }        return $this->texts[$key] = [$texture, (int)$w, (int)$h];    }    /** Everything freed (before its renderer is destroyed): the textures of the pictures and texts, the fonts. */    public function destroy(): void    {        foreach ($this->files as $t) {            if ($t) {                \SDL_DestroyTexture($t[0]);            }        }        foreach ($this->texts as [$t]) {            \SDL_DestroyTexture($t);        }        foreach ($this->fonts as $font) {            if ($font !== null && function_exists('TTF_CloseFont')) {                \TTF_CloseFont($font);            }        }        $this->files = $this->texts = $this->fonts = $this->failed = [];        $this->textBytes = 0;        $this->frame = '';    }}