Created
July 20, 2019 10:51
-
-
Save heisvoid/032c6e346d57a1912d0226748c4d270a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
# Extract sprites | |
import argparse | |
import struct | |
import os | |
# mode 13h resolution | |
MONITOR_WIDTH = 320 | |
MONITOR_HEIGHT = 200 | |
# bright pink | |
SPRITE_BACKGROUND = (255, 0, 255) | |
parser = argparse.ArgumentParser(description='Extract sprites.') | |
parser.add_argument('-p', required=True, help='palette file', dest='pal') | |
parser.add_argument('-f', required=True, help='compressed sprites file', | |
dest='spr') | |
args = parser.parse_args() | |
# read palette | |
pal = [] | |
with open(args.pal, 'rb') as f: | |
for i in range(256): | |
buf = f.read(3) | |
buf = struct.unpack('<BBB', buf) | |
pal.append((buf[0], buf[1], buf[2])) | |
# extract sprites | |
with open(args.spr, 'rb') as f: | |
# header | |
f.seek(0x42, os.SEEK_SET) | |
# total number of sprites | |
buf = f.read(2) | |
buf = struct.unpack('<H', buf) | |
num = buf[0] | |
# zero padding | |
f.seek(60, os.SEEK_CUR) | |
for n in range(num): | |
# total length of compressed pixel data | |
f.seek(4, os.SEEK_CUR) | |
# width and height of a sprite | |
bytes = f.read(4) | |
bytes = struct.unpack('<HH', bytes) | |
width = bytes[0] | |
height = bytes[1] | |
assert 320 >= width | |
assert 200 >= height | |
# unknown | |
f.seek(2, os.SEEK_CUR) | |
f.seek(2, os.SEEK_CUR) | |
# number of compressed chunks | |
bytes = f.read(2) | |
bytes = struct.unpack('<H', bytes) | |
chunks = bytes[0] | |
# reset monitor | |
#monitor = range(MONITOR_WIDTH * MONITOR_HEIGHT) | |
monitor = [] | |
for i in range(MONITOR_WIDTH * MONITOR_HEIGHT): | |
monitor.append(SPRITE_BACKGROUND) | |
# draw a sprite on monitor | |
idx = 0 | |
for c in range(chunks): | |
bytes = f.read(2) | |
bytes = struct.unpack('<H', bytes) | |
blanks = bytes[0] | |
idx = idx + blanks | |
bytes = f.read(1) | |
bytes = struct.unpack('<B', bytes) | |
drawn = 4 * bytes[0] | |
bytes = f.read(1) | |
bytes = struct.unpack('<B', bytes) | |
drawn = drawn + bytes[0] | |
for d in range(drawn): | |
bytes = f.read(1) | |
bytes = struct.unpack('<B', bytes) | |
pal_idx = bytes[0] | |
monitor[idx] = pal[pal_idx] | |
idx = idx + 1 | |
# write a sprite to file | |
out_name = os.path.basename(args.spr) | |
out_name = out_name + '.%05d' % n + '.ppm' | |
with open(out_name, 'w') as out: | |
out.write('P3\n') | |
out.write('%d %d\n' % (width, height)) | |
out.write('255\n') | |
for h in range(height): | |
for w in range(width): | |
rgb = monitor[320 * h + w] | |
out.write('%d %d %d\n' % (rgb[0], rgb[1], rgb[2])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment