-
Notifications
You must be signed in to change notification settings - Fork 5
/
palette.py
124 lines (86 loc) · 2.49 KB
/
palette.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
""" Copyright 2015-2017 sta256+mpskit at gmail.com
This file is part of mpskit.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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.
See LICENSE file for more details.
"""
from common import *
from PIL import Image, ImageDraw
from PIL.ImagePalette import ImagePalette
def vga_color_trans(x):
return int((x * 255) / 63)
def attach_palette(img, pal):
R,G,B = [],[],[]
for c in pal:
R.append(c[0])
G.append(c[1])
B.append(c[2])
img.putpalette(
ImagePalette(
mode = 'RGB',
palette = R + G + B,
size = len(pal) * 3,
)
)
def export_palette(pal, name_ss):
img = Image.new('P', (16,16), 0)
attach_palette(img, pal)
d = ImageDraw.ImageDraw(img)
d.rectangle((0, 0, 16, 16), fill=0)
for k in range(len(pal)):
i = k % 16
j = k // 16
d.rectangle((i, j, i+1, j+1), fill=k)
name_pal = '{}.pal.png'.format(name_ss)
img.save(name_pal)
print(name_pal)
def read_palette_col(f):
""" Read palette as encoded in Colonization
repeat 256
uint8 r
uint8 g
uint8 b
"""
pal = []
for i in range(256):
rr,gg,bb = reads(f, '3b')
r,g,b = map(vga_color_trans, [rr,gg,bb])
pal.append((r,g,b))
# something (PIL?) requires that transparency color must be present in the palette (stupid!)
# standard transparency index is 253 so I will just fill with zeroes
while len(pal) < 255:
pal.append((0,0,0))
return pal
def read_palette_rex(f, fill=(0,0,0)):
""" Read palette as encoded in Rex
uint16 ncolors
repeat ncolors
uint8 red6
uint8 green6
uint8 blue6
uint8 ind
uint8 u2
uint8 flags
"""
ncolors = read_uint16(f)
pal = []
for i in range(ncolors):
rr,gg,bb,ind,u2,flags = reads(f, '6b')
r,g,b = map(vga_color_trans, [rr,gg,bb])
#print("pal",rr,gg,bb,ind,u2,flags)
# TODO: not the case in SECTION5/RM505A8.SS
if ind != -1:
warning("palette index != -1 (ignored); ind={}", ind)
#assert pal[i] is None
pal.append((r,g,b))
assert len(pal) == ncolors
# something (PIL?) requires that transparency color must be present in the palette (stupid!)
# standard transparency index in Rex is 253 so I will just fill with zeroes
if fill is not None:
while len(pal) < 255:
pal.append(fill)
return pal