-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild.py
executable file
·199 lines (152 loc) · 5.73 KB
/
build.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
#!/usr/bin/env python3
import glob
import os
from PIL import Image
import shutil
import yaml
import argparse
import logging
logging.basicConfig()
log = logging.getLogger(__file__)
log.setLevel(logging.INFO)
TEXTURE_VARIANTS = (
'diffuse',
'norm',
'bump',
'gloss',
'glow',
'pants',
'shirt',
)
DEBUG = False
def scale_pixel(pixel, minimum, maximum):
delta = maximum - minimum
log.debug(', '.join([pixel, minimum, maximum, delta]))
def scale(pixel_value):
return int(((pixel_value / 255) * delta + minimum) * 255)
try:
r = scale(pixel[0])
g = scale(pixel[1])
b = scale(pixel[2])
return (r, g, b, pixel[3])
except TypeError:
# This is not RGBA pixel so we will return an RGBA pixel
return scale(pixel)
def scale_layer(im, minimum, maximum):
log.debug(' '.join([im, minimum, maximum]))
pixels = im.load()
for i in range(im.size[0]):
for j in range(im.size[1]):
px = pixels[i, j]
pixels[i, j] = scale_pixel(px, minimum, maximum)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Build bump map images for Quake textures.')
parser.add_argument('-i', '--input', default="textures", type=str, help='Directory containing the variant textures')
parser.add_argument('-t', '--type', default='all', type=str, help="Comma-separated list of texture variants to build. Defaults to `all` which builds all variants available.")
parser.add_argument('-o', '--output', default="~/.darkplaces/id1/textures", type=str, help='Quake textures directory to put the bump map images.')
parser.add_argument('-f', '--format', default='tga', type=str, help='Image format to use. (TODO)')
parser.add_argument('-l', '--log-level', default="info", help="Log level")
args = parser.parse_args()
log.setLevel(logging._nameToLevel[args.log_level.upper()])
if args.type == 'all':
# args.type = TEXTURE_VARIANTS
# temp override
args.type = ('bump', 'gloss', 'glow', "norm")
else:
args.type = args.type.split(',')
t_defs = {}
for variant in args.type:
try:
with open(os.path.abspath(os.path.expanduser(variant + '.yml')), 'r') as fp:
t_defs[variant] = yaml.safe_load(fp)
except FileNotFoundError:
t_defs[variant] = {}
# Set abolute paths for input and output directories
args.input = os.path.abspath(os.path.expanduser(args.input))
args.output = os.path.abspath(os.path.expanduser(args.output))
# Check that the output directory exists
if not os.path.isdir(args.output):
raise NotADirectoryError(f"The output directory `{args.output}` does not exist")
diffuse_textures = {}
for tex_path in glob.glob(os.path.join(args.input, "diffuse", "*")):
tex_filename = os.path.basename(tex_path) # window01_4.tga
tex_name, tex_ext = os.path.splitext(tex_filename) # (window01_4, .tga)
diffuse_textures[tex_name] = [tex_name]
with open(os.path.abspath(os.path.expanduser('diffuse.yml')), "r") as fp:
t_defs['diffuse'] = yaml.safe_load(fp)
diffuse_textures.update(t_defs['diffuse'])
for t_name, t_src in diffuse_textures.items():
# copy over the diffuse textures
t_ext = '.tga'
t_filename = t_name + t_ext
t_path = os.path.abspath(os.path.join(args.input, 'diffuse', t_src[0] + t_ext))
t_format = t_ext[1:] # tga
src = t_path
dst = os.path.abspath(os.path.join(args.output, t_filename))
log.info(f"Copying {src} to {dst}")
shutil.copy(src, dst)
# create or copy the variant textures
for variant in args.type:
# t_filename = os.path.basename(t_path) # window01_4.tga
# t_name, t_ext = os.path.splitext(t_filename) # (window01_4, .tga)
# t_format = t_ext[1:] # tga
im = None
dst_filename = t_name + '_' + variant + t_ext
dst = os.path.abspath(os.path.join(args.output, dst_filename))
if variant in t_defs and t_name in t_defs[variant]:
# If variant definition use that
layers = t_defs[variant][t_name]
# We only want to scale texture brightness based regular layers
# anything prefixed with __ is a special layer that isn't scaled
num_layers = 1
if len(layers) > 1:
num_layers = len(
[
layer
for layer
in layers
if layer is None or layer[:2] != '__'
]
)
for layer_level, layer_name in enumerate(layers):
if layer_name:
log.debug(f"Layer: {layer_name}")
layer_filename = layer_name
if layer_name[:2] == '__':
layer_filename = layer_name[2:]
layer = Image.open(os.path.join(args.input, variant, '{}{}'.format(layer_filename, t_ext)))
if layer.mode != 'RGBA':
layer = layer.convert('RGBA')
if im is None:
im = Image.new('RGBA', (layer.size[0], layer.size[1]), "black")
if layer_name[:2] != '__':
layer_min = float(layer_level) / num_layers
layer_max = float(layer_level + 1) / num_layers
scale_layer(layer, layer_min, layer_max)
im = Image.alpha_composite(im, layer)
log.info(f"Creating {dst}")
im.save(dst, args.format)
else:
# There is no texture definition
# if variant file exists, copy it over
try:
src = os.path.abspath(os.path.join(args.input, variant, t_filename))
log.info(f"Copying {src} to {dst}")
shutil.copy(src, dst)
except FileNotFoundError:
if variant == 'gloss':
# open the diffuse texture
diffuse_texture = Image.open(t_path)
# create new black image of dimensions
im = Image.new('RGBA', diffuse_texture.size, (0, 0, 0, 255))
# save new image as gloss texture
im.save(dst, args.format)
elif variant == 'bump':
# open the diffuse texture
diffuse_texture = Image.open(t_path)
# create new black image of dimensions
im = Image.new('RGBA', diffuse_texture.size, (128, 128, 128, 255))
# save new image as gloss texture
im.save(dst, args.format)
else:
log.warn(f"No {variant} file found for {t_name}")