106 lines
5.5 KiB
Python
106 lines
5.5 KiB
Python
# BMFont fixtures (tools/fixtures.py): a bitmap font rendered from Karla-Regular (imgui-luau fonts, or DejaVu Sans
|
|
# from nixpkgs when missing) with FreeType + Pillow, written by an independent Python writer of the three AngelCode
|
|
# encodings (text, XML, binary v3) from the BMFont documentation, plus its page PNG.
|
|
# tests/gen/bmfont.luau { text, xml, binary, page (png bytes), desc = { info, common, pages, chars, kernings },
|
|
# crops = { { id, crc } } (CRC-32 of each glyph's alpha crop) }
|
|
import base64, json, os, subprocess
|
|
|
|
FONT = os.path.join(os.environ.get("IMGUI_FONTS", os.path.expanduser("~/dev/luau/imgui/imgui-luau/fonts")), "Karla-Regular.ttf")
|
|
|
|
CODE = r'''
|
|
import base64, io, json, struct, sys, zlib
|
|
import freetype
|
|
from PIL import Image
|
|
data = base64.b64decode(sys.stdin.read())
|
|
face = freetype.Face(io.BytesIO(data))
|
|
face.set_pixel_sizes(0, 24)
|
|
chars = [c for c in range(32, 127)] + [0xE9, 0x2014]
|
|
page = Image.new("RGBA", (256, 256), (255, 255, 255, 0))
|
|
x, y, rowh = 1, 1, 0
|
|
out = []
|
|
crops = []
|
|
for cp in chars:
|
|
face.load_char(chr(cp), freetype.FT_LOAD_RENDER | freetype.FT_LOAD_NO_HINTING)
|
|
g = face.glyph
|
|
bm = g.bitmap
|
|
w, h = bm.width, bm.rows
|
|
if x + w + 1 > 256:
|
|
x, y, rowh = 1, y + rowh + 1, 0
|
|
alpha = bytes(bm.buffer[r * bm.pitch + c] for r in range(h) for c in range(w))
|
|
for r in range(h):
|
|
for c in range(w):
|
|
page.putpixel((x + c, y + r), (255, 255, 255, alpha[r * w + c]))
|
|
out.append({"id": cp, "x": x, "y": y, "width": w, "height": h, "xoffset": g.bitmap_left,
|
|
"yoffset": 19 - g.bitmap_top, "xadvance": g.advance.x // 64, "page": 0, "chnl": 15})
|
|
crops.append({"id": cp, "crc": zlib.crc32(alpha)})
|
|
x += w + 1
|
|
rowh = max(rowh, h)
|
|
kern = []
|
|
for a in "AVTWYLo":
|
|
for b in "AVTWYoe.":
|
|
k = face.get_kerning(a, b).x // 64
|
|
kern.append([ord(a), ord(b), -((ord(a) * 7 + ord(b)) % 5) - 1])
|
|
info = {"face": "Karla \"Test\" & Co", "size": 24, "bold": 0, "italic": 1, "charset": "", "unicode": 1, "stretchH": 100,
|
|
"smooth": 1, "aa": 1, "padding": [1, 2, 3, 4], "spacing": [1, 1], "outline": 0}
|
|
common = {"lineHeight": 28, "base": 19, "scaleW": 256, "scaleH": 256, "pages": 1, "packed": 0, "alphaChnl": 0,
|
|
"redChnl": 4, "greenChnl": 4, "blueChnl": 4}
|
|
pages = ["karla_0.png"]
|
|
CHAR_KEYS = ["id", "x", "y", "width", "height", "xoffset", "yoffset", "xadvance", "page", "chnl"]
|
|
def tq(s): return '"' + s.replace('"', "") + '"'
|
|
lines = ["info face=%s size=24 bold=0 italic=1 charset=\"\" unicode=1 stretchH=100 smooth=1 aa=1 padding=1,2,3,4 spacing=1,1 outline=0" % tq(info["face"]),
|
|
"common lineHeight=28 base=19 scaleW=256 scaleH=256 pages=1 packed=0 alphaChnl=0 redChnl=4 greenChnl=4 blueChnl=4",
|
|
'page id=0 file="karla_0.png"', "chars count=%d" % len(out)]
|
|
for c in out:
|
|
lines.append("char " + " ".join("%s=%d" % (k, c[k]) for k in CHAR_KEYS))
|
|
lines.append("kernings count=%d" % len(kern))
|
|
for k in kern:
|
|
lines.append("kerning first=%d second=%d amount=%d" % tuple(k))
|
|
text = "\r\n".join(lines) + "\r\n"
|
|
def xe(s): return s.replace("&", "&").replace("<", "<").replace('"', """)
|
|
xl = ['<?xml version="1.0"?>', "<font>",
|
|
' <info face="%s" size="24" bold="0" italic="1" charset="" unicode="1" stretchH="100" smooth="1" aa="1" padding="1,2,3,4" spacing="1,1" outline="0"/>' % xe(info["face"]),
|
|
' <common lineHeight="28" base="19" scaleW="256" scaleH="256" pages="1" packed="0" alphaChnl="0" redChnl="4" greenChnl="4" blueChnl="4"/>',
|
|
" <pages>", ' <page id="0" file="karla_0.png" />', " </pages>", ' <chars count="%d">' % len(out)]
|
|
for c in out:
|
|
xl.append(" <char " + " ".join('%s="%d"' % (k, c[k]) for k in CHAR_KEYS) + " />")
|
|
xl.append(" </chars>")
|
|
xl.append(' <kernings count="%d">' % len(kern))
|
|
for k in kern:
|
|
xl.append(' <kerning first="%d" second="%d" amount="%d" />' % tuple(k))
|
|
xl += [" </kernings>", "</font>"]
|
|
xml = "\n".join(xl) + "\n"
|
|
face_name = info["face"].encode()
|
|
b = bytearray(b"BMF\x03")
|
|
blk = struct.pack("<hBBHBBBBBBBB", 24, 0x80 | 0x40 | 0x20, 0, 100, 1, 1, 2, 3, 4, 1, 1, 0) + face_name + b"\0"
|
|
b += struct.pack("<BI", 1, len(blk)) + blk
|
|
blk = struct.pack("<HHHHHBBBBB", 28, 19, 256, 256, 1, 0, 0, 4, 4, 4)
|
|
b += struct.pack("<BI", 2, len(blk)) + blk
|
|
blk = b"karla_0.png\0"
|
|
b += struct.pack("<BI", 3, len(blk)) + blk
|
|
blk = b"".join(struct.pack("<IHHHHhhhBB", *[c[k] for k in CHAR_KEYS]) for c in out)
|
|
b += struct.pack("<BI", 4, len(blk)) + blk
|
|
blk = b"".join(struct.pack("<IIh", *k) for k in kern)
|
|
b += struct.pack("<BI", 5, len(blk)) + blk
|
|
png = io.BytesIO()
|
|
page.save(png, "PNG")
|
|
json.dump({"text": base64.b64encode(text.encode()).decode(), "xml": base64.b64encode(xml.encode()).decode(),
|
|
"binary": base64.b64encode(bytes(b)).decode(), "page": base64.b64encode(png.getvalue()).decode(),
|
|
"desc": {"info": info, "common": common, "pages": pages, "chars": out, "kernings": kern}, "crops": crops},
|
|
sys.stdout)
|
|
'''
|
|
|
|
|
|
def generate(ctx):
|
|
path = FONT
|
|
if not os.path.exists(path):
|
|
out = subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "nixpkgs#dejavu_fonts"], capture_output=True,
|
|
check=True, text=True).stdout.strip().split("\n")[-1]
|
|
path = os.path.join(out, "share", "fonts", "truetype", "DejaVuSans.ttf")
|
|
raw = ctx.python(["freetype-py", "pillow"], CODE, input=base64.b64encode(open(path, "rb").read()))
|
|
res = json.loads(raw)
|
|
d = base64.b64decode
|
|
for k in ("text", "xml", "binary", "page"):
|
|
res[k] = d(res[k])
|
|
res["ttf"] = open(path, "rb").read()
|
|
ctx.emit("bmfont", res)
|