IT
games/rob-revisited / src / Revisited / Ui / Canvas.php · commit f9a1307
<?phpnamespace App\Revisited\Ui;use App\Revisited\I18n\Translator;use JumPHP\Renderer\Renderer;use JumPHP\Renderer\Sdl;/** * The dashboard's drawing surface: drawn in a Renderer overlay, at the window's own resolution (after the 3D layer and * its post shader, so the HUD stays sharp and untouched by the vignette / hurt filter), placed in "units": the game view * (320 x 240) times 3, so the letterbox is 960 x 720 units whatever the window's size. * * Text: a TrueType font rendered at the real pixel size (cached textures). Icons: Icons pictograms, generated once per * pixel size. Hit regions: what draw code declares with hit() is what the next update() finds with hitAt() (the screens * are drawn after they are updated: one frame behind, invisible). * * Every text is translated when drawn (Translator::t(): the game is written in French) and FITTED in its box: the box * pushed with pushBox(), else the panel / pill drawn last under the text's anchor, else the screen. Too wide for it, a * text shrinks by 5 % steps down to 80 % (never under minPx), then its end is cut with "…" (cached: free per frame). */final class Canvas{    public const W = 960.0;    public const H = 720.0;    /** window pixels per unit */    public float $s = 1.0;    public int $ox = 0;    public int $oy = 0;    /** the letterbox's size in window pixels (begin()) */    private int $lw = 0;    private int $lh = 0;    /** the smallest text in real pixels (phones: bigger, readable) */    public int $minPx = 7;    /** test bench: draw as on a smaller screen (window pixels per unit), null = the window's own */    public ?float $forceScale = null;    /** phones: every text drawn this much bigger than asked (the layouts wrap and measure with it) */    public float $boost = 1.0;    private ?Renderer $r = null;    private int $frame = 0;    /** @var array<int, \TTF_Font> */    private array $fonts = [];    /** @var array<string, array{0: mixed, 1: int, 2: int, 3: int}> texture, w, h, last frame used */    private array $texts = [];    /** @var array<string, float> measured widths (units * size key) */    private array $widths = [];    /** @var array<string, mixed> icon textures by "id|px" */    private array $icons = [];    /** @var list<array{0: float, 1: float, 2: float, 3: float, 4: string}> */    private array $hits = [];    /** @var list<array{0: float, 1: float, 2: float, 3: float, 4: string}> */    private array $lastHits = [];    private bool $ttf = false;    private \SDL_Rect $dst;    /** test bench: when an array, every text drawn is appended (docs/i18n-plan.md "Overflow test")     *  @var list<array{text: string, full: string, x: float, w: float, box: array{0: float, 1: float, 2: float, 3: float}, auto: bool, cut: bool, scale: float}>|null */    public static ?array $record = null;    /** test bench: with $record on, every box() declared, with the panel it stands in (it must not stick out of it)     *  @var list<array{box: array{0: float, 1: float, 2: float, 3: float}, parent: array{0: float, 1: float, 2: float, 3: float}}> */    public static array $recordBoxes = [];    /** @var list<array{0: float, 1: float, 2: float, 3: float}> the panels / pills of this frame (the boxes texts fit in) */    private array $boxes = [];    /** @var list<array{0: float, 1: float, 2: float, 3: float}> boxes pushed by the layouts (pushBox / popBox) */    private array $stack = [];    /** @var array<string, array{0: string, 1: int, 2: bool}> fitted texts: "px|avail|text" => [what is drawn, its px, cut] */    private array $fits = [];    /** inner margin of a box (units) */    public const PAD = 4.0;    public function __construct(private string $fontPath, private Sdl $sdl)    {        $this->dst = new \SDL_Rect(0, 0, 0, 0);    }    /** Starts a frame of the overlay: where the view lands in the window, how big a unit is. */    public function begin(Renderer $r): void    {        $this->r = $r;        $this->frame++;        [$x, $y, $w, $h] = $r->letterbox();        if ($w <= 0 || $h <= 0) {            [$w, $h] = $r->outputSize();            $x = $y = 0;        }        $this->s = $this->forceScale ?? min($w / self::W, $h / self::H);        $this->ox = $x;        $this->oy = $y;        $this->lw = $w;        $this->lh = $h;        $this->hits = [];        $this->boxes = [];        $this->stack = [];        if (!$this->ttf && is_file($this->fontPath)) {            if (!\TTF_WasInit()) {                \TTF_Init();            }            $this->ttf = true;        }    }    public function end(): void    {        // what the next update() finds with hitAt(): the regions of this very frame (not the one before: a menu just        // opened would answer with the old menu's rows)        $this->lastHits = $this->hits;        if (count($this->texts) > 360) {            foreach ($this->texts as $k => $t) {                if ($this->frame - $t[3] > 90) {                    \SDL_DestroyTexture($t[0]);                    unset($this->texts[$k]);                }            }        }        if (count($this->widths) > 2000) {            $this->widths = [];        }        if (count($this->fits) > 1500) {            $this->fits = [];        }    }    public function dispose(): void    {        foreach ($this->texts as $t) {            \SDL_DestroyTexture($t[0]);        }        foreach ($this->fonts as $f) {            \TTF_CloseFont($f);        }        $this->texts = $this->fonts = $this->widths = [];        $this->icons = [];        $this->hits = $this->lastHits = [];    }    // ---- hit regions --------------------------------------------------------------------------------    public function hit(float $x, float $y, float $w, float $h, string $id): void    {        $this->hits[] = [$x, $y, $w, $h, $id];    }    /**     * A point of the game's view (the mouse, 0..$viewW) in units, as drawn: right at any window size, and on the test     * bench's smaller screen (forceScale) too.     * @return array{0: float, 1: float}     */    public function toUnits(float $vx, float $vy, int $viewW, int $viewH): array    {        if ($this->lw <= 0 || $this->lh <= 0 || $this->s <= 0) {            return [$vx * self::W / max(1, $viewW), $vy * self::H / max(1, $viewH)];        }        return [$vx * $this->lw / max(1, $viewW) / $this->s, $vy * $this->lh / max(1, $viewH) / $this->s];    }    /** The region under a point (units), drawn last on top: searched from the end. */    public function hitAt(float $x, float $y): ?string    {        for ($i = count($this->lastHits) - 1; $i >= 0; $i--) {            [$hx, $hy, $hw, $hh, $id] = $this->lastHits[$i];            if ($x >= $hx && $y >= $hy && $x < $hx + $hw && $y < $hy + $hh) {                return $id;            }        }        return null;    }    // ---- shapes ---------------------------------------------------------------------------------------    public function rect(float $x, float $y, float $w, float $h, array $c): void    {        $s = $this->s;        $x0 = (int) round($this->ox + $x * $s);        $y0 = (int) round($this->oy + $y * $s);        $this->r?->fillRect($x0, $y0, (int) round($this->ox + ($x + $w) * $s) - $x0, (int) round($this->oy + ($y + $h) * $s) - $y0, $c);    }    /** A 1-pixel outline (real pixels: hairlines at any size). */    public function border(float $x, float $y, float $w, float $h, array $c, int $px = 1): void    {        $s = $this->s;        $x0 = (int) round($this->ox + $x * $s);        $y0 = (int) round($this->oy + $y * $s);        $x1 = (int) round($this->ox + ($x + $w) * $s);        $y1 = (int) round($this->oy + ($y + $h) * $s);        $r = $this->r;        if ($r === null) {            return;        }        $r->fillRect($x0, $y0, $x1 - $x0, $px, $c);        $r->fillRect($x0, $y1 - $px, $x1 - $x0, $px, $c);        $r->fillRect($x0, $y0 + $px, $px, $y1 - $y0 - 2 * $px, $c);        $r->fillRect($x1 - $px, $y0 + $px, $px, $y1 - $y0 - 2 * $px, $c);    }    /** The glass look: a dark translucent fill, a lighter top band, a thin light border and a highlight line on top. */    public function panel(float $x, float $y, float $w, float $h, int $alpha = 170, ?array $accent = null): void    {        $this->boxes[] = [$x, $y, $w, $h];        $this->rect($x, $y, $w, $h, [12, 16, 22, $alpha]);        $this->rect($x, $y, $w, min($h * 0.45, 40), [255, 255, 255, 10]);        $this->border($x, $y, $w, $h, [190, 210, 230, 46]);        $this->rect($x + 1 / $this->s, $y + 1 / $this->s, $w - 2 / $this->s, 1 / $this->s, [255, 255, 255, 54]);        if ($accent !== null) {            $this->rect($x, $y, 3, $h, $accent);        }    }    /** A rounded-looking pill (a rectangle with the corners cut by a pixel). */    public function pill(float $x, float $y, float $w, float $h, array $c): void    {        $this->boxes[] = [$x, $y, $w, $h];        $p = 1 / $this->s;        $this->rect($x + $p, $y, $w - 2 * $p, $h, $c);        $this->rect($x, $y + $p, $p, $h - 2 * $p, $c);        $this->rect($x + $w - $p, $y + $p, $p, $h - 2 * $p, $c);    }    public function line(float $x1, float $y1, float $x2, float $y2, array $c, float $thick = 1.0): void    {        $r = $this->r;        if ($r === null) {            return;        }        $s = $this->s;        $ax = $this->ox + $x1 * $s;        $ay = $this->oy + $y1 * $s;        $bx = $this->ox + $x2 * $s;        $by = $this->oy + $y2 * $s;        $t = max(1, (int) round($thick * $s));        if ($t <= 1) {            $r->drawLine($ax, $ay, $bx, $by, $c);            return;        }        $len = hypot($bx - $ax, $by - $ay);        if ($len < 0.5) {            return;        }        $nx = -($by - $ay) / $len;        $ny = ($bx - $ax) / $len;        for ($k = 0; $k < $t; $k++) {            $o = $k - ($t - 1) / 2;            $r->drawLine($ax + $nx * $o, $ay + $ny * $o, $bx + $nx * $o, $by + $ny * $o, $c);        }    }    public function circle(float $cx, float $cy, float $radius, array $c): void    {        $this->r?->fillCircle($this->ox + $cx * $this->s, $this->oy + $cy * $this->s, max(1.0, $radius * $this->s), $c);    }    /** A filled triangle (scanlines): markers, arrows. */    public function triangle(float $x1, float $y1, float $x2, float $y2, float $x3, float $y3, array $c): void    {        $r = $this->r;        if ($r === null) {            return;        }        $s = $this->s;        $p = [[$this->ox + $x1 * $s, $this->oy + $y1 * $s], [$this->ox + $x2 * $s, $this->oy + $y2 * $s], [$this->ox + $x3 * $s, $this->oy + $y3 * $s]];        usort($p, static fn ($a, $b) => $a[1] <=> $b[1]);        [[$ax, $ay], [$bx, $by], [$qx, $qy]] = $p;        $y0 = (int) ceil($ay);        $y1 = (int) floor($qy);        for ($y = $y0; $y <= $y1; $y++) {            $xa = $qy - $ay > 0 ? $ax + ($qx - $ax) * ($y - $ay) / ($qy - $ay) : $ax;            $xb = $y < $by                ? ($by - $ay > 0 ? $ax + ($bx - $ax) * ($y - $ay) / ($by - $ay) : $bx)                : ($qy - $by > 0 ? $bx + ($qx - $bx) * ($y - $by) / ($qy - $by) : $bx);            if ($xa > $xb) {                [$xa, $xb] = [$xb, $xa];            }            $r->fillRect($xa, $y, max(1.0, $xb - $xa), 1, $c);        }    }    /** Draws a texture into a box of units. */    public function image(mixed $texture, float $x, float $y, float $w, float $h): void    {        $s = $this->s;        $this->r?->copy($texture, null, $this->ox + $x * $s, $this->oy + $y * $s, $w * $s, $h * $s);    }    /** An item / vital pictogram (Icons), generated at the pixel size it is shown at. */    public function icon(string $id, float $x, float $y, float $size): void    {        $px = max(8, (int) round($size * $this->s));        $key = "$id|$px";        if (!array_key_exists($key, $this->icons)) {            $this->icons[$key] = null;            try {                $name = 'rv_icon_' . preg_replace('/[^a-z0-9_]/', '_', $id) . "_$px";                $slices = $this->sdl->createTextureFromGd($name, Icons::image($id, $px));                $this->icons[$key] = $slices[0]['texture'] ?? null;            } catch (\Throwable) {                $this->icons[$key] = null;            }        }        $t = $this->icons[$key];        if ($t === null || $this->r === null) {            return;        }        $this->dst->x = (int) round($this->ox + $x * $this->s);        $this->dst->y = (int) round($this->oy + $y * $this->s);        $this->dst->w = $px;        $this->dst->h = $px;        \SDL_RenderCopy($this->r->getRenderer(), $t, null, $this->dst);    }    // ---- boxes ----------------------------------------------------------------------------------------    /** Declares a box texts anchored in it fit in (a row, a column of a table), without drawing anything. */    public function box(float $x, float $y, float $w, float $h): void    {        if (self::$record !== null) {            self::$recordBoxes[] = ['box' => [$x, $y, $w, $h], 'parent' => $this->boxAt($x + 0.5, $y + 0.5)[0]];        }        $this->boxes[] = [$x, $y, $w, $h];    }    /** The texts drawn until popBox() fit in this box, wherever they are anchored (a menu row's label column). */    public function pushBox(float $x, float $y, float $w, float $h): void    {        $this->stack[] = [$x, $y, $w, $h];    }    public function popBox(): void    {        array_pop($this->stack);    }    /**     * The box a text anchored at (x, y) fits in: the one pushed, else the panel / pill / box drawn last that holds the     * point, else the screen.     * @return array{0: array{0: float, 1: float, 2: float, 3: float}, 1: bool} the box, true when found by the anchor     */    private function boxAt(float $x, float $y): array    {        if ($this->stack !== []) {            return [$this->stack[count($this->stack) - 1], false];        }        for ($i = count($this->boxes) - 1; $i >= 0; $i--) {            [$bx, $by, $bw, $bh] = $this->boxes[$i];            if ($x >= $bx && $x <= $bx + $bw && $y >= $by && $y <= $by + $bh) {                return [$this->boxes[$i], true];            }        }        return [[0.0, 0.0, self::W, self::H], true];    }    /** How wide a text anchored at $x with $align may be in a box. */    private static function room(array $box, float $x, string $align): float    {        $left = $box[0] + self::PAD;        $right = $box[0] + $box[2] - self::PAD;        return max(0.0, match ($align) {            'center' => 2 * min($x - $left, $right - $x),            'right' => $x - $left,            default => $right - $x,        });    }    // ---- text -----------------------------------------------------------------------------------------    /**     * A line of text: $y its top, $size its height in units, $align left | center | right. Returns its width (units).     * $shadow: a dark copy one pixel below (readable over the 3D). Translated, then fitted in its box (see the class).     */    public function text(string $text, float $x, float $y, float $size, array $c, string $align = 'left', bool $shadow = true): float    {        if ($text === '' || $this->r === null || !$this->ttf) {            return 0.0;        }        $text = Translator::t($text);        $px0 = max($this->minPx, (int) round($size * $this->s * $this->boost));        [$box, $auto] = $this->boxAt($x, $y + $size * 0.5);        $room = self::room($box, $x, $align);        [$shown, $px, $cut] = $this->fitLine($text, $px0, $room);        $t = $this->texture($shown, $px, $c);        if ($t === null) {            return 0.0;        }        $wx = $this->ox + $x * $this->s;        if ($align === 'center') {            $wx -= $t[1] / 2;        } elseif ($align === 'right') {            $wx -= $t[1];        }        if (self::$record !== null) {            self::$record[] = ['text' => $shown, 'full' => $text, 'x' => ($wx - $this->ox) / $this->s, 'w' => $t[1] / $this->s,                'box' => $box, 'auto' => $auto, 'cut' => $cut, 'scale' => $px / max(1, $px0)];        }        $wy = $this->oy + $y * $this->s - $px * 0.12 + ($px0 - $px) * 0.5;        $sdl = $this->r->getRenderer();        $dst = $this->dst;        if ($shadow) {            $sh = $this->texture($shown, $px, [0, 0, 0]);            if ($sh !== null) {                $o = max(1, (int) round($px / 14));                $dst->x = (int) round($wx) + $o;                $dst->y = (int) round($wy) + $o;                $dst->w = $sh[1];                $dst->h = $sh[2];                \SDL_RenderCopy($sdl, $sh[0], null, $dst);            }        }        $dst->x = (int) round($wx);        $dst->y = (int) round($wy);        $dst->w = $t[1];        $dst->h = $t[2];        \SDL_RenderCopy($sdl, $t[0], null, $dst);        return $t[1] / $this->s;    }    /**     * A text that fits $room units at $px pixels: as it is, else smaller (5 % steps down to 80 %, never under minPx),     * else cut with "…".     * @return array{0: string, 1: int, 2: bool} what to draw, its pixel size, cut     */    private function fitLine(string $text, int $px0, float $room): array    {        $roomPx = (int) floor($room * $this->s + 0.5);        $key = $px0 . '|' . $roomPx . '|' . $text;        if (isset($this->fits[$key])) {            return $this->fits[$key];        }        $fit = [$text, $px0, false];        if ($this->widthPx($text, $px0) > $roomPx) {            $fit = null;            for ($k = 0.95; $k >= 0.799; $k -= 0.05) {                $px = max($this->minPx, (int) round($px0 * $k));                if ($px >= $px0) {                    continue;                }                if ($this->widthPx($text, $px) <= $roomPx) {                    $fit = [$text, $px, false];                    break;                }            }            if ($fit === null) {                $px = max($this->minPx, min($px0, (int) round($px0 * 0.8)));                $chars = mb_str_split(rtrim($text));                $lo = 0;                $hi = count($chars);                while ($lo < $hi) {                    $mid = intdiv($lo + $hi + 1, 2);                    if ($this->widthPx(rtrim(implode('', array_slice($chars, 0, $mid))) . '…', $px) <= $roomPx) {                        $lo = $mid;                    } else {                        $hi = $mid - 1;                    }                }                $fit = [$lo > 0 ? rtrim(implode('', array_slice($chars, 0, $lo))) . '…' : '…', $px, true];            }        }        if (count($this->fits) > 3000) {            $this->fits = [];        }        return $this->fits[$key] = $fit;    }    /** Width of a text in real pixels at a pixel size. */    private function widthPx(string $text, int $px): int    {        if (!$this->ttf) {            return (int) ceil(mb_strlen($text) * $px * 0.55);        }        $w = $h = 0;        \TTF_SizeUTF8($this->font($px), $text, $w, $h);        return (int) $w;    }    /** The height of a line of text of $size (the phone's boost and the smallest pixel size count), times $k. */    public function lineH(float $size, float $k = 1.3): float    {        return max($size * $this->boost, $this->minPx / max(0.01, $this->s)) * $k;    }    /** Width of a text in units (translated: what is drawn). */    public function measure(string $text, float $size): float    {        $text = Translator::t($text);        if ($text === '' || !$this->ttf) {            return mb_strlen($text) * $size * 0.55;        }        $px = max($this->minPx, (int) round($size * $this->s * $this->boost));        $key = "$px|$text";        if (isset($this->widths[$key])) {            return $this->widths[$key];        }        return $this->widths[$key] = $this->widthPx($text, $px) / $this->s;    }    /** @return list<string> the text (translated) cut in lines no wider than $maxW units (words kept whole) */    public function wrap(string $text, float $size, float $maxW): array    {        $text = Translator::t($text);        $out = [];        foreach (explode("\n", $text) as $para) {            $line = '';            foreach (explode(' ', $para) as $word) {                $try = $line === '' ? $word : "$line $word";                if ($line !== '' && $this->measure($try, $size) > $maxW) {                    $out[] = Translator::keep($line);                    $line = $word;                } else {                    $line = $try;                }            }            $out[] = Translator::keep($line);        }        return $out;    }    /**     * Fits a text in $maxW units: wrapped in at most $maxLines lines, else smaller (5 % steps down to $minScale), else     * the last line cut with "…".     * @return array{lines: list<string>, size: float}     */    public function fit(string $text, float $size, float $maxW, int $maxLines = 1, float $minScale = 0.8): array    {        $text = Translator::t($text);        $key = 'fit|' . $size . '|' . (int) round($maxW * $this->s) . '|' . $maxLines . '|' . $minScale . '|' . $this->boost . '|' . $text;        if (isset($this->fits[$key])) {            return ['lines' => explode("\n", $this->fits[$key][0]), 'size' => $this->fits[$key][1] / 1000];        }        $lines = [];        $use = $size;        for ($k = 1.0; $k >= $minScale - 0.001; $k -= 0.05) {            $use = $size * $k;            $lines = $this->wrap($text, $use, $maxW);            if (count($lines) <= $maxLines && max(array_map(fn ($l) => $this->measure($l, $use), $lines)) <= $maxW) {                break;            }        }        if (count($lines) > $maxLines) {            $keep = array_slice($lines, 0, $maxLines);            $keep[$maxLines - 1] .= ' ' . implode(' ', array_slice($lines, $maxLines));            $lines = $keep;        }        $last = $lines[count($lines) - 1];        if ($this->measure($last, $use) > $maxW) {            $chars = mb_str_split($last);            while ($chars !== [] && $this->measure(rtrim(implode('', $chars)) . '…', $use) > $maxW) {                array_pop($chars);            }            $lines[count($lines) - 1] = Translator::keep(rtrim(implode('', $chars)) . '…');        }        $this->fits[$key] = [implode("\n", $lines), (int) round($use * 1000), false];        return ['lines' => $lines, 'size' => $use];    }    /**     * Draws a fitted text in a box ($x, $y top-left, $w wide; $align left | center | right inside it): wrapped in at most     * $maxLines lines, smaller or cut when needed. Returns the height used (units).     */    public function textBox(string $text, float $x, float $y, float $w, float $size, array $c, string $align = 'left', int $maxLines = 1, float $lineH = 1.25, bool $shadow = true): float    {        if ($text === '') {            return 0.0;        }        $f = $this->fit($text, $size, $w - 2 * self::PAD, $maxLines);        $lh = $f['size'] * $lineH * $this->boost;        $ax = match ($align) {            'center' => $x + $w / 2,            'right' => $x + $w - self::PAD,            default => $x + self::PAD,        };        $this->pushBox($x, $y, $w, max($lh * count($f['lines']), $size));        foreach ($f['lines'] as $i => $line) {            $this->text($line, $ax, $y + $i * $lh, $f['size'], $c, $align, $shadow);        }        $this->popBox();        return $lh * count($f['lines']);    }    private function font(int $px): \TTF_Font    {        return $this->fonts[$px] ??= \TTF_OpenFont($this->fontPath, $px);    }    /** @return array{0: mixed, 1: int, 2: int, 3: int}|null */    private function texture(string $text, int $px, array $c): ?array    {        $key = $px . '|' . $c[0] . ',' . $c[1] . ',' . $c[2] . '|' . $text;        if (isset($this->texts[$key])) {            $this->texts[$key][3] = $this->frame;            return $this->texts[$key];        }        $surface = \TTF_RenderUTF8_Blended($this->font($px), $text, new \SDL_Color((int) $c[0], (int) $c[1], (int) $c[2], 255));        if (!$surface) { // @phpstan-ignore booleanNot.alwaysFalse (the binding returns false on failure)            return null;        }        $texture = \SDL_CreateTextureFromSurface($this->r?->getRenderer(), $surface);        $t = [$texture, (int) $surface->w, (int) $surface->h, $this->frame];        \SDL_FreeSurface($surface);        return $this->texts[$key] = $t;    }}