-
Notifications
You must be signed in to change notification settings - Fork 3
/
bmd.py
2085 lines (1860 loc) · 79.4 KB
/
bmd.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 sys
from struct import unpack, pack, Struct, error as StructError
from warnings import warn
from array import array
import math
from enum import Enum, IntEnum
from common import *
from texture import *
from mathutils import *
from bti import Image
bbStruct = Struct('>fff')
stringTableHeaderStruct = Struct('>H2x')
stringTableEntryStruct = Struct('>HH')
def readStringTable(pos, f):
dest = []
oldPos = f.tell()
f.seek(pos)
count, = stringTableHeaderStruct.unpack(f.read(4))
for i in range(count):
keyCode, stringOffset = stringTableEntryStruct.unpack(f.read(4))
s = getString(pos + stringOffset, f)
dest.append(s)
f.seek(oldPos)
return dest
def stringTableSize(strings):
return stringTableHeaderStruct.size+(len(strings)*stringTableEntryStruct.size)+sum([len(s.encode('shift-jis'))+1 for s in strings])
def writeStringTable(f, strings):
f.write(stringTableHeaderStruct.pack(len(strings)))
table = bytes()
offsets = []
strings = [s.encode('shift-jis') for s in strings]
for s in strings:
offsets.append(len(table)+stringTableHeaderStruct.size)
table += s+b'\0'
for s, offset in zip(strings, offsets):
f.write(stringTableEntryStruct.pack(calcKeyCode(s), offset+len(offsets)*stringTableEntryStruct.size))
f.write(table)
class DrawBlock(Section):
header = Struct('>H2xLL')
fields = [
'count',
'offsetToIsWeighted',
'offsetToData'
]
def read(self, fin, start, size):
super().read(fin, start, size)
fin.seek(start+self.offsetToIsWeighted)
self.offsetToIsWeighted = None
bisWeighted = array('B')
bisWeighted.fromfile(fin, self.count)
if not all([x in (0,1) for x in bisWeighted]):
raise Exception("unexpected value in isWeighted array: %s", bisWeighted)
self.isWeighted = list([x == 1 for x in bisWeighted])
fin.seek(start+self.offsetToData)
self.offsetToData = None
self.data = array('H')
self.data.fromfile(fin, self.count)
self.count = None
if sys.byteorder == 'little': self.data.byteswap()
def write(self, fout):
self.count = len(self.data)
self.offsetToIsWeighted = self.header.size+8
self.offsetToData = self.offsetToIsWeighted+self.count
super().write(fout)
bisWeighted = array('B', self.isWeighted)
bisWeighted.tofile(fout)
swapArray(self.data).tofile(fout)
class EnvelopBlock(Section):
header = Struct('>H2xIIII')
fields = [
'count',
'boneCountOffset',
'weightedIndicesOffset',
'boneWeightsTableOffset',
'matrixTableOffset'
]
def read(self, fin, start, size):
super().read(fin, start, size)
fin.seek(start+self.boneCountOffset)
self.boneCountOffset = None
counts = array('B')
counts.fromfile(fin, self.count)
fin.seek(start+self.weightedIndicesOffset)
self.weightedIndicesOffset = None
self.weightedIndices = [array('H') for i in range(self.count)]
for i in range(self.count):
self.weightedIndices[i].fromfile(fin, counts[i])
if sys.byteorder == 'little': self.weightedIndices[i].byteswap()
#numMatrices = max(list(map(max, self.weightedIndices)))+1 if self.count > 0 else 0
fin.seek(start+self.boneWeightsTableOffset)
self.boneWeightsTableOffset = None
self.weightedWeights = [array('f') for i in range(self.count)]
for i in range(self.count):
self.weightedWeights[i].fromfile(fin, counts[i])
if sys.byteorder == 'little': self.weightedWeights[i].byteswap()
self.count = None
fin.seek(start+self.matrixTableOffset)
self.matrixTableOffset = None
self.matrices = []
while fin.tell() <= start+size-0x30:
m = Matrix()
for j in range(3):
m[j] = unpack('>ffff', fin.read(16))
self.matrices.append(m)
def write(self, fout):
self.count = len(self.weightedIndices)
if self.count != len(self.weightedWeights): raise ValueError()
self.boneCountOffset = self.header.size+8
self.weightedIndicesOffset = self.boneCountOffset+self.count
self.boneWeightsTableOffset = alignOffset(self.weightedIndicesOffset+(2*sum(map(len, self.weightedIndices))))
self.matrixTableOffset = alignOffset(self.boneWeightsTableOffset+(4*sum(map(len, self.weightedWeights))))
super().write(fout)
counts = array('B', map(len, self.weightedIndices))
counts.tofile(fout)
for indices in self.weightedIndices:
swapArray(indices).tofile(fout)
alignFile(fout)
for weights in self.weightedWeights:
swapArray(weights).tofile(fout)
alignFile(fout)
for m in self.matrices:
for row in m[:3]:
fout.write(pack('>ffff', *row))
class ModelHierarchy(ReadableStruct):
header = Struct('>HH')
fields = ["type", "index"]
class ModelInfoBlock(Section):
header = Struct('>H2xIII')
fields = [
'loadFlags',
'mtxGroupCount',
'vertexCount',
'offsetToEntries'
]
def read(self, fin, start, size):
super().read(fin, start, size)
fin.seek(start+self.offsetToEntries)
self.offsetToEntries = None
self.scenegraph = []
n = ModelHierarchy()
n.read(fin)
while n.type != 0:
self.scenegraph.append(n)
n = ModelHierarchy()
n.read(fin)
def write(self, fout):
self.offsetToEntries = self.header.size+8
super().write(fout)
for n in self.scenegraph:
n.write(fout)
fout.write(b'\0\0\0\0')
class SceneGraph(object):
def __init__(self):
self.children = []
self.type = 0
self.index = 0
def to_dict(self, bmd=None):
d = {'children': [c.to_dict(bmd) for c in self.children],
'type': self.type,
'index': self.index}
if bmd is not None:
if self.type == 0x10:
# joint
d['frame'] = bmd.jnt1.frames[self.index]
elif self.type == 0x11:
# material
d['material'] = bmd.mat3.materials[self.index]
elif self.type == 0x12:
# shape
d['batch'] = bmd.shp1.batches[self.index]
return d
def copy(self):
sg = SceneGraph()
sg.children = [c.copy() for c in self.children]
sg.type = self.type
sg.index = self.index
return sg
def to_array(self):
m = ModelHierarchy()
m.type = self.type
m.index = self.index
l = [m]
if len(self.children) > 0:
m = ModelHierarchy()
m.type = 1
m.index = 0
l.append(m)
for c in self.children:
l.extend(c.to_array())
m = ModelHierarchy()
m.type = 2
m.index = 0
l.append(m)
return l
INVALID_INDEX = 0xFFFF
def buildSceneGraph(inf1, sg, j=0):
i = j
while i < len(inf1.scenegraph):
n = inf1.scenegraph[i]
if n.type == 1:
i += buildSceneGraph(inf1, sg.children[-1], i + 1)
elif n.type == 2:
return i - j + 1
elif n.type == 0x10 or n.type == 0x11 or n.type == 0x12:
t = SceneGraph()
t.type = n.type
t.index = n.index
sg.children.append(t)
else:
warn("buildSceneGraph(): unexpected node type %d"%n.type)
i += 1
# remove dummy node at root
if len(sg.children) == 1:
sg = sg.children[0]
else:
sg.type = sg.index = INVALID_INDEX
warn("buildSceneGraph(): Unexpected size %d"%len(sg.children))
return 0
class JointBlock(Section):
header = Struct('>H2xIII')
fields = [
'count',
'jntEntryOffset',
'remapTableOffset',
'stringTableOffset'
]
def read(self, fin, start, size):
super().read(fin, start, size)
boneNames = readStringTable(start+self.stringTableOffset, fin)
if len(boneNames) != self.count: warn("number of strings doesn't match number of joints")
fin.seek(start+self.jntEntryOffset)
self.jntEntryOffset = None
self.matrices = [Matrix() for i in range(self.count)]
for m in self.matrices:
m.zero()
self.isMatrixValid = [False]*self.count
self.frames = []
for i in range(self.count):
f = Jnt1Entry()
f.read(fin)
f.name = boneNames[i]
self.frames.append(f)
fin.seek(start+self.remapTableOffset)
self.remapTableOffset = None
self.remapTable = array('H')
self.remapTable.fromfile(fin, self.count)
self.count = None
if sys.byteorder == 'little': self.remapTable.byteswap()
def write(self, fout):
self.count = len(self.frames)
if self.count != len(self.matrices): raise ValueError()
self.jntEntryOffset = self.header.size+8
self.remapTableOffset = self.jntEntryOffset+(self.count*(Jnt1Entry.header.size+bbStruct.size+bbStruct.size))
self.stringTableOffset = alignOffset(self.remapTableOffset+len(self.remapTable)*self.remapTable.itemsize)
super().write(fout)
for f in self.frames:
f.write(fout)
swapArray(self.remapTable).tofile(fout)
alignFile(fout)
writeStringTable(fout, [f.name for f in self.frames])
class Jnt1Entry(Readable):
header = Struct('>HBxfffhhh2xffff')
def __init__(self, name=None, scale=None, rotation=None, translation=None):
if name is not None: self.name = name
if scale is not None: self.scale = scale
if rotation is not None: self.rotation = rotation
if translation is not None: self.translation = translation
def read(self, fin):
self.flags, self.calcFlags, \
sx, sy, sz, \
rx, ry, rz, \
tx, ty, tz, \
self.boundingSphereRadius = self.header.unpack(fin.read(40))
self.scale = Vector((sx, sy, sz))
self.rotation = Euler((rx*math.pi/0x8000, ry*math.pi/0x8000, rz*math.pi/0x8000))
self.translation = Vector((tx, ty, tz))
self.bbMin = bbStruct.unpack(fin.read(bbStruct.size))
self.bbMax = bbStruct.unpack(fin.read(bbStruct.size))
def write(self, fout):
fout.write(self.header.pack(
self.flags, self.calcFlags,
self.scale.x, self.scale.y, self.scale.z,
round(self.rotation.x*0x8000/math.pi),
round(self.rotation.y*0x8000/math.pi),
round(self.rotation.z*0x8000/math.pi),
self.translation.x, self.translation.y, self.translation.z,
self.boundingSphereRadius
))
fout.write(bbStruct.pack(*self.bbMin))
fout.write(bbStruct.pack(*self.bbMax))
def __repr__(self):
return "{}({}, {}, {}, {})".format(__class__.__name__, repr(self.name), self.scale, self.rotation, self.translation)
class IndTexOrder(ReadableStruct):
header = Struct('BBxx')
fields = ["texCoordId", "texture"]
class IndTexMtx(Readable):
def read(self, fin):
p = unpack('>6f', fin.read(0x18))
self.exponent, = unpack('bxxx', fin.read(4))
scale = 2**self.exponent
self.m = [
p[0]*scale, p[1]*scale, p[2]*scale, scale,
p[3]*scale, p[4]*scale, p[5]*scale, 0.0
]
def write(self, fout):
scale = 2**self.exponent
p = [
self.m[0]/scale, self.m[1]/scale, self.m[2]/scale,
self.m[4]/scale, self.m[5]/scale, self.m[6]/scale
]
fout.write(pack('>6f', *p))
fout.write(pack('Bxxx', self.exponent))
class IndTexCoordScale(ReadableStruct):
header = Struct('BBxx')
fields = ["scaleS", "scaleT"]
class IndTevStage(ReadableStruct):
header = Struct('BBBBBBBBBxxx')
fields = ["indTexId", "format", "bias", "mtxId", "wrapS", "wrapT", "addPrev", ("unmodifiedTexCoordLod", bool), "alphaSel"]
class IndInitData(ReadableStruct):
header = Struct('BBxx')
fields = [("hasIndirect", bool), "indTexStageNum"]
def read(self, fin):
super().read(fin)
self.indTexOrder = [IndTexOrder(fin) for i in range(4)]
self.indTexMtx = [IndTexMtx(fin) for i in range(3)]
self.indTexCoordScale = [IndTexCoordScale(fin) for i in range(4)]
self.indTevStage = [IndTevStage(fin) for i in range(16)]
def write(self, fout):
super().write(fout)
for x in self.indTexOrder: x.write(fout)
for x in self.indTexMtx: x.write(fout)
for x in self.indTexCoordScale: x.write(fout)
for x in self.indTevStage: x.write(fout)
def __eq__(self, other):
return super().__eq__(other) and \
self.indTexOrder == other.indTexOrder and \
self.indTexMtx == other.indTexMtx and \
self.indTexCoordScale == other.indTexCoordScale and \
self.indTevStage == other.indTevStage
class CullMode(Enum):
NONE = 0 # Do not cull any primitives.
FRONT = 1 # Cull front-facing primitives.
BACK = 2 # Cull back-facing primitives.
ALL = 3 # Cull all primitives.
class ColorSrc(Enum):
REG = 0
VTX = 1
class DiffuseFunction(Enum):
NONE = 0
SIGN = 1
CLAMP = 2
def _SHIFTL(v, s, w):
"""mask the first w bits of v before lshifting"""
return (v & ((0x01 << w) - 1)) << s
def _SHIFTR(v, s, w):
"""rshift v and mask the first w bits afterwards"""
return (v >> s) & ((0x01 << w) - 1)
class ColorChanInfo(ReadableStruct):
header = Struct('>BBBBBB2x')
fields = [
("lightingEnabled", bool),
("matColorSource", ColorSrc),
"litMask",
("diffuseFunction", DiffuseFunction),
"attenuationFunction",
("ambColorSource", ColorSrc)
]
def getId(self):
difffn = DiffuseFunction.NONE if self.attenuationFunction==0 else self.diffuseFunction
return (self.matColorSource.value&1)|\
(_SHIFTL(self.lightingEnabled,1,1))|\
(_SHIFTL(self.litMask,2,4))|\
(_SHIFTL(self.ambColorSource.value,6,1))|\
(_SHIFTL(difffn.value,7,2))|\
(_SHIFTL(((2-self.attenuationFunction)>0),9,1))|\
(_SHIFTL((self.attenuationFunction>0),10,1))|\
(_SHIFTL((_SHIFTR(self.litMask,4,4)),11,4))
class LightInfo(ReadableStruct):
header = Struct('>ffffffBBBBffffff')
fields = [
'x', 'y', 'z',
'dx', 'dy', 'dz',
'r', 'g', 'b', 'a',
'a0', 'a1', 'a2',
'k0', 'k1', 'k2'
]
def read(self, fin):
super().read(fin)
self.pos = (self.x, self.y, self.z)
self.dir = (self.dx, self.dy, self.dz)
self.color = (self.r, self.g, self.b, self.a)
def write(self, fout):
self.x, self.y, self.z = self.pos
self.dx, self.dy, self.dz = self.dir
self.r, self.g, self.b, self.a = self.color
super().write(fout)
class TexGenType(IntEnum):
MTX3x4 = 0
MTX2x4 = 1
BUMP0 = 2
BUMP1 = 3
BUMP2 = 4
BUMP3 = 5
BUMP4 = 6
BUMP5 = 7
BUMP6 = 8
BUMP7 = 9
SRTG = 10
class TexGenSrc(IntEnum):
POS = 0
NRM = 1
BINRM = 2
TANGENT = 3
TEX0 = 4
TEX1 = 5
TEX2 = 6
TEX3 = 7
TEX4 = 8
TEX5 = 9
TEX6 = 10
TEX7 = 11
TEXCOORD0 = 12
TEXCOORD1 = 13
TEXCOORD2 = 14
TEXCOORD3 = 15
TEXCOORD4 = 16
TEXCOORD5 = 17
TEXCOORD6 = 18
COLOR0 = 19
COLOR1 = 20
class TexGenMatrix(IntEnum):
PNMTX0 = 0
PNMTX1 = 3
PNMTX2 = 6
PNMTX3 = 9
PNMTX4 = 12
PNMTX5 = 15
PNMTX6 = 18
PNMTX7 = 21
PNMTX8 = 24
PNMTX9 = 27
TEXMTX0 = 30
TEXMTX1 = 33
TEXMTX2 = 36
TEXMTX3 = 39
TEXMTX4 = 42
TEXMTX5 = 45
TEXMTX6 = 48
TEXMTX7 = 51
TEXMTX8 = 54
TEXMTX9 = 57
IDENTITY = 60
DTTMTX0 = 64
DTTMTX1 = 67
DTTMTX2 = 70
DTTMTX3 = 73
DTTMTX4 = 76
DTTMTX5 = 79
DTTMTX6 = 82
DTTMTX7 = 85
DTTMTX8 = 88
DTTMTX9 = 91
DTTMTX10 = 94
DTTMTX11 = 97
DTTMTX12 = 100
DTTMTX13 = 103
DTTMTX14 = 106
DTTMTX15 = 109
DTTMTX16 = 112
DTTMTX17 = 115
DTTMTX18 = 118
DTTMTX19 = 121
DTTIDENTITY = 125
class TexCoordInfo(ReadableStruct):
header = Struct('>BBBx')
fields = [
("type", TexGenType),
("source", TexGenSrc),
("matrix", TexGenMatrix)
]
class TexMtxProjection(Enum):
MTX3x4 = 0
MTX2x4 = 1
class TexMtxInfo(ReadableStruct):
header = Struct('>BB2x')
fields = [
("projection", TexMtxProjection),
"info"
]
def read(self, fin):
super().read(fin)
self.center = unpack('>3f', fin.read(12))
self.scale = unpack('>2f', fin.read(8))
self.rotation = unpack('>h2x', fin.read(4))[0]/0x7FFF
self.translation = unpack('>2f', fin.read(8))
self.effectMatrix = unpack('>16f', fin.read(64))
def write(self, fout):
super().write(fout)
fout.write(pack('>3f', *self.center))
fout.write(pack('>2f', *self.scale))
fout.write(pack('>h2x', int(self.rotation*0x7FFF)))
fout.write(pack('>2f', *self.translation))
fout.write(pack('>16f', *self.effectMatrix))
def __repr__(self):
return super().__repr__()+", center=%s, scale=%s, rotation=%s, translation=%s, effectMatrix=%s"% \
(self.center, self.scale, self.rotation, self.translation, self.effectMatrix)
def __eq__(self, other):
return super().__eq__(other) and \
self.center == other.center and \
self.scale == other.scale and \
self.rotation == other.rotation and \
self.translation == other.translation and \
self.effectMatrix == other.effectMatrix
class ColorChannelID(Enum):
COLOR0 = 0
COLOR1 = 1
ALPHA0 = 2
ALPHA1 = 3
COLOR0A0 = 4
COLOR1A1 = 5
COLOR_ZERO = 6
ALPHA_BUMP = 7
ALPHA_BUMP_N = 8
COLOR_NULL = 0xFF
class TevOrderInfo(ReadableStruct):
header = Struct('>BBBx')
fields = [
"texCoordId",
"texMap",
("chanId", ColorChannelID)
]
class CompareType(Enum):
NEVER = 0
LESS = 1
EQUAL = 2
LEQUAL = 3
GREATER = 4
NEQUAL = 5
GEQUAL = 6
ALWAYS = 7
class AlphaOp(Enum):
AND = 0
OR = 1
XOR = 2
XNOR = 3
class AlphaCompInfo(ReadableStruct):
header = Struct('>BBBBB3x')
fields = [
("comp0", CompareType),
"ref0",
("op", AlphaOp),
("comp1", CompareType),
"ref1"
]
class BlendMode(Enum):
NONE = 0
BLEND = 1
LOGIC = 2
SUBTRACT = 3
class BlendFactor(Enum):
ZERO = 0
ONE = 1
SRCCLR = 2
INVSRCCLR = 3
SRCALPHA = 4
INVSRCALPHA = 5
DSTALPHA = 6
INVDSTALPHA = 7
class LogicOp(Enum):
CLEAR = 0
AND = 1
REVAND = 2
COPY = 3
INVAND = 4
NOOP = 5
XOR = 6
OR = 7
NOR = 8
EQUIV = 9
INV = 10
REVOR = 11
INVCOPY = 12
INVOR = 13
NAND = 14
SET = 15
class BlendInfo(ReadableStruct):
header = Struct('>BBBB')
fields = [
("blendMode", BlendMode),
("srcFactor", BlendFactor),
("dstFactor", BlendFactor),
("logicOp", LogicOp)
]
class ZModeInfo(ReadableStruct):
header = Struct('>BBBx')
fields = [
("enable", bool),
("func", CompareType),
("writeZ", bool)
]
class NBTScaleInfo(ReadableStruct):
header = Struct('>Bxxx3f')
fields = [("enable", bool), "x", "y", "z"]
class TevColorArg(Enum):
CPREV = 0 # Use the color value from previous TEV stage
APREV = 1 # Use the alpha value from previous TEV stage
C0 = 2 # Use the color value from the color/output register 0
A0 = 3 # Use the alpha value from the color/output register 0
C1 = 4 # Use the color value from the color/output register 1
A1 = 5 # Use the alpha value from the color/output register 1
C2 = 6 # Use the color value from the color/output register 2
A2 = 7 # Use the alpha value from the color/output register 2
TEXC = 8 # Use the color value from texture
TEXA = 9 # Use the alpha value from texture
RASC = 10 # Use the color value from rasterizer
RASA = 11 # Use the alpha value from rasterizer
ONE = 12
HALF = 13
KONST = 14
ZERO = 15 # Use to pass zero value
class TevOp(Enum):
ADD = 0
SUB = 1
COMP_R8_GT = 8
COMP_R8_EQ = 9
COMP_GR16_GT = 10
COMP_GR16_EQ = 11
COMP_BGR24_GT = 12
COMP_BGR24_EQ = 13
COMP_RGB8_GT = 14
COMP_RGB8_EQ = 15
class TevBias(Enum):
ZERO = 0
ADDHALF = 1
SUBHALF = 2
_HWB_COMPARE = 3
class TevScale(Enum):
SCALE_1 = 0
SCALE_2 = 1
SCALE_4 = 2
DIVIDE_2 = 3
class Register(IntEnum):
PREV = 0
REG0 = 1
REG1 = 2
REG2 = 3
class TevAlphaArg(Enum):
APREV = 0 # Use the alpha value from previous TEV stage
A0 = 1 # Use the alpha value from the color/output register 0
A1 = 2 # Use the alpha value from the color/output register 1
A2 = 3 # Use the alpha value from the color/output register 2
TEXA = 4 # Use the alpha value from texture
RASA = 5 # Use the alpha value from rasterizer
KONST = 6
ZERO = 7 # Use to pass zero value
class TevStageInfo(ReadableStruct):
header = Struct('>x4BBBBBB4BBBBBBx')
fields = [
("colorInA", TevColorArg),
("colorInB", TevColorArg),
("colorInC", TevColorArg),
("colorInD", TevColorArg),
("colorOp", TevOp),
("colorBias", TevBias),
("colorScale", TevScale),
("colorClamp", bool),
("colorRegId", Register),
("alphaInA", TevAlphaArg),
("alphaInB", TevAlphaArg),
("alphaInC", TevAlphaArg),
("alphaInD", TevAlphaArg),
("alphaOp", TevOp),
("alphaBias", TevBias),
("alphaScale", TevScale),
("alphaClamp", bool),
("alphaRegId", Register)
]
class TevKColorSel(IntEnum):
CONST_1 = 0x00 # constant 1.0
CONST_7_8 = 0x01 # constant 7/8
CONST_3_4 = 0x02 # constant 3/4
CONST_5_8 = 0x03 # constant 5/8
CONST_1_2 = 0x04 # constant 1/2
CONST_3_8 = 0x05 # constant 3/8
CONST_1_4 = 0x06 # constant 1/4
CONST_1_8 = 0x07 # constant 1/8
K0 = 0x0C # K0[RGB] register
K1 = 0x0D # K1[RGB] register
K2 = 0x0E # K2[RGB] register
K3 = 0x0F # K3[RGB] register
K0_R = 0x10 # K0[RRR] register
K1_R = 0x11 # K1[RRR] register
K2_R = 0x12 # K2[RRR] register
K3_R = 0x13 # K3[RRR] register
K0_G = 0x14 # K0[GGG] register
K1_G = 0x15 # K1[GGG] register
K2_G = 0x16 # K2[GGG] register
K3_G = 0x17 # K3[GGG] register
K0_B = 0x18 # K0[BBB] register
K1_B = 0x19 # K1[BBB] register
K2_B = 0x1A # K2[BBB] register
K3_B = 0x1B # K3[RBB] register
K0_A = 0x1C # K0[AAA] register
K1_A = 0x1D # K1[AAA] register
K2_A = 0x1E # K2[AAA] register
K3_A = 0x1F # K3[AAA] register
class TevSwapModeInfo(ReadableStruct):
header = Struct('>BB2x')
fields = ["rasSel", "texSel"]
class TevSwapModeTableInfo(ReadableStruct):
header = Struct('>BBBB')
fields = ["rSel", "gSel", "bSel", "aSel"]
class FogInfo(ReadableStruct):
header = Struct('>BBHffff')
fields = ["type", "enable", "center", "startz", "endz", "nearz", "farz"]
def read(self, fin):
super().read(fin)
self.color = unpack('>4B', fin.read(4))
self.table = unpack('>10H', fin.read(20))
def write(self, fout):
super().write(fout)
fout.write(pack('>4B', *self.color))
fout.write(pack('>10H', *self.table))
def __hash__(self):
return hash(super().as_tuple()+(self.color, self.table))
def __eq__(self, other):
return super().__eq__(other) and \
self.color == other.color and \
self.table == other.table
def safeGet(arr, idx):
if idx >= 0 and idx < len(arr):
return arr[idx]
else:
return None
def safeIndex(arr, val):
try:
return arr.index(val)
except ValueError:
return 0xFFFF
class Material(ReadableStruct):
header = Struct('>BBBBBBBB')
fields = ["materialMode", "cullModeIndex", "colorChanNumIndex", "texGenNumIndex",
"tevStageNumIndex", "zCompLocIndex", "zModeIndex", "ditherIndex"]
def read(self, fin):
super().read(fin)
# 0x08
self.matColorIndices = unpack('>2H', fin.read(4))
# 0x0C
self.colorChanIndices = unpack('>4H', fin.read(8))
# 0x14
self.ambColorIndices = unpack('>2H', fin.read(4))
# 0x18
self.lightInfoIndices = unpack('>8H', fin.read(16))
# 0x28
self.texCoordIndices = unpack('>8H', fin.read(16))
# 0x38
self.postTexGenIndices = unpack('>8H', fin.read(16))
# 0x48
self.texMtxIndices = unpack('>10H', fin.read(20))
# 0x5C
self.postTexMtxIndices = unpack('>20H', fin.read(40))
# 0x84
self.texNoIndices = unpack('>8H', fin.read(16))
# 0x94
self.tevKColorIndices = unpack('>4H', fin.read(8))
# 0x9C
self.tevKColorSels = [TevKColorSel(x) if x < 0x20 else x for x in unpack('>16B', fin.read(16))]
# 0xAC
self.tevKAlphaSels = [TevKColorSel(x) if x < 0x20 else x for x in unpack('>16B', fin.read(16))]
# 0xBC
self.tevOrderIndices = unpack('>16H', fin.read(32))
# 0xDC
self.tevColorIndices = unpack('>4H', fin.read(8))
# 0xE4
self.tevStageIndices = unpack('>16H', fin.read(32))
# 0x104
self.tevSwapModeIndices = unpack('>16H', fin.read(32))
# 0x124
self.tevSwapModeTableIndices = unpack('>4H', fin.read(8))
# 0x12C
self.unknownIndices6 = unpack('>12H', fin.read(24))
# 0x144
self.fogIndex, self.alphaCompIndex, self.blendIndex, self.nbtScaleIndex = unpack('>HHHH', fin.read(8))
def resolve(self, mat3):
self.cullMode = safeGet(mat3.cullModeArray, self.cullModeIndex)
self.cullModeIndex = None
self.colorChanNum = safeGet(mat3.colorChanNumArray, self.colorChanNumIndex)
self.colorChanNumIndex = None
self.texGenNum = safeGet(mat3.texGenNumArray, self.texGenNumIndex)
self.texGenNumIndex = None
self.tevStageNum = safeGet(mat3.tevStageNumArray, self.tevStageNumIndex)
self.tevStageNumIndex = None
self.zCompLoc = safeGet(mat3.zCompLocArray, self.zCompLocIndex)
self.zCompLocIndex = None
self.zMode = safeGet(mat3.zModeArray, self.zModeIndex)
self.zModeIndex = None
self.dither = safeGet(mat3.ditherArray, self.ditherIndex)
self.ditherIndex = None
self.matColors = [safeGet(mat3.matColorArray, i) for i in self.matColorIndices]
self.matColorIndices = None
self.colorChans = [safeGet(mat3.colorChanArray, i) for i in self.colorChanIndices]
self.colorChanIndices = None
self.ambColors = [safeGet(mat3.ambColorArray, i) for i in self.ambColorIndices]
self.ambColorIndices = None
self.lightInfos = [safeGet(mat3.lightInfoArray, i) for i in self.lightInfoIndices]
self.lightInfoIndices = None
self.texCoords = [safeGet(mat3.texCoordArray, i) for i in self.texCoordIndices]
self.texCoordIndices = None
self.postTexGens = [safeGet(mat3.postTexGenArray, i) for i in self.postTexGenIndices]
self.postTexGenIndices = None
self.texMtxs = [safeGet(mat3.texMtxArray, i) for i in self.texMtxIndices]
self.texMtxIndices = None
self.postTexMtxs = [safeGet(mat3.postTexMtxArray, i) for i in self.postTexMtxIndices]
self.postTexMtxIndices = None
self.texNos = [safeGet(mat3.texNoArray, i) for i in self.texNoIndices]
self.texNoIndices = None
self.tevKColors = [safeGet(mat3.tevKColorArray, i) for i in self.tevKColorIndices]
self.tevKColorIndices = None
self.tevOrders = [safeGet(mat3.tevOrderArray, i) for i in self.tevOrderIndices]
self.tevOrderIndices = None
self.tevColors = [safeGet(mat3.tevColorArray, i) for i in self.tevColorIndices]
self.tevColorIndices = None
self.tevStages = [safeGet(mat3.tevStageArray, i) for i in self.tevStageIndices]
self.tevStageIndices = None
self.tevSwapModes = [safeGet(mat3.tevSwapModeArray, i) for i in self.tevSwapModeIndices]
self.tevSwapModeIndices = None
self.tevSwapModeTables = [safeGet(mat3.tevSwapModeTableArray, i) for i in self.tevSwapModeTableIndices]
self.tevSwapModeTableIndices = None
self.fog = safeGet(mat3.fogArray, self.fogIndex)
self.fogIndex = None
self.alphaComp = safeGet(mat3.alphaCompArray, self.alphaCompIndex)
self.alphaCompIndex = None
self.blend = safeGet(mat3.blendArray, self.blendIndex)
self.blendIndex = None
self.nbtScale = safeGet(mat3.nbtScaleArray, self.nbtScaleIndex)
self.nbtScaleIndex = None
def write(self, fout):
super().write(fout)
fout.write(pack('>2H', *self.matColorIndices))
fout.write(pack('>4H', *self.colorChanIndices))
fout.write(pack('>2H', *self.ambColorIndices))
fout.write(pack('>8H', *self.lightInfoIndices))
fout.write(pack('>8H', *self.texCoordIndices))
fout.write(pack('>8H', *self.postTexGenIndices))
fout.write(pack('>10H', *self.texMtxIndices))
fout.write(pack('>20H', *self.postTexMtxIndices))
fout.write(pack('>8H', *self.texNoIndices))
fout.write(pack('>4H', *self.tevKColorIndices))
fout.write(pack('>16B', *self.tevKColorSels))
fout.write(pack('>16B', *self.tevKAlphaSels))
fout.write(pack('>16H', *self.tevOrderIndices))
fout.write(pack('>4H', *self.tevColorIndices))
fout.write(pack('>16H', *self.tevStageIndices))
fout.write(pack('>16H', *self.tevSwapModeIndices))
fout.write(pack('>4H', *self.tevSwapModeTableIndices))
fout.write(pack('>12H', *self.unknownIndices6))
fout.write(pack('>HHHH', self.fogIndex, self.alphaCompIndex, self.blendIndex, self.nbtScaleIndex))
def index(self, mat3):
self.cullModeIndex = safeIndex(mat3.cullModeArray, self.cullMode.value)
self.colorChanNumIndex = safeIndex(mat3.colorChanNumArray, self.colorChanNum)
self.texGenNumIndex = safeIndex(mat3.texGenNumArray, self.texGenNum)
self.tevStageNumIndex = safeIndex(mat3.tevStageNumArray, self.tevStageNum)
self.zCompLocIndex = safeIndex(mat3.zCompLocArray, self.zCompLoc)
self.zModeIndex = safeIndex(mat3.zModeArray, self.zMode)
self.ditherIndex = safeIndex(mat3.ditherArray, self.dither)
self.matColorIndices = [safeIndex(mat3.matColorArray, x) for x in self.matColors]
self.colorChanIndices = [safeIndex(mat3.colorChanArray, x) for x in self.colorChans]
self.ambColorIndices = [safeIndex(mat3.ambColorArray, x) for x in self.ambColors]
self.lightInfoIndices = [safeIndex(mat3.lightInfoArray, x) for x in self.lightInfos]
self.texCoordIndices = [safeIndex(mat3.texCoordArray, x) for x in self.texCoords]
self.postTexGenIndices = [safeIndex(mat3.postTexGenArray, x) for x in self.postTexGens]
self.texMtxIndices = [safeIndex(mat3.texMtxArray, x) for x in self.texMtxs]
self.postTexMtxIndices = [safeIndex(mat3.postTexMtxArray, x) for x in self.postTexMtxs]
self.texNoIndices = [safeIndex(mat3.texNoArray, x) for x in self.texNos]
self.tevKColorIndices = [safeIndex(mat3.tevKColorArray, x) for x in self.tevKColors]
self.tevOrderIndices = [safeIndex(mat3.tevOrderArray, x) for x in self.tevOrders]
self.tevColorIndices = [safeIndex(mat3.tevColorArray, x) for x in self.tevColors]
self.tevStageIndices = [safeIndex(mat3.tevStageArray, x) for x in self.tevStages]
self.tevSwapModeIndices = [safeIndex(mat3.tevSwapModeArray, x) for x in self.tevSwapModes]
self.tevSwapModeTableIndices = [safeIndex(mat3.tevSwapModeTableArray, x) for x in self.tevSwapModeTables]
self.fogIndex = safeIndex(mat3.fogArray, self.fog)
self.alphaCompIndex = safeIndex(mat3.alphaCompArray, self.alphaComp)
self.blendIndex = safeIndex(mat3.blendArray, self.blend)
self.nbtScaleIndex = safeIndex(mat3.nbtScaleArray, self.nbtScale)
def debug(self):
print(self.name)
print("materialMode =", self.materialMode)
print("cullMode =", self.cullMode)
print("colorChanNum =", self.colorChanNum)
print("texGenNum =", self.texGenNum)
print("tevStageNum =", self.tevStageNum)
print("zCompLoc =", self.zCompLoc)
print("zMode =", self.zMode)
print("dither =", self.dither)
print("matColors =", self.matColors)
print("colorChans =", self.colorChans)
print("ambColors =", self.ambColors)
print("lightInfos =", self.lightInfos)
print("texCoords =", self.texCoords)
print("postTexGens =", self.postTexGens)
print("texMtxs =", self.texMtxs)
print("postTexMtxs =", self.postTexMtxs)
print("texNos =", self.texNos)
print("tevKColors =", self.tevKColors)
print("tevKColorSels =", self.tevKColorSels)
print("tevKAlphaSels =", self.tevKAlphaSels)
print("tevOrders =", self.tevOrders)
print("tevColors =", self.tevColors)
print("tevStages =", self.tevStages)
print("tevSwapModes =", self.tevSwapModes)