text, x, y, size (view px), colour, align */ private array $lines = []; private ?int $overlay = null; private ?Renderer $renderer = null; /** @var array */ private array $fonts = []; /** @var array */ private array $textures = []; public function __construct(private string $fontPath) { } public function attach(Renderer $renderer): void { if ($this->overlay !== null || !is_file($this->fontPath)) { return; } if (!\TTF_WasInit()) { \TTF_Init(); } $this->renderer = $renderer; $this->overlay = $renderer->addOverlay(fn (Renderer $r) => $this->draw($r)); } public function detach(): void { if ($this->overlay !== null) { $this->renderer?->removeOverlay($this->overlay); $this->overlay = null; } foreach ($this->textures as $t) { \SDL_DestroyTexture($t[0]); } foreach ($this->fonts as $f) { \TTF_CloseFont($f); } $this->textures = $this->fonts = []; } /** A line for the next frame: $size = its height in view pixels, $align left | center. */ public function show(string $text, float $x, float $y, float $size, array $colour, string $align = 'left'): void { foreach (explode("\n", $text) as $i => $line) { $this->lines[] = [$line, $x, $y + $i * $size * 1.25, $size, $colour, $align]; } } private function draw(Renderer $r): void { $lines = $this->lines; $this->lines = []; if ($lines === []) { return; } [$lx, $ly, $lw, $lh] = $r->letterbox(); $sx = $lw / max(1, $r->getWidth()); $sy = $lh / max(1, $r->getHeight()); $sdl = $r->getRenderer(); foreach ($lines as [$text, $x, $y, $size, $colour, $align]) { if ($text === '') { continue; } $px = max(8, (int) round($size * $sy)); $shadow = max(1, (int) round($px / 12)); foreach ([[[0, 0, 0], $shadow], [$colour, 0]] as [$c, $off]) { $t = $this->texture($sdl, $text, $px, $c); if ($t === null) { continue 2; } $wx = $lx + $x * $sx - ($align === 'center' ? $t[1] / 2 : 0); \SDL_RenderCopy($sdl, $t[0], null, new \SDL_Rect((int) round($wx + $off), (int) round($ly + $y * $sy + $off), $t[1], $t[2])); } } } /** @return array{0: mixed, 1: int, 2: int}|null */ private function texture(mixed $sdl, string $text, int $px, array $c): ?array { $key = "$px|" . implode(',', $c) . "|$text"; if (isset($this->textures[$key])) { return $this->textures[$key]; } $font = $this->fonts[$px] ??= \TTF_OpenFont($this->fontPath, $px); $surface = \TTF_RenderUTF8_Blended($font, $text, new \SDL_Color($c[0], $c[1], $c[2], 255)); if (!$surface) { // @phpstan-ignore booleanNot.alwaysFalse (the binding returns false on failure) return null; } $texture = \SDL_CreateTextureFromSurface($sdl, $surface); $t = [$texture, (int) $surface->w, (int) $surface->h]; \SDL_FreeSurface($surface); if (count($this->textures) > 64) { foreach ($this->textures as $old) { \SDL_DestroyTexture($old[0]); } $this->textures = []; } return $this->textures[$key] = $t; } }