Initial commit.

current
Kiyoshi Aman 2017-12-07 08:38:28 -06:00
parent d0a19d3a7c
commit d03fa10184
6 changed files with 391 additions and 0 deletions

7
license.txt Normal file
View File

@ -0,0 +1,7 @@
Copyright 2018 Kiyoshi Aman
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
Melissa 8 is copyright 2018 Gemini under the terms of the Creative Commons Attribution-ShareAlike 4.0 International license.

90
melissa8.json Normal file
View File

@ -0,0 +1,90 @@
{
"font_name": "Melissa 8 VWF",
"filename": "melissa8.png",
"bits_per_pixel": 2,
"width": 8,
"height": 8,
"map": {
" ": {"index": 115, "width": 4},
"a": {"index": 1, "width": 5},
"b": {"index": 2, "width": 5},
"c": {"index": 3, "width": 5},
"d": {"index": 4, "width": 5},
"e": {"index": 5, "width": 5},
"f": {"index": 6, "width": 5},
"g": {"index": 7, "width": 5},
"h": {"index": 8, "width": 5},
"i": {"index": 9, "width": 4},
"j": {"index": 10, "width": 3},
"k": {"index": 11, "width": 5},
"l": {"index": 12, "width": 4},
"m": {"index": 13, "width": 8},
"n": {"index": 14, "width": 5},
"o": {"index": 15, "width": 5},
"p": {"index": 16, "width": 5},
"q": {"index": 17, "width": 5},
"r": {"index": 18, "width": 5},
"s": {"index": 19, "width": 5},
"t": {"index": 20, "width": 5},
"u": {"index": 21, "width": 5},
"v": {"index": 22, "width": 6},
"w": {"index": 23, "width": 7},
"x": {"index": 24, "width": 6},
"y": {"index": 25, "width": 6},
"z": {"index": 26, "width": 5},
"A": {"index": 33, "width": 6},
"B": {"index": 34, "width": 6},
"C": {"index": 35, "width": 6},
"D": {"index": 36, "width": 6},
"E": {"index": 37, "width": 5},
"F": {"index": 38, "width": 5},
"G": {"index": 39, "width": 6},
"H": {"index": 40, "width": 6},
"I": {"index": 41, "width": 4},
"J": {"index": 42, "width": 4},
"K": {"index": 43, "width": 6},
"L": {"index": 44, "width": 6},
"M": {"index": 45, "width": 6},
"N": {"index": 46, "width": 6},
"O": {"index": 47, "width": 6},
"P": {"index": 48, "width": 6},
"Q": {"index": 49, "width": 6},
"R": {"index": 50, "width": 6},
"S": {"index": 51, "width": 5},
"T": {"index": 52, "width": 6},
"U": {"index": 53, "width": 6},
"V": {"index": 54, "width": 6},
"W": {"index": 55, "width": 7},
"X": {"index": 56, "width": 6},
"Y": {"index": 57, "width": 6},
"Z": {"index": 58, "width": 6},
"0": {"index": 81, "width": 5},
"1": {"index": 82, "width": 4},
"2": {"index": 83, "width": 5},
"3": {"index": 84, "width": 5},
"4": {"index": 85, "width": 5},
"5": {"index": 86, "width": 5},
"6": {"index": 87, "width": 5},
"7": {"index": 88, "width": 5},
"8": {"index": 89, "width": 5},
"9": {"index": 90, "width": 5},
":": {"index": 97, "width": 2},
",": {"index": 98, "width": 3},
";": {"index": 99, "width": 3},
"-": {"index": 100, "width": 5},
"/": {"index": 101, "width": 4},
"(": {"index": 102, "width": 4},
")": {"index": 103, "width": 4},
".": {"index": 104, "width": 2},
"'": {"index": 105, "width": 3},
"\"": {"index": 106, "width": 5},
"%": {"index": 107, "width": 4},
"!": {"index": 108, "width": 3},
"?": {"index": 109, "width": 6},
"~": {"index": 110, "width": 7},
"*": {"index": 111, "width": 4},
"+": {"index": 112, "width": 6},
"=": {"index": 113, "width": 5},
"#": {"index": 114, "width": 6}
}
}

BIN
melissa8.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

52
readme.txt Normal file
View File

@ -0,0 +1,52 @@
Smeargle 0.2.1 readme
-------------------
Usage: smeargle.py font.json script.txt
font.json is a JSON document which describes the font and provides a mapping
of characters to font indexes and font widths.
script.txt is a plaintext document without formatting which is rendered as an
image in both PNG and raw binary formats.
Script output
-------------
The following files are emitted when Smeargle is run:
* script.png contains the rendered script with deduplication, formatted
compactly. This is provided so that you can use your favourite viewer to
inspect the output.
* script.bin is almost identical to the above; the difference is that it has
been converted to your font's bitdepth directly.
* script_index.txt provides an index mapping which tells you how to index
into the rendered tilemap to reproduce the text.
font.json format
----------------
The following format MUST be observed, or you will not get the output you want.
Remove '//' and everything following it in each line if you plan to copy/paste
this example for your own use. Do not leave a trailing comma on the final entry
in the map.
{
"font_name": "Example", // Human-readable, not currently used
"filename": "example.png", // Filename of the font (PNG)
"bits_per_pixel": 2, // Depth in bits; 2**n is color count
"width": 8, // Width of a given tile
"height": 8, // Height of a given tile
"map": { // character -> index & width
" ": {"index": 115, "width": 4}, // Must be a blank tile somewher
}
}
Raw output
----------
The raw output is fairly simple. For 2bpp, four pixels are encoded at a time.
For 3bpp, six pixels are encoded at a time. For 4bpp, only two are encoded at
a time. Raw output looks like:
2bpp [0123] -> 0b11100100
3bpp [01234543] -> 0b01110010 0b01000110 0b10001000
4bpp [01] -> 0b00010000
Note that it doesn't matter how the pixels are arranged in the original image;
your code should be aware of the image dimensions regardless.

236
smeargle.py Normal file
View File

@ -0,0 +1,236 @@
# Copyright 2018 Kiyoshi Aman
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
# SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
# IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
import sys
import json
import os.path as op
from math import ceil
from PyQt5.QtGui import QImage, QPixmap, QPainter, QGuiApplication
def pack(bits=2, bytes=()):
min = 0
max = 2**bits - 1
base = 0
shift = 0
ret = bytearray()
for byte in bytes:
if byte > max:
raise ValueError('{} exceeds bit cap'.format(bin(byte)))
base = base + ((byte & max) << shift)
shift += bits
while base > 0:
byte = base & 0xFF
ret.append(byte)
base -= 256
ret.reverse()
return ret
def export(image, filename, bits=2):
if bits == 2:
write = 4
elif bits == 3:
write = 8
elif bits == 4:
write = 2
else:
raise ValueError('too many bits per pixel')
if image.colorCount() > 2**bits:
raise ValueError('too many colors')
with open(filename, mode='wb') as f:
qwidth = int(image.width() / write)
for y in range(image.height()):
for qx in range(qwidth):
if write == 4:
packing = (
image.pixelIndex(qx * write + 0, y),
image.pixelIndex(qx * write + 1, y),
image.pixelIndex(qx * write + 2, y),
image.pixelIndex(qx * write + 3, y)
)
elif write == 2:
packing = (
image.pixelIndex(qx * write + 0, y),
image.pixelIndex(qx * write + 1, y)
)
elif write == 6:
packing = (
image.pixelIndex(qx * write + 0, y),
image.pixelIndex(qx * write + 1, y),
image.pixelIndex(qx * write + 2, y),
image.pixelIndex(qx * write + 3, y),
image.pixelIndex(qx * write + 4, y),
image.pixelIndex(qx * write + 5, y),
image.pixelIndex(qx * write + 6, y),
image.pixelIndex(qx * write + 7, y),
)
f.write(pack(bits, packing))
class Font(QPixmap):
"""A simple class for basic bitmap fonts."""
def __init__(self, filename, width=8, height=8):
super().__init__(filename)
self._width = width
self._height = height
self._tpr = int(self.width() / self._width)
def index(self, tile):
row = int(tile / self._tpr)
column = tile % self._tpr
x = column * self._width
y = row * self._height
if (x > self.width()) or (y > self.height()):
raise KeyError('index')
return self.copy(x, y, self._width, self._height)
def main():
if len(sys.argv) < 2:
print(
"""Usage: smeargle.py font.json script
font.json is the metadata file associated with the font.
script is the text to be typeset.
The PNG and raw binary outputs will be exported using the script filename
as a base. (ex: test.txt -> test.png & test.bin)
"""
)
sys.exit(1)
app = QGuiApplication(sys.argv)
(font, script) = sys.argv[1:3]
font_info = None
script_base, ext = op.splitext(script)
output = script_base + '.png'
output_raw = script_base + '.bin'
print('Loading font information...')
with open(font, mode='rb') as f:
font_info = json.load(f)
print('Loading font data...')
font_data = Font(font_info['filename'], font_info['width'], font_info['height'])
print('Loading text...')
with open(script, mode='r', encoding='utf-8', errors='replace') as f:
text = f.read()
images = []
fmap = font_info['map']
width = font_info['width']
height = font_info['height']
line = 0
lines = text.split('\n')
painter = QPainter()
filler = font_data.index(fmap[' ']['index']).toImage().pixel(0, 0)
print('Rendering text...')
scriptmap = {}
while len(images) < text.count('\n'):
position = 0
temp = QImage(width * len(lines[line]), height, QImage.Format_RGB32)
temp.fill(filler)
painter.begin(temp)
for char in lines[line]:
if char in fmap.keys():
glyph = font_data.index(fmap[char]['index'] - 1)
painter.drawImage(position, 0, glyph.toImage())
painter.save()
position += fmap[char]['width']
else:
print('WARNING: unknown glyph "{}"'.format(char))
painter.end()
temp = temp.copy(0, 0, ceil(position / width) * width, height)
images.append(temp)
scriptmap[lines[line]] = temp
line += 1
print('Text rendered. Generating tilemap...')
tilemap = {}
tilemap_index = {}
counter_unique = 0
counter_total = 0
for line, image in scriptmap.items():
iwidth = image.width()
tiles = int(iwidth / width)
column = 0
text_tiles = []
while tiles > 0:
tile = image.copy(column, 0, width, height).convertToFormat(QImage.Format_Indexed8)
data = bytearray()
for y in range(tile.height()):
for x in range(tile.width()):
data.append(tile.pixelIndex(x, y))
data = bytes(data)
if data not in tilemap.keys():
tilemap[data] = tile
tilemap_index[data] = str(counter_unique)
counter_unique += 1
text_tiles.append(tilemap_index[data])
counter_total += 1
column += width
tiles -= 1
scriptmap[line] = text_tiles
print('Tilemap generated, with {} tiles mapped ({} unique). Rendering tilemap...'.format(counter_total, counter_unique))
image = QImage(width * 16, ceil(len(tilemap.keys()) / 16) * height, QImage.Format_RGB32)
image.fill(filler)
painter.begin(image)
(row, column) = (0, 0)
for data, tile in tilemap.items():
painter.drawImage(column, row, tile)
if column < (width * 16 - width):
column += width
else:
column = 0
row += height
painter.end()
print('Writing line <-> tilemap indexing...')
with open(script_base + '_index.txt', mode='w') as f:
for line, index in scriptmap.items():
f.write('{} -> {}\n'.format(line, ', '.join(index)))
print('Saving rendered tilemap...')
file = QPixmap.fromImage(image)
file.save(output, 'PNG')
print('Exporting as 2bpp...')
export(image.convertToFormat(QImage.Format_Indexed8), output_raw, font_info['bits_per_pixel'])
if __name__ == '__main__':
main()

6
test.txt Normal file
View File

@ -0,0 +1,6 @@
Potion
Hi Potion
Phoenix Tail
X-Potion
Huh?!
Oh my god, are you serious?!