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.

5.3 KB
Raw Blame
"""Generate anti-aliased 2 bpp bitmap fonts (Baloo 2 ExtraBold, the typeface used by Fancade)
and a few UI icons as src/font.c.

usage: font.py path/to/baloo2.woff ../src/font.c"""
import sys
from PIL import Image, ImageDraw, ImageFont

SS = 4  # supersampling factor

FONTS = [
    # name, pixel size, characters
    ('font_s', 11, ''.join(chr(c) for c in range(32, 127))),
    ('font_m', 14, ''.join(chr(c) for c in range(32, 127))),
    ('font_l', 20, ' .0123456789:DGLMTadegilmnorstv'),
]


def quant(im):
    """downsample an L image by SS and quantise to 2 bits"""
    w, h = im.size
    im = im.resize((w // SS, h // SS), Image.BOX)
    w, h = im.size
    b = im.tobytes()
    return [[(b[y * w + x] * 3 + 127) // 255 for x in range(w)] for y in range(h)]


def glyph_record(rows):
    """trim to the ink box; returns (xoff, y0, w, h, packed bytes)"""
    H = len(rows)
    W = len(rows[0]) if H else 0
    ys = [y for y in range(H) if any(rows[y])]
    xs = [x for x in range(W) if any(rows[y][x] for y in range(H))]
    if not ys:
        return 0, 0, 0, 0, b''
    x0, x1, y0, y1 = xs[0], xs[-1] + 1, ys[0], ys[-1] + 1
    bits = []
    for y in range(y0, y1):
        bits += rows[y][x0:x1]
    out = bytearray()
    for i in range(0, len(bits), 4):
        q = bits[i:i + 4] + [0] * (4 - len(bits[i:i + 4]))
        out.append(q[0] | q[1] << 2 | q[2] << 4 | q[3] << 6)
    return x0, y0, x1 - x0, y1 - y0, bytes(out)


def build_font(path, size, chars):
    f = ImageFont.truetype(path, size * SS)
    asc, desc = f.getmetrics()
    H = (asc + desc) // SS + 1
    recs = []
    for ch in chars:
        adv = round(f.getlength(ch) / SS)
        W = adv + 4
        im = Image.new('L', (W * SS, H * SS), 0)
        ImageDraw.Draw(im).text((SS, 0), ch, font=f, fill=255)
        x0, y0, w, h, data = glyph_record(quant(im))
        recs.append((ch, adv, x0 - 1, y0, w, h, data))
    # vertical metrics: baseline and cap height for layout
    cap = f.getbbox('H')
    return dict(h=H, base=asc // SS, cap_top=cap[1] // SS, recs=recs)


def icon(draw_fn, w, h):
    im = Image.new('L', (w * SS, h * SS), 0)
    draw_fn(ImageDraw.Draw(im), SS)
    rows = quant(im)
    return glyph_record(rows)


def rr(d, box, r, fill=255, outline=None, width=0):
    d.rounded_rectangle(box, r, fill=fill, outline=outline, width=width)


ICONS = {
    # pause: two rounded pills with dark outline (drawn as two layers: outline + fill)
    'ic_pause_o': (lambda d, s: (rr(d, (0, 0, 7 * s, 16 * s), 3.5 * s), rr(d, (7 * s, 0, 14 * s, 16 * s), 3.5 * s)), 15, 17),
    'ic_pause_f': (lambda d, s: (rr(d, (1.2 * s, 1.2 * s, 5.8 * s, 14.8 * s), 2.3 * s),
                                 rr(d, (8.2 * s, 1.2 * s, 12.8 * s, 14.8 * s), 2.3 * s)), 15, 17),
    'ic_play': (lambda d, s: d.polygon([(1 * s, 0), (13 * s, 7 * s), (1 * s, 14 * s)], fill=255), 14, 15),
    'ic_restart': (lambda d, s: (d.arc((1 * s, 1 * s, 13 * s, 13 * s), 300, 250, fill=255, width=int(2.4 * s)),
                                 d.polygon([(5 * s, -0.5 * s), (10.5 * s, 2.2 * s), (5 * s, 6.0 * s)], fill=255)), 14, 14),
    'ic_back': (lambda d, s: d.line([(8 * s, 1 * s), (2 * s, 8 * s), (8 * s, 15 * s)], fill=255, width=int(2.6 * s), joint='curve'), 10, 17),
    'ic_next': (lambda d, s: d.line([(2 * s, 1 * s), (8 * s, 8 * s), (2 * s, 15 * s)], fill=255, width=int(2.6 * s), joint='curve'), 10, 17),
    'ic_left': (lambda d, s: d.polygon([(0.5 * s, 3 * s), (5.5 * s, 0), (5.5 * s, 6 * s)], fill=255), 6, 6),
    'ic_right': (lambda d, s: d.polygon([(5.5 * s, 3 * s), (0.5 * s, 0), (0.5 * s, 6 * s)], fill=255), 6, 6),
    'ic_lock': (lambda d, s: (d.arc((2 * s, 0, 8 * s, 8 * s), 180, 360, fill=255, width=int(1.6 * s)),
                              rr(d, (0.5 * s, 4 * s, 9.5 * s, 11 * s), 1.5 * s)), 10, 11),
}


def c_bytes(b):
    return ','.join(str(x) for x in b)


def main():
    src, out = sys.argv[1], sys.argv[2]
    lines = ['/* generated by tools/font.py from Baloo 2 ExtraBold (SIL Open Font License) */',
             '#include "font.h"', '']
    for name, size, chars in FONTS:
        F = build_font(src, size, chars)
        data = bytearray()
        glyphs = []
        for ch, adv, xo, y0, w, h, bits in F['recs']:
            glyphs.append((ord(ch), adv, xo, y0, w, h, len(data)))
            data += bits
        lines.append('static const uint8_t %s_data[] = {%s};' % (name, c_bytes(data)))
        lines.append('static const Glyph %s_glyphs[] = {' % name)
        for c, adv, xo, y0, w, h, off in glyphs:
            lines.append('  {%d, %d, %d, %d, %d, %d, %d},' % (c, adv, xo, y0, w, h, off))
        lines.append('};')
        lines.append('const Font %s = {%d, %d, %d, %d, %s_glyphs, %s_data};' % (
            name, F['h'], F['base'], F['cap_top'], len(glyphs), name, name))
        lines.append('')
        print(name, 'glyph bytes', len(data), 'glyphs', len(glyphs), file=sys.stderr)
    for name, (fn, w, h) in ICONS.items():
        xo, y0, gw, gh, bits = icon(fn, w, h)
        lines.append('static const uint8_t %s_data[] = {%s};' % (name, c_bytes(bits)))
        lines.append('const Icon %s = {%d, %d, %d, %d, %d, %d, %s_data};' % (name, w, h, xo, y0, gw, gh, name))
    open(out, 'w').write('\n'.join(lines) + '\n')
    hdr = ['extern const Font %s;' % n for n, _, _ in FONTS] + ['extern const Icon %s;' % n for n in ICONS]
    print('\n'.join(hdr))


if __name__ == '__main__':
    main()