roc/tools/fontmaker.py
2017-05-08 13:10:48 -07:00

93 lines
2 KiB
Python

import os
import pygame
import sys
import math
pygame.init()
pygame.font.init()
assert pygame.font.get_init()
fmod = pygame.font
Font = pygame.font.Font
fontname, fontsize = sys.argv[1:]
if '/' in fontname:
ffile = fontname
fontname = os.path.splitext(os.path.split(fontname)[1])[0].lower()
else:
ffile = fmod.match_font(fontname)
if not ffile:
print("Unable to find font... here is a list of fonts:\n")
for x in sorted(fmod.get_fonts()):
print(x)
sys.exit(0)
fontsize = int(fontsize)
fontname = "%s%s" % (fontname, fontsize)
f = Font(ffile, fontsize)
start = 32
end = 128
images = []
imsizes = []
maxwidth = 0
maxheight = 0
for char in range(start, end):
letter = chr(char)
sz = f.size(letter)
maxwidth = max(maxwidth, sz[0])
maxheight = max(maxheight, sz[1])
im = f.render(letter, True, (255, 255, 255))
images.append(im)
imsizes.append(sz)
print(len(images))
maxwidth += 1
maxheight += 1
ratio = float(maxwidth) / float(maxheight)
print("Ratio %s" % (ratio,))
reqwidth = maxwidth * len(images)
ratioheight = int(math.ceil(math.sqrt(len(images) * ratio)))
ratiowidth = int(math.ceil(len(images) / math.sqrt(len(images) * ratio)))
print([ratioheight, ratiowidth])
reqwidth = maxwidth * ratiowidth
reqheight = maxheight * ratioheight
print([reqheight, reqwidth])
texsize = 16
while texsize < reqheight or texsize < reqwidth:
texsize *= 2
print(texsize)
tex = pygame.Surface((texsize, texsize), pygame.SRCALPHA, 32)
tex.fill((0, 0, 0, 0))
for i, im in enumerate(images):
tex.blit(im, (((i % ratiowidth) * maxwidth), ((i // ratiowidth) * maxheight)))
pygame.image.save(tex, "%s.png" % (fontname,))
datf = open("%s.tfd" % (fontname,), "w")
datf.write("fontheader\n")
datf.write("%s,%s\n" % (start, end))
datf.write("%s,%s\n" % (maxwidth, maxheight))
datf.write("%s,%s\n" % (ratiowidth, ratioheight))
datf.write("%s,%s\n" % (texsize, texsize))
datf.write("charsizes\n")
for i, sz in enumerate(imsizes):
datf.write("%s,%s\n" % (sz[0], sz[1]))
datf.close()