-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathc64image.py
executable file
·315 lines (242 loc) · 9.54 KB
/
c64image.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
#!/usr/bin/python3
# c64image.py
#
# A small python program to convert an image to Commodore 64 multi-colour
# bitmap data. Output can be an executable PRG or a header file.
#
# - Philip Heron <[email protected]>
#
# --
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# --
import sys
import math
import random
import argparse
from PIL import Image
p = argparse.ArgumentParser(description = 'Convert an image to a Commodore 64 multi-colour bitmap.')
p.add_argument('input', help='The image file to read.')
p.add_argument('output', help='Output filename.')
p.add_argument('-f', '--format', help='Set the output file format S, H, KOA, GG or PRG. Default: S', default = 'S')
p.add_argument('-b', '--background', help='Set the background colour 0-15. Default: Auto', default = False, type=int)
p.add_argument('--id', help='Set the image ID in S or H files', default = 'image')
args = p.parse_args()
background = args.background
out_format = args.format.upper()
image_id = args.id
if background != False and (background < 0 or background > 15):
p.print_usage()
print("Invalid background colour " + str(background))
exit()
if out_format not in ('S', 'H', 'KOA', 'GG', 'PRG'):
p.print_usage()
print("Invalid output format " + out_format)
exit()
# Open and convert the image to 160x200 RGB frame
im = Image.open(args.input).convert('RGB').resize((160, 200), Image.BICUBIC)
# The C64 palette
palette = (
(0x00, 0x00, 0x00),
(0xFF, 0xFF, 0xFF),
(0x88, 0x00, 0x00),
(0xAA, 0xFF, 0xEE),
(0xCC, 0x44, 0xCC),
(0x00, 0xCC, 0x55),
(0x00, 0x00, 0xAA),
(0xEE, 0xEE, 0x77),
(0xDD, 0x88, 0x55),
(0x66, 0x44, 0x00),
(0xFF, 0x77, 0x77),
(0x33, 0x33, 0x33),
(0x77, 0x77, 0x77),
(0xAA, 0xFF, 0x66),
(0x00, 0x88, 0xFF),
(0xBB, 0xBB, 0xBB),
)
palette_names = (
'Black',
'White',
'Red',
'Cyan',
'Violet',
'Green',
'Blue',
'Yellow',
'Orange',
'Brown',
'Lightred',
'Dark Grey',
'Medium Grey',
'Light Green',
'Light Blue',
'Light Grey',
)
# Colour usage counters, palette order
ccounter = [0] * 16
# Create the canvas. This represents an 'ideal' C64 image where
# there are no colour restrictions within the blocks
canvas = [[[[0] * 4 for row in range(8)] for ccol in range(40)] for crow in range(25)]
# Convert an (r, g, b) value to the nearest C64 palette entry
def rgb2pal(colour):
s = -1
c = -1
# Random noise dither
#colour = list(colour)
#colour[0] += random.randint(-32,32)
#colour[1] += random.randint(-32,32)
#colour[2] += random.randint(-32,32)
for x in range(0, len(palette)):
d = abs(math.sqrt(
(colour[0] - palette[x][0]) ** 2 +
(colour[1] - palette[x][1]) ** 2 +
(colour[2] - palette[x][2]) ** 2
))
if s == -1 or d < s:
s = d
c = x
return c
# Find the nearest C64 palette entry from a list of palette codes
def pal2pal(colour, colours):
s = -1
c = -1
colour = palette[colour]
for x in range(0, len(colours)):
d = abs(math.sqrt(
(colour[0] - palette[colours[x]][0]) ** 2 +
(colour[1] - palette[colours[x]][1]) ** 2 +
(colour[2] - palette[colours[x]][2]) ** 2
))
if s == -1 or d < s:
s = d
c = colours[x]
return c
# Write bytes to a string
def write_bytes(name, data, cformat):
if cformat == 'S':
s = "%s\n" % name
for line in (data[x:x + 32] for x in range(0, len(data), 32)):
s += "\t.byte " + ",".join(("$%02X" % x for x in line)) + "\n"
elif cformat == 'H':
s = "unsigned char %s[0x%d] = [\n" % (name, len(data))
for line in (data[x:x + 32] for x in range(0, len(data), 32)):
s += "\t" + ",".join(("0x%02X" % x for x in line)) + ",\n"
s += "];\n";
return s
# Koala Painter-style RLE compression
def koala_rle(data):
if len(data) == 0:
return bytes([])
rle = 0
last = -1
compressed = []
# Pad the end with a dummy byte to flush remaining RLE data
data += bytes([~data[-1] & 0xFF])
for byte in data:
if byte == last:
rle += 1
continue
while (last != 0xFE and rle > 3) or (last == 0xFE and rle > 0):
compressed += [0xFE, last, min(0xFF, rle)]
rle -= min(0xFF, rle)
while rle > 0:
compressed += [last]
rle -= 1
last = byte
rle = 1
return bytes(compressed)
# Render the PIL image to the canvas
for cy in range(0, 25):
for cx in range(0, 40):
ox = cx * 4
oy = cy * 8
for y in range(0, 8):
for x in range(0, 4):
p = rgb2pal(im.getpixel((ox + x, oy + y)))
canvas[cy][cx][y][x] = p
ccounter[p] += 1
if background == False:
# Select the background based on the most used colour
background = ccounter.index(max(ccounter))
print("Using %s (%d) for background colour" % (palette_names[background], background))
else:
print("Background fixed at %s (%d)" % (palette_names[background], background))
# Initialise the bitmap buffer
bitmap_bytes = []
screen_bytes = []
colour_bytes = []
last_colours = False
for cy in range(0, 25):
for cx in range(0, 40):
# Make a list of all the colours used in this block
# Background is always used, even if not referenced
colours = [background]
ccounter = [0]
for row in canvas[cy][cx]:
for colour in row:
if not colour in colours:
colours.append(colour)
ccounter.append(0)
ccounter[colours.index(colour)] += 1
# Sort the colours, background first then most used to least
colours = [background] + list(x[1] for x in sorted(zip(ccounter[1:], colours[1:]), reverse = True))
if len(colours) > 4:
print("Block %dx%d has too many non-background colours: %s -> %s" % (cx, cy, colours[1:], colours[1:4]))
# Crop colour list to the background and 3 most used values
colours = colours[:4]
# Replace removed colours in the block with the nearest valid match
for y in range(8):
for x in range(4):
p = canvas[cy][cx][y][x]
if not p in colours:
canvas[cy][cx][y][x] = pal2pal(p, colours)
# If all the colours of this block are present in the previous block,
# use that same order. This may help with RLE compression.
if last_colours != False and set(colours).issubset(set(last_colours)):
colours = last_colours
elif len(colours) != 4:
colours += [0] * (4 - len(colours))
last_colours = colours
# Output this block
for row in canvas[cy][cx]:
bitmap_bytes.append(colours.index(row[0]) << 6 | colours.index(row[1]) << 4 | colours.index(row[2]) << 2 | colours.index(row[3]))
screen_bytes.append(colours[1] << 4 | colours[2])
colour_bytes.append(colours[3])
# Write the results
if out_format == 'S':
s = "\n%s_background = %d\n\n" % (image_id, background)
s += write_bytes(image_id, bitmap_bytes, out_format) + "\n"
s += write_bytes(image_id + "_screen", screen_bytes, out_format) + "\n"
s += write_bytes(image_id + "_colour", colour_bytes, out_format) + "\n"
s = bytes(s, encoding='utf-8')
elif out_format == 'H':
s = "\n#define %s_background %d\n\n" % (image_id, background)
s += write_bytes(image_id, bitmap_bytes, out_format) + "\n"
s += write_bytes(image_id + "_screen", screen_bytes, out_format) + "\n"
s += write_bytes(image_id + "_colour", colour_bytes, out_format) + "\n"
s = bytes(s, encoding='utf-8')
elif out_format == 'KOA':
s = bytes([0x00, 0x60]) + bytes(bitmap_bytes) + bytes(screen_bytes) + bytes(colour_bytes) + bytes([background])
elif out_format == 'GG':
s = bytes([0x00, 0x60]) + koala_rle(bytes(bitmap_bytes) + bytes(screen_bytes) + bytes(colour_bytes) + bytes([background]))
elif out_format == 'PRG':
# This string is the binary produced from the assembly program "showimg.s"
# Pay no attention to the ugly hack to set the background colour.
s = bytes.fromhex(
('01080c080d089e3230363100000078a240a01f205608a9008d6308a9448d6408a2e' +
'8a003205608a9008d6308a9d88d6408a2e8a003205608a91c8d18d0a93b8d11d0a9' +
'188d16d0a9028d00dda9%02X8d20d08d21d04c5308e8c8cad00488d00160ad78088d0' +
'060ee6008d003ee6108ee6308d003ee64084c5808') % background
)
s += bytes(bitmap_bytes) + bytes(screen_bytes) + bytes(colour_bytes)
open(args.output, 'wb').write(s)