-
Notifications
You must be signed in to change notification settings - Fork 25
/
run.py
451 lines (395 loc) · 15.8 KB
/
run.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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
#-*- coding:utf-8 -*-
import os
import platform
import shutil
import time
import sys
import codecs
import inspect
import getopt
import math
import subprocess
import argparse
temp_dirs = []
argParser = argparse.ArgumentParser()
argParser.add_argument("-i", "--input", help="input folder", type=str, default=None)
argParser.add_argument("-o", "--output", help="output folder", type=str, default=None)
argParser.add_argument("-x", "--xml", help="export xml", action="store_true", default=False)
argParser.add_argument("-s", "--scale", help="scale the source images", type=float, default=1)
argParser.add_argument("--with-png", help="output with the combined png", action="store_true", default=False)
argParser.add_argument("--quiet", action="store_true", default=False)
argParser.add_argument("--extend-name", help="extra string after name", type=str, default="")
argParser.add_argument("--dump-pic-usage", help="dump png usage info to text", action="store_true", default=False)
group = argParser.add_mutually_exclusive_group()
group.add_argument("--tree", help="dump tree structure", action="store_true",default=False)
group.add_argument("--single", help="export flash one by one", action="store_true", default=False)
args = argParser.parse_args()
def remove_temp_dirs_when_except():
print("===remove temp dirs===")
for filepath in temp_dirs:
shutil.rmtree(filepath)
def show_exception_and_exit(exc_type, exc_value, tb):
import traceback
traceback.print_exception(exc_type, exc_value, tb)
raw_input("run failed.")
remove_temp_dirs_when_except();
sys.exit(-1)
import struct
import imghdr
def get_image_size(fname):
'''Determine the image type of fhandle and return its size.
from draco'''
with open(fname, 'rb') as fhandle:
head = fhandle.read(24)
if len(head) != 24:
return
if imghdr.what(fname) == 'png':
check = struct.unpack('>i', head[4:8])[0]
if check != 0x0d0a1a0a:
return
width, height = struct.unpack('>ii', head[16:24])
elif imghdr.what(fname) == 'gif':
width, height = struct.unpack('<HH', head[6:10])
elif imghdr.what(fname) == 'jpeg':
try:
fhandle.seek(0) # Read 0xff next
size = 2
ftype = 0
while not 0xc0 <= ftype <= 0xcf:
fhandle.seek(size, 1)
byte = fhandle.read(1)
while ord(byte) == 0xff:
byte = fhandle.read(1)
ftype = ord(byte)
size = struct.unpack('>H', fhandle.read(2))[0] - 2
# We are at a SOFn block
fhandle.seek(1, 1) # Skip `precision' byte.
height, width = struct.unpack('>HH', fhandle.read(4))
except Exception: #IGNORE:W0703
return
else:
return
return width, height
sys.excepthook = show_exception_and_exit
this_file = inspect.getfile(inspect.currentframe())
DIR_PATH = os.path.abspath(os.path.dirname(this_file))
SEP = os.path.sep
sys.path.append(DIR_PATH + SEP + 'scripts')
import handleCombine as HC
FLASH_ROOT = args.input
OUTPUT_PATH = args.output
OUTPUT_NAME = "flash"
LEAVE_FILE = ['%s.1.ppm'%OUTPUT_NAME, '%s.1.pgm'%OUTPUT_NAME, '%s.lua'%OUTPUT_NAME, "%s.txt"%OUTPUT_NAME]
if args.with_png:
LEAVE_FILE.append('%s.1.png'%OUTPUT_NAME)
if args.xml:
LEAVE_FILE.append('combine.xml')
global sysOpen
TMP_FOLDER_NAME = "__tmp"
SCRIPT_PATH = DIR_PATH + SEP + 'scripts'
OUTPUT_PATH = OUTPUT_PATH or DIR_PATH + SEP + 'output'
FLASH_ROOT = FLASH_ROOT or DIR_PATH + SEP + 'input'
FLASH_ROOT = os.path.realpath(FLASH_ROOT)
OUTPUT_PATH = os.path.realpath(OUTPUT_PATH)
CONVERT_PATH = SCRIPT_PATH + SEP + 'convert '
if not os.path.exists(OUTPUT_PATH):
os.makedirs(OUTPUT_PATH)
class CmdError(Exception):
def __init__(self, string):
self.string = string
def __str__(self):
return repr(self.string)
class MainTree():
def __init__(self, path):
self.mainpath = path
self.folders = {}
self.files = []
self.tmpPath = self.mainpath + '/' + TMP_FOLDER_NAME
temp_dirs.append(self.tmpPath)
for root, dirs, files in os.walk(path):
self.SaveFiles(files)
self.ParseDirs(dirs)
dirs[:] = []
def SaveFiles(self, fileTuple):
for k in fileTuple:
if k[-4:] == '.fla':
self.files.append(self.mainpath + '/' + k)
def ParseDirs(self, dirs):
for k in dirs:
self.folders[k] = MainTree(self.mainpath + '/' + k)
def SetSingleExport(self):
self.single_export = True
def Export(self, forceBatch=False):
self.Clean()
if len(self.files) > 0:
if args.single and not forceBatch:
self.SingleExport()
else:
self.BatchExport()
for (k,v) in self.folders.items():
v.Export()
def BatchExport(self):
if (not args.quiet):
print('[info]Walking into %s'%self.mainpath)
os.makedirs(self.tmpPath)
self.CopyScript(self.tmpPath)
# pngs
if (not args.quiet):
print ('[info]Export png')
os.system(sysOpen + ' ' + self.tmpPath + SEP + 'exportFiles.jsfl')
self.WaitJSDone(self.tmpPath + SEP + 'done', True)
#TP
self.PreHandleMirror()
self.RemoveAnchorPng()
self.TexturePacker()
if os.path.isfile(self.tmpPath + SEP + "%s.png"%OUTPUT_NAME):
self.ImageMagicka()
self.WriteOriginImgSizeInfo()
else:
self.CopyScript(self.tmpPath, True)
#xml
os.system(sysOpen + ' ' + self.tmpPath + SEP + '/main.jsfl')
self.WaitJSDone(self.tmpPath + SEP + 'done', True)
self.Combine()
self.CopyUsefulFiles()
self.Clean()
def SingleExport(self):
groupFiles = []
os.makedirs(self.tmpPath)
for fpath in self.files:
fname = os.path.basename(fpath)
file_dir_path = self.tmpPath + SEP + fname[:-4]
if "@" in fname:
groupName = fname.split('@')[0]
if groupName not in groupFiles:
groupFiles.append(groupName)
groupDir = self.tmpPath + SEP + groupName
if not os.path.isdir(groupDir):
os.makedirs(groupDir)
shutil.copy(fpath, self.tmpPath + SEP + groupName + SEP + fname)
else:
os.makedirs(file_dir_path)
shutil.copy(fpath, file_dir_path + SEP + fname)
tree = MainTree(file_dir_path)
tree.SetSingleExport()
tree.Export(True)
for groupName in groupFiles:
tree = MainTree(self.tmpPath + SEP + groupName)
tree.SetSingleExport()
tree.Export(True)
self.Clean()
def WaitJSDone(self, filepath, bRemove = False):
while(not os.path.exists(filepath)):
time.sleep(0.5)
if bRemove:
while os.path.exists(filepath):
try:
os.remove(filepath)
except OSError:
time.sleep(0.5)
finally:
return
def CopyUsefulFiles(self):
if args.with_png:
os.rename(self.tmpPath + SEP + "%s.png"%OUTPUT_NAME, self.tmpPath + SEP + "%s.1.png"%OUTPUT_NAME)
for filename in LEAVE_FILE:
if os.path.exists(self.tmpPath + '/%s'%filename):
name, ext = os.path.splitext(filename)
else:
continue
if ext == ".ppm" or ext == ".pgm" or ext == ".png":
ext = ".1" + ext
ext = args.extend_name + ext
dirname = os.path.dirname(self.tmpPath.replace('\\', '/'))
names = dirname.split('/')
output_filename = names[len(names) - 1] + ext
if args.tree:
path_tree = self.mainpath .replace(FLASH_ROOT, '')
if not os.path.exists(OUTPUT_PATH + path_tree):
os.makedirs(OUTPUT_PATH + path_tree)
shutil.copy(self.tmpPath + '/%s'%filename, OUTPUT_PATH + path_tree + '/%s'%output_filename)
else:
shutil.copy(self.tmpPath + '/%s'%filename, OUTPUT_PATH + '/%s'%output_filename)
def Clean(self):
while os.path.exists(self.tmpPath):
try:
shutil.rmtree(self.tmpPath)
except OSError:
time.sleep(0.5)
finally:
return
def Combine(self):
bExist = False
filepath = self.tmpPath + '/combine.xml'
for root, dirs, files in os.walk(self.tmpPath):
for k in files:
if not k[-4:] == '.xml':
continue
if not bExist:
bExist = True
handle = codecs.open(filepath, 'a')
handle.write('<root>\n')
handle.close()
src = codecs.open(root + '/' +k, 'r')
content = src.read()
handle = codecs.open(filepath, 'a')
handle.write(content)
handle.write('\n')
handle.close()
break
if bExist:
handle = codecs.open(filepath, 'a')
handle.write('</root>\n')
handle.close()
self.hc = HC.Handler(filepath.replace('\\','/'), quiet = args.quiet)
self.hc.Export(self.tmpPath.replace('\\','/') + '/%s.lua'%OUTPUT_NAME)
if args.dump_pic_usage:
self.hc.ExportDumpinfo(self.tmpPath.replace('\\','/') + '/%s.txt'%OUTPUT_NAME)
def PreHandleMirror(self):
self.originImgSize = {}
tpath = self.tmpPath
imgpath = self.tmpPath + '/singleimg'
sysType = platform.system()
if sysType == "Windows":
tpath = tpath.replace('/','\\')
imgpath = imgpath.replace('/','\\')
files = os.listdir(imgpath)
identify_path = SCRIPT_PATH + SEP + 'identify '
if sysType == "Windows":
identify_path = SCRIPT_PATH + SEP + 'identify.exe '
for k in files:
w, h = get_image_size(imgpath + '%s%s'%(os.path.sep ,k))
w, h = int(w), int(h)
self.originImgSize[k] = '{"w": %s, "h":%s}'%(w, h)
main_name, ext = os.path.splitext(k)
bCrop = False
if main_name[-3:] == '_UD':
bCrop = True
s_w, s_h = w, h / 2
elif main_name[-3:] == '_LR':
bCrop = True
s_w, s_h = w / 2, h
elif main_name[-2:] == '_C':
bCrop = True
s_w, s_h = w / 2, h / 2
if bCrop:
if not w % 2 == 0:
s_w = s_w + 1
if not h % 2 == 0:
s_h = s_h + 1
self.CropImage(imgpath, k, s_w, s_h)
def CropImage(self, imgpath, filename, w, h):
cmd = "%s %s -crop %sx%s+0+0 %s"
cmd = cmd%(
CONVERT_PATH,
imgpath + os.path.sep + filename,
w,
h,
imgpath + os.path.sep + filename,
)
self.ExecuteCmd(cmd)
def RemoveAnchorPng(self):
imgpath = self.tmpPath + os.path.sep + 'singleimg'
files = os.listdir(imgpath)
for k in files:
if k.find('__anchor') >= 0:
os.remove(imgpath + os.path.sep + k)
def ExecuteCmd(self, cmd):
pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True, universal_newlines=True)
output = "".join(pipe.stdout.readlines())
sts = pipe.returncode
if sts is None: sts = 0
if not sts == 0:
self.Clean()
raise CmdError, output
sys.exit(-1)
return sts, output
def ImageMagicka(self):
cmd = CONVERT_PATH + self.tmpPath + SEP + "%s.png "%OUTPUT_NAME + self.tmpPath + SEP + "%s.1.ppm"%OUTPUT_NAME
cmd2 = CONVERT_PATH + self.tmpPath + SEP + "%s.png "%OUTPUT_NAME + ' -channel A -separate %s.1.pgm'%(self.tmpPath + SEP + OUTPUT_NAME)
self.ExecuteCmd(cmd)
self.ExecuteCmd(cmd2)
def TexturePacker(self):
tpath = self.tmpPath
sysType = platform.system()
if sysType == "Windows":
tpath = tpath.replace('/','\\')
cmd = ' '.join([
'TexturePacker',
'--algorithm MaxRects',
'--maxrects-heuristics Best',
'--pack-mode Best',
'--scale %s'%args.scale,
'--premultiply-alpha',
'--sheet %s' %(tpath + os.path.sep + '%s.png'%OUTPUT_NAME),
'--texture-format png',
'--extrude 2',
'--data %s' % (tpath + os.path.sep + '%s.json'%OUTPUT_NAME),
'--format json',
'--trim-mode Trim',
'--disable-rotation',
'--size-constraints AnySize',
'--max-width 2048',
'--max-height 2048',
'--common-division-x 2',
'--common-division-y 2',
#'--shape-debug',
'%s' % (tpath + os.path.sep + 'singleimg')
])
sts, out = self.ExecuteCmd(cmd)
if sts == 0:
if (not args.quiet):
print('[info]TP success')
def WriteOriginImgSizeInfo(self):
content = "{"
for k,v in self.originImgSize.items():
content += '"%s" : %s,\n'%(k, v)
content += "}"
handle = open(self.mainpath + '/' + TMP_FOLDER_NAME + '/originsize.json', 'w')
handle.write(content)
handle.close()
def CopyScript(self, path, no_png_out=False):
handle = open(SCRIPT_PATH + '/exportFiles.jsfl')
content = handle.read()
handle.close()
header = "var publishFolder = '%s'; \n"%(self.mainpath.replace('\\','/'))
footer = """batToDo(publishFolder);
FLfile.write("file:///%s",FLfile.uriToPlatformPath(publishFolder) + "\\n");"""%(self.mainpath.replace('\\','/') + '/' + TMP_FOLDER_NAME + '/done')
content = header + content + footer
handle = open(self.mainpath + '/' + TMP_FOLDER_NAME + '/exportFiles.jsfl', 'w')
handle.write(content)
handle.close()
handle = open(SCRIPT_PATH + '/main.jsfl')
content = handle.read()
handle.close()
header = ""
if not no_png_out:
header = 'eval("var JSONFILE = " + FLfile.read("file:///%s/%s.json"));\n'%(self.tmpPath.replace('\\','/'), OUTPUT_NAME)
header += 'eval("var ORIGIN_SIZE = " + FLfile.read("file:///%s/%s.json"));\n'%(self.tmpPath.replace('\\','/'), "originsize")
else:
header = 'eval("var JSONFILE = {};") \n'
header += 'eval("var ORIGIN_SIZE = {};") \n'
footer = "var publishFolder = '%s'; \n"%(self.mainpath.replace('\\','/'))
footer += "var tmpPath = '%s';\n"%(self.tmpPath.replace('\\','/'))
footer += """batToDo(publishFolder, tmpPath);
FLfile.write("file:///%s",FLfile.uriToPlatformPath(publishFolder) + "\\n");"""%(self.mainpath.replace('\\','/') + '/' + TMP_FOLDER_NAME + '/done')
content = header + content + footer
handle = open(self.mainpath + '/' + TMP_FOLDER_NAME + '/main.jsfl', 'w')
handle.write(content)
handle.close()
def Run(self):
self.Export()
def loadFiles():
root = MainTree(FLASH_ROOT)
return root
if __name__ == '__main__':
sysType = platform.system()
if sysType == "Darwin":
sysOpen = "open"
elif sysType == "Windows":
sysOpen = "start"
CONVERT_PATH = SCRIPT_PATH + SEP + 'convert.exe '
else:
raise CmdError, 'System not support: %s'%sysType
root = loadFiles()
root.Run()