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.1 KB
Raw Blame
#!/usr/bin/env python3
"""Builds src/assets.h from the files in ../assets (see extract_ti.py).

Sprites and tiles stay in the original 4 bits per pixel layout (two pixels
per byte, left pixel in the high nibble) with a (height, bytes per row)
header, so the drawing code works exactly like the original's.
Tiles, sprites, font, title art and both level packs (28 KB) are packed
into one DEFLATE stream (about 11 KB) that the game unpacks into RAM when
it starts (src/inflate.c)."""
import os
import zlib

from PIL import Image

HERE = os.path.dirname(os.path.abspath(__file__))
A = os.path.join(HERE, '..', 'assets')
OUT = os.path.join(HERE, '..', 'src', 'assets.h')


def nibbles(im, x0, y0, w, h):
    out = bytearray([h, w // 2])
    for y in range(h):
        for x in range(0, w, 2):
            out.append(im.getpixel((x0 + x, y0 + y)) << 4 | im.getpixel((x0 + x + 1, y0 + y)))
    return out


def carray(name, data, typ='uint8_t'):
    s = 'static const %s %s[%d] = {' % (typ, name, len(data))
    for i, v in enumerate(data):
        if i % 24 == 0:
            s += '\n  '
        s += '%d,' % v
    return s + '\n};\n'


def main():
    out = ['/* Generated by tools/gen_assets.py from assets/: do not edit. */\n',
           '#ifndef PORTAL_ASSETS_H\n#define PORTAL_ASSETS_H\n#include <stdint.h>\n']
    pal = [int(v, 16) for v in open(os.path.join(A, 'palette.txt')).read().split()]
    out.append(carray('PAL_DEFAULT', pal, 'uint16_t'))
    blob, parts = bytearray(), []

    def part(name, data):
        parts.append((name, len(blob), len(data)))
        blob.extend(data)

    tiles = Image.open(os.path.join(A, 'tiles.png'))
    t = bytearray()
    for i in range(31):
        t += nibbles(tiles, i * 16, 0, 16, 16)
    part('TILES', t)

    sheet = Image.open(os.path.join(A, 'sprites.png'))
    data, names = bytearray(), []
    for line in open(os.path.join(A, 'sprites.txt')):
        if line.startswith('#') or not line.strip():
            continue
        n, x, y, w, h = line.split()
        names.append((n, len(data)))
        data += nibbles(sheet, int(x), int(y), int(w), int(h))
    part('SPRITES', data)

    font = Image.open(os.path.join(A, 'font.png')).convert('1')
    f = bytearray()
    for c in range(font.width // 8):
        for y in range(8):
            b = 0
            for x in range(8):
                b = b << 1 | (1 if font.getpixel((c * 8 + x, y)) else 0)
            f.append(b)
    part('FONT', f)

    # title pictures: (h, bytes per row) header then 1 bpp rows, separated
    # by one empty column in title.png
    title = Image.open(os.path.join(A, 'title.png')).convert('1')
    widths = [48, 80, 80, 40]
    heights = [52, 34, 34, 34]
    tdata, x, offs = bytearray(), 0, []
    for w, h in zip(widths, heights):
        offs.append(len(tdata))
        tdata += bytes([h, w // 8])
        for yy in range(h):
            for bx in range(w // 8):
                b = 0
                for xx in range(8):
                    b = b << 1 | (1 if title.getpixel((x + bx * 8 + xx, yy)) else 0)
                tdata.append(b)
        x += w + 1
    part('TITLE', tdata)
    for name in ('main', 'prelude'):
        part('PACK_' + name.upper(), open(os.path.join(A, name + '.bin'), 'rb').read())

    try:
        import zopfli.zlib
        z = zopfli.zlib.compress(bytes(blob), numiterations=50)[2:-4]
    except ImportError:
        z = zlib.compress(bytes(blob), 9)[2:-4]
    assert zlib.decompress(z, -15) == bytes(blob)
    out.append('#define ASSETS_SIZE %d\n' % len(blob))
    out.append('extern uint8_t assets[ASSETS_SIZE];\n')
    for name, off, n in parts:
        out.append('#define %s (assets + %d)\n#define %s_SIZE %d\n' % (name, off, name, n))
    out.append('#define TILE_BYTES 130\n#define FONT_CHARS %d\n' % (font.width // 8))
    for n, off in names:
        out.append('#define S_%s (SPRITES + %d)\n' % (n, off))
    for i, o in enumerate(offs):
        out.append('#define TITLE_PIC%d (TITLE + %d)\n' % (i, o))
    out.append(carray('ASSETS_Z', z))
    out.append('#endif\n')
    open(OUT, 'w').write(''.join(out))
    print('wrote', OUT, 'assets', len(blob), 'packed', len(z))


if __name__ == '__main__':
    main()