-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBaK.py
1701 lines (1466 loc) · 62.8 KB
/
BaK.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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import functools
import itertools
import math
import pprint
import statistics
import struct
import sys
import time
import tkinter
import tkinter.font
import tkinter.ttk
import PIL.Image
import PIL.ImageTk
import PIL.ImageOps
import PIL.ImageChops
import matplotlib.pyplot as plt
import matplotlib.patches as pch
import numpy as np
def Dynamix_LZW(length, compressed):
dict_table = []
code_size = 0
cache_bits = 0
dict_full = False
code_cur = []
dict_max = 0
def Dynamix_LZW_reset():
nonlocal dict_table
nonlocal code_size
nonlocal cache_bits
nonlocal dict_full
nonlocal code_cur
nonlocal dict_max
dict_table = [bytes([x]) for x in range(256)]
dict_table.append(None) # 0x100 is reset code
code_size = 9
cache_bits = 0
dict_full = False
code_cur = []
dict_max = 0x200
bitarray = ''.join(["{:08b}".format(x) for x in compressed[::-1]])
buf_out = []
Dynamix_LZW_reset()
while len(buf_out) < length:
code = int(bitarray[-code_size:], 2)
bitarray = bitarray[:-code_size]
if code == 0xFFFFFFFF:
return buf_out
cache_bits = cache_bits + code_size
if cache_bits >= code_size * 8:
cache_bits = cache_bits - (code_size * 8)
if code == 0x100:
if cache_bits > 0:
bitarray = bitarray[:-((code_size * 8) - cache_bits)]
Dynamix_LZW_reset()
continue
if code >= len(dict_table) and dict_full == False:
code_cur.append(code_cur[0])
buf_out += code_cur
else:
buf_out += dict_table[code]
code_cur.append(dict_table[code][0])
if len(code_cur) >= 2:
if dict_full == False:
if len(dict_table) == dict_max and code_size == 12:
dict_full = True
else:
cache_bits = 0
if len(dict_table)+1 == dict_max and code_size < 12:
dict_max = dict_max * 2
code_size = code_size + 1
dict_table.append(code_cur)
code_cur = list(dict_table[code])
return buf_out
# Oddly this is the same compression scheme used by Chrono Trigger
def Dynamix_LZSS(length, compressed):
buf_out = []
while len(buf_out) < length:
header = compressed.pop(0)
for b in "{:08b}".format(header)[::-1]:
if b == "1":
buf_out.append(compressed.pop(0))
else:
offset, = struct.unpack("<H", compressed[:2])
run_length = compressed[2] + 5
del compressed[:3]
buf_out += buf_out[offset:offset+run_length]
if len(buf_out) >= length:
break
return buf_out
def Dynamix_RLE(length, compressed):
buf_out = []
while len(buf_out) < length:
header = compressed.pop(0)
if header & 0x80:
buf_out += [ compressed.pop(0) ] * (header & 0x7f)
else:
buf_out += compressed[:header]
del compressed[:header]
return buf_out
#TODO change index to BufferedReader
def LoadTags(raw):
index = 0
tags = {}
while index < len(raw):
label, size = struct.unpack("<4sI", raw[index:index+8])
index = index + 8
if size & 0x80000000:
size = size & ~0x80000000
tags[label[:-1].decode()] = LoadTags(raw[index:index+size])
else:
tags[label[:-1].decode()] = raw[index:index+size]
index = index + size
return tags
def LoadTagFNT(FNT):
index = 0
format = "<HBBBBHBI"
format_size = struct.calcsize(format)
_, height, _, first, count, _, compression, size = struct.unpack(format, FNT[index:index+format_size])
index = index + format_size
if compression != 1:
print("Unsupported compression", compression)
return None
raw = bytes(Dynamix_RLE(size, bytearray(FNT[index:])))
glyphs = []
for i in range(count):
offset, = struct.unpack("<H", raw[i*2:i*2+2])
width, = struct.unpack("<B", raw[count*2+i:count*2+i+1])
if width <= 8:
format = ">B"
format_size = 1
else:
format = ">H"
format_size = 2
glyph = []
for j in range(height):
line, = struct.unpack(format, raw[count*3+offset+j*format_size:count*3+offset+j*format_size+format_size])
if width <= 8: line = line << 8
glyph.append(line)
glyphs.append(glyph)
return glyphs
def LoadTagINF(INF):
index = 0
count, = struct.unpack("<H", INF[index:index+2])
index = index + 2 + 1
offsets = []
for _ in range(count):
offsets.append( struct.unpack("<HI", INF[index:index+6]) )
index = index + 6
return offsets
def LoadTagPAG(PAG):
index = 0
return struct.unpack("<H", PAG[index:index+2])[0]
def LoadTagPAL(PAL):
palette = {}
for k, v in PAL.items():
palette[k] = eval("LoadTag"+k+"(v)")
return palette
def LoadTagRES(RES):
index = 0
count, = struct.unpack("<H", RES[index:index+2])
index = index + 2
ress = []
for _ in range(count):
id, = struct.unpack("<H", RES[index:index+2])
index = index + 2
nul = RES.index(b'\x00', index)
res, = struct.unpack("<"+str(nul-index)+"s", RES[index:nul])
index = nul + 1
ress.append( (id, res) )
return ress
def LoadTagSCR(SCR):
index = 0
compression, = struct.unpack("<B", SCR[index:index+1])
index = index + 1
if compression != 2:
print("Unsupported compression", key, compression)
return None
screen_size, = struct.unpack("<I", SCR[index:index+4])
index = index + 4
screen = Dynamix_LZW(screen_size, SCR[index:])
return screen
def LoadTagTAG(TAG):
index = 0
count, = struct.unpack("<H", TAG[index:index+2])
index = index + 2
tags = []
for _ in range(count):
id, = struct.unpack("<H", TAG[index:index+2])
index = index + 2
nul = TAG.index(b'\x00', index)
name, = struct.unpack("<"+str(nul-index)+"s", TAG[index:nul])
index = nul + 1
tags.append( (id, name) )
return tags
def LoadTagTT3(TT3):
index = 1
tt3_size, = struct.unpack("<I", TT3[index:index+4])
index = index + 4
raw = bytes(Dynamix_RLE(tt3_size, bytearray(TT3[index:])))
raw_index = 0
chunks = []
while raw_index < len(raw):
code, = struct.unpack("<H", raw[raw_index:raw_index+2])
raw_index = raw_index + 2
csize = code & 0x000f
ccode = code & 0xfff0
chunks.append( {"code":ccode, "data":[]} )
if ccode == 0x1110 and csize == 1:
id, = struct.unpack("<H", raw[raw_index:raw_index+2])
raw_index = raw_index + 2
chunks[-1]["data"].append(id)
elif csize == 15:
nul = raw.index(b'\x00', raw_index)
name, = struct.unpack("<"+str(nul-raw_index)+"s", raw[raw_index:nul])
raw_index = nul + 1
chunks[-1]["name"] = name.decode().upper()
raw_index = raw_index + 1 if raw_index & 0x1 else raw_index
else:
for _ in range(csize):
chunks[-1]["data"].append( *struct.unpack("<h", raw[raw_index:raw_index+2]) )
raw_index = raw_index + 2
return chunks
def LoadTagTTI(TTI):
return None
def LoadTagVER(VER):
index = 0
size = len(VER)
version, = struct.unpack("<"+str(size)+"s", VER[index:index+size])
index = index + size
version = version.rstrip(b'\x00').decode()
return version
def LoadTagVGA(VGA):
palette = []
index = 0
for c in range(index, index+len(VGA), 3):
r, g, b = struct.unpack("<BBB", VGA[c:c+3])
palette.extend( [r<<2, g<<2, b<<2] )
return palette
def LoadADS(ADS):
animation = {}
for k, v in LoadTags(ADS).items():
animation[k] = eval("LoadTag"+k+"(v)")
return animation
def LoadBMX(BMX):
index = 0
format = "<HHHHI"
format_size = struct.calcsize(format)
magic, compression, image_count, data_size, raw_size = struct.unpack(format, BMX[index:index+format_size])
index = index + format_size
if magic != 0x1066:
# TODO BOOK.BMX 0x4D42
# Possibly low color hi res
print("Unsupported magic number", hex(magic))
return None
format = "<HHHH"
format_size = struct.calcsize(format)
images = []
for _ in range(image_count):
images.append( dict(zip(["data_size", "flags", "width", "height"]
, struct.unpack(format, BMX[index:index+format_size]))) )
index = index + format_size
# LZW
if compression == 0:
format = "<BI"
format_size = struct.calcsize(format)
magic, lzw_size = struct.unpack(format, BMX[index:index+format_size])
index = index + format_size
assert(magic == 0x02)
assert(raw_size == lzw_size)
raw = Dynamix_LZW(raw_size, bytearray(BMX[index:]))
elif compression == 1:
raw = Dynamix_LZSS(raw_size, bytearray(BMX[index:]))
elif compression == 2:
raw = Dynamix_RLE(raw_size, bytearray(BMX[index:]))
else:
print("Unsupported compression", compression)
return None
raw_index = 0
for image in images:
if image["flags"] & 0x20:
image["width"], image["height"] = image["height"], image["width"]
if image["flags"] & 0x80:
pixels = Dynamix_RLE(image["width"] * image["height"], bytearray(raw[raw_index:]))
else:
pixels = raw[raw_index:raw_index+image["data_size"]]
image["image"] = PIL.Image.frombytes("PA", (image["width"], image["height"])
, bytes([a for p in pixels for a in (p, p if not p else 0xff)]).ljust(image["width"] * image["height"], b'\x00'))
if image["flags"] & 0x60 == 0x60:
image["image"] = image["image"].rotate(270, expand=True)
image["width"], image["height"] = image["height"], image["width"]
image["image"] = PIL.ImageOps.mirror(image["image"])
elif image["flags"] & 0x20 == 0x20:
image["image"] = image["image"].rotate(270, expand=True)
image["width"], image["height"] = image["height"], image["width"]
elif image["flags"] & 0x40:
# Don't want to mirror if its not also rotated, don't know why
pass
raw_index = raw_index + image["data_size"]
return images
def LoadBOK(BOK):
file_size, = struct.unpack("<I", BOK[:4])
page_count, = struct.unpack("<H", BOK[4:6])
page_offsets = list(struct.unpack("<"+str(page_count)+"I", BOK[6:6+4*page_count]))
pages = []
for offset in page_offsets:
index = 4 + offset
format = "<hhhhHHHHHHHHH"
format_size = struct.calcsize(format)
( ypos, xpos, width, height, number, id, prevId, _
, nextId, flag, numDecorations, numFirstLetters
, showNumber ) = struct.unpack(format, BOK[index:index+format_size])
index = index + format_size + 30
decorations = []
for _ in range(numDecorations):
dypos, dxpos, did, dflag = struct.unpack("<hhHH", BOK[index:index+8])
decorations.append( (dypos, dxpos, did, dflag) )
index = index + 8
firstLetters = []
for _ in range(numFirstLetters):
fypos, fxpos, fid, fflag = struct.unpack("<hhHH", BOK[index:index+8])
firstLetters.append( (fypos, fxpos, fid, fflag) )
index = index + 8
EOP = BOK.index(b'\xF0', index)
text = BOK[index:index+EOP]
pages.append( (ypos, xpos, width, height, number, id, prevId
, nextId, flag, numDecorations, numFirstLetters
, showNumber, decorations, firstLetters, text) )
return pages
def LoadDDX(DDX):
found = []
def LoadBranch(DDX, offset):
index = 5 + offset
child_count, unk_count, length = struct.unpack("<BBH", DDX[index:index+4])
index = index + 4
children = []
for _ in range(child_count):
index = index + 4
type, child_offset = struct.unpack("<hI", DDX[index:index+6])
index = index + 6
children.append( (type, child_offset) )
for _ in range(child_count):
type, child_offset = children.pop(0)
if not child_offset & 0x80000000 and child_offset not in found:
found.append(child_offset)
children.append(LoadBranch(DDX, child_offset))
index = index + unk_count * 10
try:
nul = DDX.index(b'\x00', index)
except:
if index == len(DDX):
nul = index
else:
raise
text, = struct.unpack("<"+str(nul-index)+"s", DDX[index:index+(nul-index)])
return (text, children)
count, = struct.unpack("<H", DDX[:2])
index = 2
offsets = []
for _ in range(count):
id, offset = struct.unpack("<II", DDX[index:index+8])
offsets.append( (id, offset) )
index = index + 8
dialog = []
for id, offset in offsets:
dialog.append( (id, LoadBranch(DDX, offset)) )
return dialog
def LoadFNT(FNT):
glyphs = {}
for k, v in LoadTags(FNT).items():
glyphs[k] = eval("LoadTag"+k+"(v)")
return glyphs
def LoadGAM(GAM):
index = 106
format = "<IIIBBBII"
format_size = struct.calcsize(format)
yloc, xloc, _, zone, xcell, ycell, ypos, xpos = struct.unpack(format, GAM[index:index+format_size])
index = index + format_size + 5
heading = struct.unpack("<H", GAM[index:index+2])
index = index + 2 + 23
party = []
for _ in range(6):
name = struct.unpack("<10s", GAM[index:index+10])[0].rstrip(b'\x00')
index = index + 10
party.append( {"name":name} )
for i in range(6):
stats = []
index = index + 8
for _ in range(16):
stats.append(struct.unpack("<5B", GAM[index:index+5]))
index = index + 5
index = index + 7
party[i]["stats"] = stats
count, = struct.unpack("<B", GAM[index:index+1])
index = index + 1
active = struct.unpack("<"+str(count)+"B", GAM[index:index+count])
index = 0x03a7f8
for i in range(6):
unk_count, = struct.unpack("<H", GAM[index:index+2])
index = index + 2 + unk_count
items = []
item_count, slot_count = struct.unpack("<BH", GAM[index:index+3])
index = index + 3
for _ in range(slot_count):
items.append( struct.unpack("<BBH", GAM[index:index+4]) )
index = index + 4
index = index + 1
party[i]["items"] = items
return (yloc, xloc, zone, xcell, ycell, ypos, xpos, heading, party, active)
def LoadLBL(LBL):
count, = struct.unpack("<H", LBL[:2])
index = 2
labels = []
for _ in range(count):
format = "<hhhhbb"
format_size = struct.calcsize(format)
labels.append(list(struct.unpack(format, LBL[index:index+format_size])))
index = index + format_size
start = index + 2
for i in range(count):
if labels[i][0] >= 0:
index = start + labels[i][0]
nul = LBL.index(b'\x00', index)
labels[i].append(struct.unpack("<"+str(nul-index)+"s", LBL[index:index+(nul-index)])[0])
return labels
def LoadPAL(PAL):
palette = {}
for k, v in LoadTags(PAL).items():
palette[k] = eval("LoadTag"+k+"(v)")
return palette
def LoadREQ(REQ):
index = 2
format = "<h2Bhhhh2Bhh"
format_size = struct.calcsize(format)
box = struct.unpack(format, REQ[index:index+format_size])
index = index + format_size + 8
count, = struct.unpack("<H", REQ[index:index+2])
index = index + 2
data = []
for _ in range(count):
format = "<HhB6BhhHH2BhhH2BH"
format_size = struct.calcsize(format)
data.append( list(struct.unpack(format, REQ[index:index+format_size])) )
index = index + format_size + 2
start = index + 2
for i in range(count):
if data[i][15] >= 0:
index = start + data[i][15]
nul = REQ.index(b'\x00', index)
data[i].append( struct.unpack("<"+str(nul-index)+"s", REQ[index:index+(nul-index)])[0] )
return data
def LoadSCX(SCX):
width = 320
height = 200
index = 3 # Skip Magic Number 0x27b6
raw_size, = struct.unpack("<I", SCX[index:index+4])
index = index + 4
raw = Dynamix_LZW(raw_size, SCX[index:])
return PIL.Image.frombytes("PA", (width, height), bytes([a for p in raw for a in (p, p if not p else 0xff)]).ljust(width * height, b'\x00'))
def LoadSX(SX):
sound = {}
for k, v in LoadTags(SX).items():
if k == "DAT":
index = 0
format = "<HBHIH"
format_size = struct.calcsize(format)
id, type, _, raw_size, _ = struct.unpack(format, SX[index:index+format_size])
index = index + format_size
start = index
type, = struct.unpack("<B", SX[index:index+1])
index = index + 1
data = []
sounds = []
while type != 0xFF:
code, = struct.unpack("<B", SX[index:index+1])
index = index + 1
samp_offsets = []
while code != 0xFF:
index = index + 1
samp_offsets.append( struct.unpack("<HH", SX[index:index+4]) )
index = index + 4
code, = struct.unpack("<B", SX[index:index+1])
index = index + 1
voices = []
for samp_offset, samp_size in samp_offsets:
samp_offset = start + samp_offset
voices.append( SX[samp_offset:samp_offset+samp_size] )
sounds.append( voices )
type, = struct.unpack("<B", SX[index:index+1])
index = index + 1
data.append( (id, type, sounds) )
sound[k] = data
else:
sound[k] = eval("LoadTag"+k+"(v)")
return sound
def LoadTBL(TBL):
items = []
for k, v in LoadTags(TBL).items():
if k == "MAP":
index = 2
count, = struct.unpack("<H", v[index:index+2])
index = index + 2
offsets = []
for _ in range(count):
offsets.append( struct.unpack("<H", v[index:index+2])[0] )
index = index + 2
index = index + 2
start = index
for offset in offsets:
index = start + offset
nul = v.index(b'\x00', index)
items.append( {"MAP":struct.unpack("<"+str(nul-index)+"s", v[index:nul])[0].decode()} )
elif k == "APP":
pass
elif k == "GID":
index = 0
offsets = []
for _ in range(len(items)):
low, high = struct.unpack("<HH", v[index:index+4])
index = index + 4
offsets.append( (high << 4) + (low & 0xF) )
for i, offset in enumerate(offsets):
index = offset
items[i]["GID"] = dict(zip(["xradius", "yradius", "type", "count", "unknown", "unknown2"], struct.unpack("<HHBBBB", v[index:index+8])))
index = index + 8
length = sorted([n for n in offsets + [len(v)] if n > offset])[0]
items[i]["GID"]["raw"] = list(map("{:02X}".format,v[offset:length]))
if items[i]["GID"]["type"] == 0:
items[i]["GID"]["textures"] = []
for _ in range(items[i]["GID"]["count"]):
header = {"unknown":struct.unpack("<2B", v[index:index+2])}
index = index + 2
header["count"] = struct.unpack("<H", v[index:index+2])[0]
index = index + 2
header["unknown2"] = struct.unpack("<2B", v[index:index+2])
index = index + 2
items[i]["GID"]["textures"].append( {"header":header} )
for t in items[i]["GID"]["textures"]:
t["coords"] = []
for _ in range(t["header"]["count"]):
t["coords"].append(list(zip(["u", "v", "x", "y"], struct.unpack("<bbhh", v[index:index+6]))))
index = index + 6
else:
items[i]["GID"]["textures"] = ["TODO"]
elif k == "DAT":
index = 0
offsets = []
while True:
low, high = struct.unpack_from("<HH", v, index)
index += 4
offset = (high << 4) + (low & 0xF)
if not offset:
break
offsets.append( offset )
for i, offset in enumerate(offsets):
#length = sorted([n for n in offsets + [len(v)] if n > offset])[0]
#items[i]["DAT"]["raw"] = list(map("{:02X}".format,v[offset:length]))
#print( items[i]["MAP"] )
items[i]["DAT"] = dict(zip(
["flags", "type", "terrain", "scale"]
, struct.unpack_from("<BBBB", v, offset + 0)))
items[i]["DAT"] |= dict(zip(
["animation count", "animation offset"]
, struct.unpack_from("<HH", v, offset + 4)))
# All offsets are themselves offset from the base offset
items[i]["DAT"] |= dict(zip(
["model count", "base offset", "u1", "u2"]
, struct.unpack_from("<HH2B", v, offset + 8)))
if not items[i]["DAT"]["flags"] & 0x20: # UNBOUNDED
minx, miny, minz, maxx, maxy, maxz = struct.unpack_from(
"<hhhhhh"
, v
, offset + 14 )
items[i]["DAT"] |= {
"min":(minx, miny, minz)
, "max":(maxx, maxy, maxz) }
for j in range( items[i]["DAT"]["model count"] ):
items[i]["DAT"].setdefault("model", []).append( dict(zip(
["u1", "u2", "mesh count", "mesh offset"]
, struct.unpack_from(
"<2BHH"
, v
, offset + 14
+ ( 12 if not items[i]["DAT"]["flags"] & 0x20 else 0 )
+ ( j * 6 ) ))) )
# all offsets are from the start of the model table
offset += 14 + ( 12 if not items[i]["DAT"]["flags"] & 0x20 else 0 )
for j in range( items[i]["DAT"]["animation count"] ):
items[i]["DAT"].setdefault("animation", []).append( dict(zip(
["u1", "u2", "u3", "u4", "u5", "u6", "u7", ]
, struct.unpack_from(
"<7B"
, v
, offset
+ items[i]["DAT"]["animation offset"]
- items[i]["DAT"]["base offset"]
+ ( j * 7 ) ))) )
if 'model' not in items[i]["DAT"]:
continue
for model in items[i]["DAT"]["model"]:
for j in range( model[ "mesh count" ] ):
model.setdefault("mesh", []).append( dict(zip(
[ "u1"
, "u2"
, "u3"
, "vertex count"
, "vertex offset"
, "face count"
, "face offset"
, "u4"
, "u5"
, "u6"
, "u7" ]
, struct.unpack_from(
"<3BBHHH4B"
, v
, offset
+ model[ "mesh offset" ]
- items[i]["DAT"]["base offset"]
+ ( j * 14 ) ))) )
def chain_siblings( siblings, parent ):
return functools.reduce(
lambda l, k: itertools.chain( *[ v.get(k, []) for v in l ] )
, siblings
, parent )
vertex_set = {
( mesh["vertex count"], mesh["vertex offset"] )
for mesh in chain_siblings( [ "mesh" ], items[i]["DAT"]["model"] ) }
vertex = {}
for vcount, voffset in vertex_set:
vertex[ voffset ] = []
for j in range( vcount ):
vertex[ voffset ].append( struct.unpack_from(
"<hhh"
, v
, offset
+ voffset
- items[i]["DAT"]["base offset"]
+ ( j * 6 ) ) )
for mesh in chain_siblings( [ "mesh" ], items[i]["DAT"]["model"] ):
if items[i]["DAT"]["terrain"] and not items[i]["DAT"]["scale"]: # FIELD
mesh["pos"] = vertex[ mesh[ "vertex offset" ] ][0]
for j in range( mesh[ "face count" ] ):
mesh.setdefault("face", []).append( dict(zip(
[ "type"
, "edge count"
, "edge offset"
, "u1"
, "u2" ]
, struct.unpack_from(
"<HHH2B"
, v
, offset
+ mesh[ "face offset" ]
- items[i]["DAT"]["base offset"]
+ ( j * 8 ) ))) )
for face in chain_siblings( [ "mesh", "face" ], items[i]["DAT"]["model"] ):
if face[ "type" ] == 0:
for j in range( face[ "edge count" ] ):
face.setdefault("edge", []).append( dict(zip(
[ "u1"
, "color1"
, "color2"
, "color3"
, "color4"
, "group"
, "vertex offset" ]
, struct.unpack_from(
"<B4BBH"
, v
, offset
+ face[ "edge offset" ]
- items[i]["DAT"]["base offset"]
+ ( j * 8 ) ))) )
for edge in chain_siblings( [ "mesh", "face", "edge" ], items[i]["DAT"]["model"] ):
nul = v.index( b'\xFF', offset + edge["vertex offset"] - items[i]["DAT"]["base offset"] )
edge[ "vertex" ] = struct.unpack_from(
"<"+str( nul - ( offset + edge["vertex offset"] - items[i]["DAT"]["base offset"] ) )+"B"
, v
, offset
+ edge["vertex offset"]
- items[i]["DAT"]["base offset"]
)
# convert vertex indexes to vertices
for mesh in chain_siblings( [ "mesh" ], items[i]["DAT"]["model"] ):
for edge in chain_siblings( [ "edge" ], mesh[ "face" ] ):
edge[ "vertex" ] = [
vertex[ mesh[ "vertex offset" ] ][p]
for p in edge[ "vertex" ] ]
elif face[ "type" ] == 2:
items[i]["DAT"]["sprite"] = face[ "edge count" ]
return items
def LoadTTM(TTM):
movie = {}
for k, v in LoadTags(TTM).items():
movie[k] = eval("LoadTag"+k+"(v)")
return movie
def LoadWLD(WLD):
index = 0
world = []
while index < len(WLD):
world.append( dict(zip(["type", "xrot", "yrot", "zrot", "xloc", "yloc", "zloc"]
, struct.unpack("<HHHHIII", WLD[index:index+20]))) )
index = index + 20
return world
class Movie(object):
def __init__(self, tk, surface, scale, ttm, canvas):
self.tk = tk
self.surface = surface
self.scale = scale
self.ttm = LoadTTM(resources[ttm])
self.canvas = canvas
self.rect = None
self.backbuffer = PIL.Image.new("PA", (320, 200))
self.frontbuffer = PIL.Image.new("PA", (320, 200))
self.frontpalette = None
self.saved = None
self.sprites = {}
self.sprite = None
self.palettes = {}
self.palette = None
self.screen = None
self.snippet = None
self.delay = 0
self.index = 0
self.render_queue = []
self.fadeby = None
def Render(self):
if self.saved: self.backbuffer.paste(self.saved)
if self.snippet: self.backbuffer.paste(self.snippet, (self.snippetX, self.snippetY))
for r, x, y in self.render_queue:
if r:
self.backbuffer.paste(r, (x, y), r.getchannel("A"))
def Flip(self):
self.frontbuffer.paste(self.backbuffer)
if self.palette in self.palettes: self.frontpalette = self.palettes[self.palette].copy()
def Refresh(self):
if self.frontpalette: self.frontbuffer.putpalette(self.frontpalette)
self.surface.paste(self.frontbuffer.convert("RGB").resize((320*self.scale, 200*self.scale)))
def Next(self):
while self.index < len(self.ttm["TT3"]):
chunk = self.ttm["TT3"][self.index]
if chunk["code"] == 0x0020: # SAVE_BACKGROUND
print("save bg")
self.Render()
if not self.saved: self.saved = PIL.Image.new("PA", (320, 200))
self.saved.paste(self.backbuffer)
pass
elif chunk["code"] == 0x0080: # DRAW_BACKGROUND
print("draw bg")
pass
elif chunk["code"] == 0x0110: # PURGE
print("pruge")
self.saved = None
self.snippet = None
pass
elif chunk["code"] == 0x0ff0: # UPDATE
print("update")
self.Render()
self.Flip()
self.Refresh()
self.render_queue.clear()
if self.delay:
print("***done")
tk.after(self.delay, self.Next)
self.index = self.index + 1
break
#self.index = self.index + 1
#break
pass
elif chunk["code"] == 0x1020: # DELAY
print("set delay")
self.delay = chunk["data"][0] * 10
pass
elif chunk["code"] == 0x1050: # SLOT_IMAGE
print("pick sprite", hex(chunk["data"][0]))
self.sprite = chunk["data"][0]
pass
elif chunk["code"] == 0x1060: # SLOT_PALETTE
print("pick palette")
self.palette = chunk["data"][0]
pass
elif chunk["code"] == 0x1110: # SET_SCENE
print("scene", list(map(hex, chunk["data"])), chunk.get("name", None))
pass
elif chunk["code"] in (0x2000, 0x2010): # SET_FRAME01
print("frame", list(map(hex, chunk["data"])), chunk.get("name", None))
pass
elif chunk["code"] == 0x4000: # CROP
print("crop")
# may not need to crop if it's always masked anyway
x, y, w, h = chunk["data"]
self.canvas.create_rectangle( (x*self.scale, y*self.scale, w*self.scale, h*self.scale), outline="Red")
elif chunk["code"] == 0x4110: # FADE_OUT
first, number, steps, delay = chunk["data"]
if self.frontpalette is None:
print("fade out")
print("no palette")
print("***done")
self.index = self.index + 1
tk.after(delay, self.Next)
break
if self.fadeby is None:
print("fade out")
self.fadeto = [0] * number*3
self.fade = self.frontpalette[first*3:(first+number)*3]
percent = 1 / (64 << (steps & 0xf))
self.fadeby = [c * percent for c in self.fade]
self.fade = [c - p for c, p in zip(self.fade, self.fadeby)]
self.frontpalette[first*3:(first+number)*3] = [max(t, int(c)) for c, t in zip(self.fade, self.fadeto)]
self.Refresh()
if all(v == t for v, t in zip(self.fade, self.fadeto)):
print("***done")
self.fadeto = None
self.fadeby = None
self.fade = None
self.index = self.index + 1
#else:
tk.after(delay, self.Next)
break
pass
elif chunk["code"] == 0x4120: # FADE_IN
first, number, steps, delay = chunk["data"]
if self.frontpalette is None:
print("fade in")
print("no palette")
print("***done")
self.index = self.index + 1
tk.after(delay, self.Next)
break
if self.fadeby is None:
print("fade in")
self.Render()
self.Flip()
self.fadeto = self.frontpalette[first*3:(first+number)*3]
self.fade = [0] * number*3
percent = 1 / (64 << (steps & 0xf))
self.fadeby = [c * percent for c in self.fadeto]
self.fade = [c + p for c, p in zip(self.fade, self.fadeby)]
self.frontpalette[first*3:(first+number)*3] = [min(t, int(c)) for c, t in zip(self.fade, self.fadeto)]
self.Refresh()
if all(v == t for v, t in zip(self.fade, self.fadeto)):
print("***done")
self.fadeto = None
self.fadeby = None
self.fade = None
self.index = self.index + 1
#else:
tk.after(delay, self.Next)
break
pass
elif chunk["code"] in (0x4200, 0x4210): # SAVE_IMAGE01
print("snippet")
self.snippetX, self.snippetY, w, h = chunk["data"]
self.snippet = self.backbuffer.crop( (self.snippetX, self.snippetY, w, h) )
pass
elif chunk["code"] == 0xa100: # ERASE
print("erase")
if self.saved: self.saved.paste(0x00, (chunk["data"][0], chunk["data"][1], chunk["data"][0]+chunk["data"][2], chunk["data"][1]+chunk["data"][3]))
pass
elif chunk["code"] in (0xa500, 0xa510, 0xa520, 0xa530, 0xa5a0): # DRAW_SPRITE0123
if chunk["data"][3] in self.sprites and chunk["data"][2] < len(self.sprites[chunk["data"][3]]):
print("draw sprite", hex(chunk["code"]), hex(self.sprites[chunk["data"][3]][chunk["data"][2]]["flags"]))
sprite = self.sprites[chunk["data"][3]][chunk["data"][2]]["image"]
#TODO
# backgrounds are mirrored
# temple symbols are mirrored
# C11B mirrored
# char sprites are mirrored
if chunk["code"] & 0x0010:
sprite = PIL.ImageOps.flip(sprite)
if chunk["code"] & 0x0020:
sprite = PIL.ImageOps.mirror(sprite)
if chunk["code"] & 0x0080:
print("unknown flag 0x0080", hex(chunk["data"][-1]))
if len(chunk["data"]) > 4:
sprite = sprite.resize( (chunk["data"][4], chunk["data"][5]), resample=PIL.Image.NEAREST )
self.render_queue.append( (sprite, chunk["data"][0], chunk["data"][1]) )