xen32os/gen/fontgen.py

85 lines
2.0 KiB
Python
Raw Normal View History

2024-02-07 19:32:27 +01:00
import json
import struct
# generates:
2024-02-07 22:52:21 +01:00
# font_data.bin
# font_table.bin
# font_data.inc
2024-02-07 19:32:27 +01:00
#
# struct Char {
# width: u8, height: u8, baseline: u8,
2024-02-07 22:52:21 +01:00
# data_offset: offset into font_data
2024-02-07 19:32:27 +01:00
# } (7 bytes)
2024-02-07 22:52:21 +01:00
CODEPAGE = {
0: None,
128: 'Ξ',
}
for x in range(32, 127):
CODEPAGE[x] = chr(x)
2024-02-07 19:32:27 +01:00
BASELINE = 7
codepoints = json.load(open("ultlf/codepoints.json"))
font_data = json.load(open("ultlf/data.json"))
baselines = json.load(open("ultlf/trimmed_baselines.json"))
UNKNOWN = [
"# ### #",
"# # # #",
"# # #",
"# # #",
"# # #",
"# #",
"# # #",
]
2024-02-07 22:52:21 +01:00
SPACE = [" "]
SCALE = 2
def scale(glyph):
out = []
for line in glyph:
line_scaled = ""
for ch in line:
line_scaled += ch * SCALE
out.extend([line_scaled] * SCALE)
return out
with open("xenrom/data/font_table.dat", "wb") as table_file, open("xenrom/data/font_data.dat", "wb") as data_file, open("xenrom/data/font_data.inc", "w") as inc_file:
2024-02-07 19:32:27 +01:00
table = b''
2024-02-07 22:52:21 +01:00
data = b''
2024-02-07 19:32:27 +01:00
2024-02-07 22:52:21 +01:00
for i in range(256):
ch = CODEPAGE.get(i, None)
unicode_codepoint = ord(ch) if ch is not None else None
if unicode_codepoint is None:
glyph = UNKNOWN
baseline = 6
elif unicode_codepoint == 32:
glyph = SPACE
baseline = 1
2024-02-07 19:32:27 +01:00
else:
2024-02-07 22:52:21 +01:00
ultlf_idx = codepoints.index(unicode_codepoint)
glyph = font_data[ultlf_idx]
baseline = baselines[ultlf_idx]
if "X" in "".join(glyph):
2024-02-07 19:32:27 +01:00
glyph = UNKNOWN
baseline = 6
2024-02-07 22:52:21 +01:00
glyph = scale(glyph)
baseline *= SCALE
table += struct.pack("<BBBI", len(glyph[0]), len(glyph), baseline, len(data))
2024-02-07 19:32:27 +01:00
for line in glyph:
2024-02-07 22:52:21 +01:00
for ch in line:
data += b'\x00' if ch == ' ' else b'\x01'
2024-02-07 19:32:27 +01:00
2024-02-07 22:52:21 +01:00
table_file.write(table)
data_file.write(data)
2024-02-07 19:32:27 +01:00
2024-02-07 22:52:21 +01:00
inc_file.write(f"const FONT_SIZE: {SCALE}\n")
inc_file.write(f"const FONT_LINE_HEIGHT: {8 * SCALE}\n")