Skip to content

Free games for graphing calculators: NumWorks, TI-Nspire CX, Casio fx-CG50 and soon TI-84 Plus CE. Balatro, Celeste, Hollow Knight, Minecraft and more.

4.9 KB
Raw Blame
#!/usr/bin/env python3
"""Rasterizes the launcher's fonts into launcher/src/font_data.c.

Glyphs come from Nunito (SIL Open Font License, see LICENSES/), rendered 4x
supersampled with the baseline on a pixel boundary and stored as 4-bit
coverage. Run it again only to change sizes or weights; the output is
committed.

With --extra, letters beyond ASCII follow (a language build's accents, from tools/lang.py): their
code points go in np_font_extra, in the order of their glyphs after the ASCII ones.

Usage: fontgen.py out.c [--extra 233,232,...]
"""
import hashlib
import sys
import urllib.request
from pathlib import Path

import numpy as np
from PIL import Image, ImageDraw, ImageFont

ROOT = Path(__file__).resolve().parent
CACHE = ROOT / ".fonts"
UP = 4
SOURCE = ("Nunito.ttf", "https://raw.githubusercontent.com/google/fonts/main/ofl/nunito/Nunito%5Bwght%5D.ttf",
          "bb55a5ca5c2042335b3991af27c4d0705d0ef41cac6164ac737fd8f2a1e85207")

# name, cap height in pixels, weight, extra letter spacing (1/4 px)
SPECS = [
    ("np_font_title", 15, 900, 0),
    ("np_font_body", 9, 800, 1),
    ("np_font_small", 7, 800, 2),
]
FIRST, LAST = 32, 126


def font_file():
    name, url, digest = SOURCE
    p = CACHE / name
    if not p.exists():
        CACHE.mkdir(exist_ok=True)
        data = urllib.request.urlopen(url).read()
        if hashlib.sha256(data).hexdigest() != digest:
            raise SystemExit("unexpected font data")
        p.write_bytes(data)
    return str(p)


def load(cap, weight):
    for size in range(6, 200):
        f = ImageFont.truetype(font_file(), size * UP)
        f.set_variation_by_axes([weight])
        bb = f.getbbox("H", anchor="ls")
        if -bb[1] >= cap * UP - UP // 2:
            return f
    raise SystemExit("size")


def glyph(f, ch, spacing):
    adv = (f.getlength(ch) + spacing) / UP
    bb = f.getbbox(ch, anchor="ls")
    if bb[2] <= bb[0] or bb[3] <= bb[1]:
        return None, round(adv)
    pad = 2 * UP
    x0 = pad - bb[0]
    y0 = pad - bb[1]
    x0 += (-x0) % UP
    y0 += (-y0) % UP
    w = x0 + bb[2] + pad
    h = y0 + bb[3] + pad
    w += (-w) % UP
    h += (-h) % UP
    im = Image.new("L", (w, h), 0)
    ImageDraw.Draw(im).text((x0, y0), ch, font=f, fill=255, anchor="ls")
    a = np.asarray(im).astype(np.float32) / 255
    a = a.reshape(h // UP, UP, w // UP, UP).mean(axis=(1, 3))
    q = np.clip(np.round(a * 15), 0, 15).astype(np.uint8)
    ys, xs = np.nonzero(q)
    if not len(ys):
        return None, round(adv)
    q = q[ys.min():ys.max() + 1, xs.min():xs.max() + 1]
    ox = xs.min() - x0 // UP
    oy = ys.min() - y0 // UP  # top relative to the baseline
    return (q, ox, oy), round(adv)


def main(out, extra=()):
    lines = ["/* Generated by tools/fontgen.py from Nunito (SIL Open Font License 1.1). */",
             '#include "font.h"', ""]
    extra = sorted(set(extra))
    lines.append(f"const uint16_t np_font_extra[{max(1, len(extra))}] = {{" + (", ".join(str(c) for c in extra) or "0") + "};")
    lines.append(f"const int np_font_extra_count = {len(extra)};")
    lines.append("")
    total = 0
    for name, cap, weight, spacing in SPECS:
        f = load(cap, weight)
        data = bytearray()
        glyphs = []
        asc = desc = 0
        for c in list(range(FIRST, LAST + 1)) + extra:
            g, adv = glyph(f, chr(c), spacing * UP / 4)
            if g is None:
                glyphs.append((0, 0, 0, 0, adv, len(data)))
                continue
            q, ox, oy = g
            h, w = q.shape
            if c <= LAST:  # (the line's metrics from ASCII: accents don't move the layout)
                asc = max(asc, -oy)
                desc = max(desc, h + oy)
            flat = q.flatten().tolist()
            if len(flat) % 2:
                flat.append(0)
            off = len(data)
            for i in range(0, len(flat), 2):
                data.append(flat[i] | flat[i + 1] << 4)
            glyphs.append((w, h, ox, oy, adv, off))
        total += len(data) + 7 * len(glyphs)
        lines.append(f"static const uint8_t {name}_data[{len(data)}] = {{")
        for i in range(0, len(data), 24):
            lines.append("  " + ",".join(str(b) for b in data[i:i + 24]) + ",")
        lines.append("};")
        lines.append(f"static const np_glyph_t {name}_glyphs[{len(glyphs)}] = {{")
        for w, h, ox, oy, adv, off in glyphs:
            lines.append(f"  {{{w}, {h}, {ox}, {oy}, {adv}, {off}}},")
        lines.append("};")
        lines.append(f"const np_font_t {name} = {{{FIRST}, {LAST - FIRST + 1 + len(extra)}, {asc}, {desc}, {name}_glyphs, {name}_data}};")
        lines.append("")
        print(f"{name}: cap {cap}px, ascent {asc}, descent {desc}, {len(data)} bytes of glyphs")
    Path(out).write_text("\n".join(lines))
    print(f"total {total} bytes")


if __name__ == "__main__":
    extra = []
    if "--extra" in sys.argv:
        v = sys.argv[sys.argv.index("--extra") + 1]
        extra = [int(c) for c in v.split(",") if c]
    main(sys.argv[1], extra)