This repository has been archived by the owner on Sep 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcommon.py
2035 lines (1702 loc) · 52.2 KB
/
common.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
from struct import error
import os, os.path
import bpy
import mathutils
import math
import queue
from typing import List, Dict, Tuple
from . import fileHelper, enums
DO = False # Debug Out
def get_path():
return os.path.dirname(os.path.realpath(__file__))
def get_name():
return os.path.basename(get_path())
def get_prefs():
return bpy.context.preferences.addons[get_name()].preferences
def center(p1: float, p2: float) -> float:
"""Returns the mid point between two numbers"""
return (p1 + p2) / 2.0
def hex4(number: int) -> str:
return '{:08x}'.format(number)
def RadToBAMS(v: float, asInt=False, clamp=False) -> int:
if (clamp):
if (v < 0):
v = math.radians(math.degrees(v) + 360.0)
o = int(((v) * ((65536) / ((2) * (math.pi)))))
if o < 0:
o = (o + (2**32))
return o
def BAMSToRad(v: int, shortRot=False) -> float:
if not shortRot and v & 0x80000000:
v -= 0x100000000
elif shortRot:
v &= 0xFFFF
return float(v / (65536.0 / (2 * math.pi)))
def getDistinctwID(items: list):
distinct = list()
IDs = [0] * len(items)
for i, o in enumerate(items):
found = None
for j, d in enumerate(distinct):
if o == d:
found = j
break
if found is None:
distinct.append(o)
IDs[i] = len(distinct) - 1
else:
IDs[i] = found
return distinct, IDs
class ExportError(Exception):
def __init__(self, message):
super().__init__(message)
class ColorARGB:
"""4 Channel Color (ARGB)
takes values from 0.0 - 1.0 as input and converts them to 0 - 255
"""
a: int
r: int
g: int
b: int
def __init__(self, c=(1, 1, 1, 1)):
self.a = round(c[3] * 255)
self.r = round(c[0] * 255)
self.g = round(c[1] * 255)
self.b = round(c[2] * 255)
@classmethod
def fromRGBA(cls, value: int):
col = ColorARGB()
col.r = (value >> 24) & 0xFF
col.g = (value >> 16) & 0xFF
col.b = (value >> 8) & 0xFF
col.a = value & 0xFF
return col
def writeRGBA(self, fileW):
"""writes data to file"""
fileW.wByte(self.a)
fileW.wByte(self.b)
fileW.wByte(self.g)
fileW.wByte(self.r)
@classmethod
def fromARGB(cls, value: int):
col = ColorARGB()
col.a = (value >> 24) & 0xFF
col.r = (value >> 16) & 0xFF
col.g = (value >> 8) & 0xFF
col.b = value & 0xFF
return col
def writeARGB(self, fileW):
"""writes data to file"""
fileW.wByte(self.b)
fileW.wByte(self.g)
fileW.wByte(self.r)
fileW.wByte(self.a)
def writeRGB(self, fileW):
"""writes data to file"""
fileW.wByte(self.b)
fileW.wByte(self.g)
fileW.wByte(self.r)
def toBlenderTuple(self):
return (self.r / 255.0, self.g / 255.0, self.b / 255.0, self.a / 255.0)
def isWhite(self):
return self.a == 255 \
and self.r == 255 \
and self.g == 255 \
and self.b == 255
def __eq__(self, other):
return self.a == other.a \
and self.r == other.r \
and self.g == other.g \
and self.b == other.b
def __str__(self):
return f"({self.a},{self.r},{self.g},{self.b})"
class UV:
"""A single texture coordinate
Converts from 0.0 - 1.0 range to 0 - 255 range """
x: int
y: int
def __init__(self, uv=(0.0, 0.0)):
self.x = max(-32767, min(32767, round(uv[0] * 255)))
self.y = max(-32767, min(32767, round((1-uv[1]) * 255)))
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def getBlenderUV(self):
return (self.x / 255.0, 1-(self.y / 255.0))
def write(self, fileW: fileHelper.FileWriter):
"""Writes data to file"""
fileW.wShort(self.x)
fileW.wShort(self.y)
class Vector3(mathutils.Vector):
"""Point in 3D Space"""
def length(self):
"""returns length of the vector"""
return (self.x**2 + self.y**2 + self.z**2)**(0.5)
def write(self, fileW):
"""Writes data to file"""
fileW.wFloat(self.x)
fileW.wFloat(self.y)
fileW.wFloat(self.z)
def __str__(self):
return f"({round(self.x, 3)},{round(self.y, 3)},{round(self.z, 3)})"
class BAMSRotation:
"""XYZ Rotation used for the adventure games"""
x: int
y: int
z: int
def __init__(self, val, asInt=False):
self.x = RadToBAMS(val[0], asInt=asInt)
self.y = RadToBAMS(val[1], asInt=asInt)
self.z = RadToBAMS(val[2], asInt=asInt)
def toQuaternion(self) -> mathutils.Quaternion:
return mathutils.Euler((
BAMSToRad(self.x),
BAMSToRad(self.y),
BAMSToRad(self.z)
)).to_quaternion()
def write(self, fileW: fileHelper.FileWriter):
"""Writes data to file"""
fileW.wUInt(self.x)
fileW.wUInt(self.y)
fileW.wUInt(self.z)
def __str__(self):
return (f"({round(BAMSToRad(self.x), 3)},"
f"{round(BAMSToRad(self.y), 3)},"
f"{round(BAMSToRad(self.z), 3)})")
class BoundingBox:
"""Used to calculate the bounding sphere which the game uses"""
boundCenter: Vector3
radius: float
def vecAdd(self, v1: Vector3, v2: Vector3):
return (Vector3(((v1.x + v2.x), (v1.y + v2.y), (v1.z + v2.z))))
def vecDistSquared(self, v1: Vector3, v2: Vector3):
x = (v1.x - v2.x)
y = (v1.y - v2.y)
z = (v1.z - v2.z)
return (float(((x * x) + (y * y) + (z * z))))
def __init__(self, vertices):
if vertices is None:
self.radius = 0
self.boundCenter = Vector3((0, 0, 0))
return
center = Vector3((0,0,0))
for v in vertices:
print(v.co)
vert = Vector3((v.co[0], v.co[1], v.co[2]))
print(vert)
print(center)
center = self.vecAdd((vert), (center))
center /= float(len(vertices))
radius = float(0)
for v in vertices:
vert = Vector3((v.co[0], v.co[1], v.co[2]))
distance = self.vecDistSquared(center, vert)
if (distance > radius):
radius = distance
radius = math.sqrt(radius)
self.boundCenter = center
self.radius = radius
def adjust(self, matrix: mathutils.Matrix):
self.boundCenter = matrix @ self.boundCenter
self.radius *= matrix.to_scale()[0]
def write(self, fileW):
self.boundCenter.write(fileW)
fileW.wFloat(self.radius)
def __str__(self):
return str(self.boundCenter) + " - " + str(self.radius)
class ModelData:
"""A class that holds all necessary data to export an Object/COL"""
name: str
# used for exporting the meshes in correct formats
origObject: bpy.types.Object
# the triangulated mesh
processedMesh: bpy.types.Mesh
children: list
child: "ModelData" = None
sibling: "ModelData" = None
parent: "ModelData" = None
hierarchyDepth: int
partOfArmature: bool
worldMatrix: mathutils.Matrix
position: Vector3
rotation: BAMSRotation
scale: Vector3
bounds: BoundingBox
objFlags: dict
saProps: dict
unknown1: int # sa1 COL
unknown2: int # both COL
meshPtr: int # set after writing meshes
objectPtr: int # set after writing model address
def __init__(self,
bObject: bpy.types.Object,
parent: "ModelData",
hierarchyDepth: int,
name: str,
global_matrix: mathutils.Matrix,
collision: bool = False,
visible: bool = False):
if global_matrix is None:
return
self.name = name
self.hierarchyDepth = hierarchyDepth
if parent is not None:
self.partOfArmature = isinstance(parent, Armature) \
or parent.partOfArmature
else:
self.partOfArmature = False
if bObject is not None and bObject.type == 'MESH':
# get the blender bounds
self.bounds = BoundingBox(None)
self.saProps = bObject.saSettings.toDictionary()
self.saProps['sfSolid'] = collision
self.saProps['sfVisible'] = visible
else:
self.bounds = BoundingBox(None)
self.saProps = None
self.origObject = bObject
self.objFlags = bObject.saObjflags.toDictionary()
if bObject is None:
self.worldMatrix = mathutils.Matrix.Identity(4)
else:
self.worldMatrix = bObject.matrix_world
self.children = list()
self.parent = parent
if parent is not None:
self.parent.children.append(self)
matrix = parent.worldMatrix.inverted() @ self.worldMatrix
else:
matrix = self.worldMatrix
# settings space data
obj_mat: mathutils.Matrix = global_matrix @ matrix
scale = matrix.to_scale()
rot: mathutils.Euler = matrix.to_euler('XYZ')
rot = global_matrix @ mathutils.Vector((rot.x, rot.y, rot.z))
self.position = Vector3(obj_mat.to_translation())
self.rotation = BAMSRotation(rot, asInt=True)
self.scale = Vector3((scale.x, scale.z, scale.y))
# settings the unknowns
self.unknown1 = 0
self.unknown2 = 0
self.meshPtr = None
@classmethod
def updateMeshes(cls, objList: list, meshList: list):
for o in objList:
o.processedMesh = None
if o.origObject is not None and o.origObject.type == 'MESH':
for m in meshList:
if m.name == o.origObject.data.name:
o.processedMesh = m
break
@classmethod
def updateMeshPointer(cls,
objList: list,
meshDict: dict,
cMeshDict: list = None):
"""Updates the mesh pointer of a ModelData list utilizing a meshDict"""
for o in objList:
if o.processedMesh is not None:
if cMeshDict is not None and o.saProps['sfSolid']:
o.meshPtr, bounds = cMeshDict[o.processedMesh.name]
else:
o.meshPtr, bounds = meshDict[o.processedMesh.name]
else:
o.meshPtr = 0
continue
if o.meshPtr is not None:
# now its time to rotate the point
# around the center of the object
# get matrix from rotation
rotMtx = o.rotation.toQuaternion().to_matrix().to_4x4()
o.bounds.boundCenter = rotMtx @ bounds.boundCenter
o.bounds.boundCenter += o.position
# getting the biggest scale
s = o.scale[0]
if o.scale[1] > s:
s = o.scale[1]
if o.scale[2] > s:
s = o.scale[2]
o.bounds.radius = s * bounds.radius * 1.01
def getObjectFlags(self, lvl = False) -> enums.ObjectFlags:
"""Calculates the Objectflags"""
from .enums import ObjectFlags
flags = ObjectFlags.null
if self.objFlags is None:
return flags
p = self.objFlags
if p["ignorePosition"]:
flags |= ObjectFlags.NoPosition
if p["ignoreRotation"]:
flags |= ObjectFlags.NoRotate
if p["ignoreScale"]:
flags |= ObjectFlags.NoScale
if p["rotateZYX"]:
flags |= ObjectFlags.RotateZYX
if p["skipDraw"]:
flags |= ObjectFlags.NoDisplay
if p["skipChildren"]:
flags |= ObjectFlags.NoChildren
if p["flagAnimate"]:
flags |= ObjectFlags.NoAnimate
if p["flagMorph"]:
flags |= ObjectFlags.NoMorph
# Checks for NONE object type or if no children for an object to auto-set those flags in the event the user did not set them.
if ((flags & ObjectFlags.NoDisplay) != 0):
if self.origObject.type == 'NONE':
flags |= ObjectFlags.NoDisplay
if ((flags & ObjectFlags.NoChildren) != 0):
if len(self.origObject.children) < 1:
flags |= ObjectFlags.NoChildren
return flags
def getSA1SurfaceFlags(self) -> enums.SA1SurfaceFlags:
"""Calculates SA1 COL flags"""
from .enums import SA1SurfaceFlags
flags = SA1SurfaceFlags.null
if self.saProps is None:
return flags
p = self.saProps
if p['sfVisible']:
flags |= SA1SurfaceFlags.Visible
if p['sfSolid']:
flags |= SA1SurfaceFlags.Solid
if p['sfNoAccel']:
flags |= SA1SurfaceFlags.NoAcceleration
if p['sfLowAccel']:
flags |= SA1SurfaceFlags.LowAcceleration
if p['sfAccel']:
flags |= SA1SurfaceFlags.Accelerate
if p['sfIncAccel']:
flags |= SA1SurfaceFlags.IncreasedAcceleration
if p['sfUnclimbable']:
flags |= SA1SurfaceFlags.Unclimbable
if p['sfDiggable']:
flags |= SA1SurfaceFlags.Diggable
if p['sfNoFriction']:
flags |= SA1SurfaceFlags.NoFriction
if p['sfStairs']:
flags |= SA1SurfaceFlags.Stairs
if p['sfWater']:
flags |= SA1SurfaceFlags.Water
if p['sfCannotLand']:
flags |= SA1SurfaceFlags.CannotLand
if p['sfHurt']:
flags |= SA1SurfaceFlags.Hurt
if p['sfFootprints']:
flags |= SA1SurfaceFlags.Footprints
if p['sfGravity']:
flags |= SA1SurfaceFlags.Gravity
if p['sfUseRotation']:
flags |= SA1SurfaceFlags.UseRotation
if p['sfDynCollision']:
flags |= SA1SurfaceFlags.DynamicCollision
if p['sfWaterCollision']:
flags |= SA1SurfaceFlags.WaterCollision
if p['sfUseSkyDrawDistance']:
flags |= SA1SurfaceFlags.UseSkyDrawDistance
if p['sfNoZWrite']:
flags |= SA1SurfaceFlags.NoZWrite
if p['sfLowDepth']:
flags |= SA1SurfaceFlags.LowDepth
if p['sfDrawByMesh']:
flags |= SA1SurfaceFlags.DrawByMesh
if p['sfWaterfall']:
flags |= SA1SurfaceFlags.Waterfall
if p['sfChaos0Land']:
flags |= SA1SurfaceFlags.Chaos0Land
if p['sfEnableManipulation']:
flags |= SA1SurfaceFlags.EnableManipulation
if p['sfSA1U_200']:
flags |= SA1SurfaceFlags.sa1U_200
if p['sfSA1U_800']:
flags |= SA1SurfaceFlags.sa1U_800
if p['sfSA1U_8000']:
flags |= SA1SurfaceFlags.sa1U_8000
if p['sfSA1U_20000']:
flags |= SA1SurfaceFlags.sa1U_20000
if p['sfSA1U_80000']:
flags |= SA1SurfaceFlags.sa1U_80000
if p['sfSA1U_20000000']:
flags |= SA1SurfaceFlags.sa1U_20000000
if p['sfSA1U_40000000']:
flags |= SA1SurfaceFlags.sa1U_40000000
return flags
def getSA2SurfaceFlags(self) -> enums.SA2SurfaceFlags:
"""Calculates SA2 COL flags"""
from .enums import SA2SurfaceFlags
flags = SA2SurfaceFlags.null
if self.saProps is None:
return flags
p = self.saProps
if p['sfVisible']:
flags |= SA2SurfaceFlags.Visible
if p['sfSolid']:
flags |= SA2SurfaceFlags.Solid
if p['sfNoAccel']:
flags |= SA2SurfaceFlags.NoAcceleration
if p['sfLowAccel']:
flags |= SA2SurfaceFlags.LowAcceleration
if p['sfAccel']:
flags |= SA2SurfaceFlags.Accelerate
if p['sfIncAccel']:
flags |= SA2SurfaceFlags.IncreasedAcceleration
if p['sfUnclimbable']:
flags |= SA2SurfaceFlags.Unclimbable
if p['sfDiggable']:
flags |= SA2SurfaceFlags.Diggable
if p['sfNoFriction']:
flags |= SA2SurfaceFlags.NoFriction
if p['sfStairs']:
flags |= SA2SurfaceFlags.Stairs
if p['sfWater']:
flags |= SA2SurfaceFlags.Water
if p['sfCannotLand']:
flags |= SA2SurfaceFlags.CannotLand
if p['sfHurt']:
flags |= SA2SurfaceFlags.Hurt
if p['sfFootprints']:
flags |= SA2SurfaceFlags.Footprints
if p['sfGravity']:
flags |= SA2SurfaceFlags.Gravity
if p['sfUseRotation']:
flags |= SA2SurfaceFlags.UseRotation
if p['sfDynCollision']:
flags |= SA2SurfaceFlags.DynamicCollision
if p['sfWater2']:
flags |= SA2SurfaceFlags.Water2
if p['sfNoShadows']:
flags |= SA2SurfaceFlags.NoShadows
if p['sfNoFog']:
flags |= SA2SurfaceFlags.noFog
if p['sfSA2U_40']:
flags |= SA2SurfaceFlags.sa2U_40
if p['sfSA2U_200']:
flags |= SA2SurfaceFlags.sa2U_200
if p['sfSA2U_4000']:
flags |= SA2SurfaceFlags.sa2U_4000
if p['sfSA2U_10000']:
flags |= SA2SurfaceFlags.sa2U_10000
if p['sfSA2U_20000']:
flags |= SA2SurfaceFlags.sa2U_20000
if p['sfSA2U_40000']:
flags |= SA2SurfaceFlags.sa2U_40000
if p['sfSA2U_800000']:
flags |= SA2SurfaceFlags.sa2U_800000
if p['sfSA2U_1000000']:
flags |= SA2SurfaceFlags.sa2U_1000000
if p['sfSA2U_2000000']:
flags |= SA2SurfaceFlags.sa2U_2000000
if p['sfSA2U_4000000']:
flags |= SA2SurfaceFlags.sa2U_4000000
if p['sfSA2U_20000000']:
flags |= SA2SurfaceFlags.sa2U_20000000
if p['sfSA2U_40000000']:
flags |= SA2SurfaceFlags.sa2U_40000000
return flags
@classmethod
def writeObjectList(cls,
objects: list,
fileW: fileHelper.FileWriter,
labels: dict,
lvl: bool = False):
for o in reversed(objects):
o.writeObject(fileW, labels, lvl)
return objects[0].objectPtr
def writeObject(self,
fileW: fileHelper.FileWriter,
labels: dict,
lvl: bool = False):
"""Writes object data"""
name = self.name
numberCount = 0
while name[numberCount].isdigit():
numberCount += 1
if name[numberCount] == '_':
name = name[numberCount + 1:]
else:
name = name[numberCount:]
self.objectPtr = fileW.tell()
labels[self.objectPtr] = name
fileW.wUInt(self.getObjectFlags(lvl).value)
fileW.wUInt(self.meshPtr)
self.position.write(fileW)
self.rotation.write(fileW)
self.scale.write(fileW)
fileW.wUInt(0 if self.child is None or lvl
else self.child.objectPtr)
fileW.wUInt(0 if self.sibling is None or lvl
else self.sibling.objectPtr)
def writeCOL(self, fileW: fileHelper.FileWriter, labels: dict, SA2: bool):
"""writes COL data"""
# a COL always needs a mesh
if self.meshPtr == 0:
return
# labels[fileW.tell()] = self.name
if SA2:
self.bounds.write(fileW)
fileW.wUInt(self.objectPtr)
fileW.wUInt(self.unknown2)
fileW.wUInt(int("0x" + self.saProps["blockbit"], 0))
fileW.wUInt(self.getSA2SurfaceFlags().value
| int("0x" + self.saProps["userFlags"], 0))
else:
self.bounds.write(fileW)
fileW.wUInt(self.unknown1)
fileW.wUInt(self.unknown2)
fileW.wUInt(self.objectPtr)
fileW.wUInt(int("0x" + self.saProps["blockbit"], 0))
fileW.wUInt(self.getSA1SurfaceFlags().value
| int("0x" + self.saProps["userFlags"], 0))
class ArmatureMesh:
model: ModelData
indexBufferOffset: int
weightMap: Dict[str, Tuple[int, enums.WeightStatus]]
# a weightindex of -1 indicates to write the entire mesh
# and an index of -2 means to write only unweighted vertices
def __init__(self,
model: ModelData,
indexBufferOffset: int,
weightMap: Dict[str, Tuple[int, enums.WeightStatus]]):
self.model = model
self.indexBufferOffset = indexBufferOffset
self.weightMap = weightMap
class Bone:
name: str
hierarchyDepth: int
objFlags: dict
matrix_world: mathutils.Matrix # in the world
matrix_local: mathutils.Matrix # relative to parent bone
parentBone: "Bone" = None
children: List["Bone"]
child = None
sibling = None
position: Vector3
rotation: BAMSRotation
scale: Vector3
meshPtr: int # set after writing meshes
objectPtr: int # set after writing model address
def __init__(self,
name: str,
hierarchyDepth,
armatureMatrix: mathutils.Matrix,
localMatrix: mathutils.Matrix,
exportMatrix: mathutils.Matrix,
parentBone,
objFlags: dict):
self.name = name
self.hierarchyDepth = hierarchyDepth
self.matrix_world = armatureMatrix @ localMatrix
if parentBone is not None:
self.matrix_local = parentBone.matrix_world.inverted() \
@ self.matrix_world
matrix = self.matrix_local
else: # only the root can cause this
self.matrix_local = self.matrix_world
matrix = armatureMatrix
posMatrix = exportMatrix @ matrix
self.position = Vector3(posMatrix.to_translation())
self.scale = Vector3((1, 1, 1))
rot: mathutils.Euler = matrix.to_euler('XZY')
self.rotation = BAMSRotation(
exportMatrix @ mathutils.Vector((rot.x, rot.y, rot.z)))
self.parentBone = parentBone
self.children = list()
if parentBone is not None:
parentBone.children.append(self)
self.objFlags = objFlags
@classmethod
def getBones(cls,
bBone: bpy.types.Bone,
parent: "Bone",
hierarchyDepth: int,
export_matrix: mathutils.Matrix,
armatureMatrix: mathutils.Matrix,
result: List[ModelData]):
bone = Bone(bBone.name,
hierarchyDepth,
armatureMatrix,
bBone.matrix_local,
export_matrix, parent,
bBone.saObjflags.toDictionary())
result.append(bone)
lastSibling = None
for b in bBone.children:
child = Bone.getBones(b,
bone,
hierarchyDepth + 1,
export_matrix,
armatureMatrix,
result)
if lastSibling is not None:
lastSibling.sibling = child
lastSibling = child
# update sibling relationship
if len(bone.children) > 0:
bone.child = bone.children[0]
return bone
def write(self, fileW: fileHelper.FileWriter, labels: dict):
"""Writes bone data in form of object data"""
name = self.name
numberCount = 0
while name[numberCount].isdigit():
numberCount += 1
if name[numberCount] == '_':
name = name[numberCount + 1:]
else:
name = name[numberCount:]
self.objectPtr = fileW.tell()
labels[self.objectPtr] = name
p = self.objFlags
objFlags = enums.ObjectFlags.null
if p["ignorePosition"]:
objFlags |= enums.ObjectFlags.NoPosition
if p["ignoreRotation"]:
objFlags |= enums.ObjectFlags.NoRotate
if p["ignoreScale"]:
objFlags |= enums.ObjectFlags.NoScale
if p["rotateZYX"]:
objFlags |= enums.ObjectFlags.RotateZYX
if p["skipDraw"]:
objFlags |= enums.ObjectFlags.NoDisplay
if p["skipChildren"]:
objFlags |= enums.ObjectFlags.NoChildren
if p["flagAnimate"]:
objFlags |= enums.ObjectFlags.NoAnimate
if p["flagMorph"]:
objFlags |= enums.ObjectFlags.NoMorph
# Checking if NoDisplay or NoChildren is set and auto-setting them if not to prevent potential error in-game.
if (objFlags & enums.ObjectFlags.NoDisplay) or (objFlags & enums.ObjectFlags.NoChildren):
if self.meshPtr == 0:
objFlags |= enums.ObjectFlags.NoDisplay
if len(self.children) == 0:
objFlags |= enums.ObjectFlags.NoChildren
fileW.wUInt(objFlags.value)
fileW.wUInt(self.meshPtr)
self.position.write(fileW)
self.rotation.write(fileW)
self.scale.write(fileW)
fileW.wUInt(0 if self.child is None else self.child.objectPtr)
fileW.wUInt(0 if self.sibling is None else self.sibling.objectPtr)
class Armature(ModelData):
def writeArmature(self,
fileW: fileHelper.FileWriter,
export_matrix: mathutils.Matrix,
materials: List[bpy.types.Material],
labels: dict):
armature = self.origObject.data
bones: List[Bone] = list()
# first we need to evaluate all bone data (the fun part)
# lets start with the root bone.
# thats basically representing the armature object
root = Bone(self.name,
0,
self.origObject.matrix_world,
mathutils.Matrix.Identity(4),
export_matrix, None,
self.objFlags)
bones.append(root)
# starting with the parentless bones
lastSibling = None
for b in armature.bones:
if b.parent is None:
bone = Bone.getBones(
b,
root,
1,
export_matrix,
self.origObject.matrix_world,
bones)
if lastSibling is not None:
lastSibling.sibling = bone
lastSibling = bone
if len(root.children) > 0:
root.child = root.children[0]
if DO:
print(" == Bone Hierarchy == \n")
for b in bones:
marker = " "
for r in range(b.hierarchyDepth):
marker += "- "
if len(marker) > 1:
print(marker, b.name)
else:
print("", b.name)
print(" - - - -\n")
# now, time to get the mesh data
# first we need to get all objects that the armature modifies
objects: List[ModelData] = list()
objQueue = queue.Queue()
for o in self.children:
objQueue.put(o)
while not objQueue.empty():
o = objQueue.get()
objects.append(o)
for c in o.children:
objQueue.put(c)
# now we have all objects that get modified by the armature
# lets get the meshes
meshes = list()
for o in objects:
if o.processedMesh not in meshes:
meshes.append(o.processedMesh)
# giving each mesh an index buffer offset
meshesWOffset = dict()
currentOffset = 0
for m in meshes:
meshesWOffset[m] = currentOffset
currentOffset += len(m.vertices)
# ok lemme write some notes down:
# there are 3 types of objects that the armature modifies:
# 1. Objects with weights, which are parented to the armature
# 2. Objects parented to bones (also no weights)
# 3. Objects without weights. may be parented to
# armature or object that is parented to armature
armatureMeshes: List[ArmatureMesh] = list()
for o in objects:
mesh = o.processedMesh
if mesh is None:
continue
case1 = False
for m in o.origObject.modifiers:
if isinstance(m, bpy.types.ArmatureModifier) \
and m.object is self.origObject:
# yeah then its case 1, otherwise no
case1 = True
break
weightMap = dict()
obj = o.origObject
if case1:
usedBoneGroups: Dict[Bone, bpy.types.VertexGroup] = dict()
for b in bones:
for g in obj.vertex_groups:
if g.name == b.name:
usedBoneGroups[b] = g
break
usedGroups = [g.index for g in usedBoneGroups.values()]
setStart = False
last = None
# checking valid weight groups
validGroups = list()
emptyVertsFound = False
for v in mesh.vertices:
found = False
for g in v.groups:
if g.group in usedGroups and g.weight > 0:
found = True
if g.group not in validGroups:
validGroups.append(g.group)
if not found:
emptyVertsFound = True
usedGroups = validGroups
validBoneGroups: Dict[Bone, bpy.types.VertexGroup] = dict()
for b, g in usedBoneGroups.items():
if g.index in usedGroups:
validBoneGroups[b] = g
usedBoneGroups = validBoneGroups
if emptyVertsFound:
weightMap[root.name] = [-2, enums.WeightStatus.Start]
setStart = True
last = root.name
for b, g in usedBoneGroups.items():
weightMap[b.name] = [g.index,
enums.WeightStatus.Middle if setStart
else enums.WeightStatus.Start]
setStart = True
last = b.name
if len(weightMap) == 0:
weightMap[root.name] = [-1, enums.WeightStatus.Start]
elif len(weightMap) == 1:
weightMap[list(weightMap.keys())[0]] = \
[-1, enums.WeightStatus.Start]
elif len(weightMap) > 1:
weightMap[last] = \
[weightMap[last][0],
enums.WeightStatus.End]
elif len(o.origObject.parent_bone) > 0:
weightMap[o.origObject.parent_bone] = \
[-1, enums.WeightStatus.Start]
else:
weightMap[root.name] = [-1, enums.WeightStatus.Start]
armatureMeshes.append(
ArmatureMesh(o,
meshesWOffset[mesh],
weightMap))
if DO:
for a in armatureMeshes:
print(" " + a.model.name, a.indexBufferOffset)
for k in a.weightMap.keys():
print(" " + k, a.weightMap[k])
print("")
boneMap: Dict[str, mathutils.Matrix] = dict()
for b in bones:
boneMap[b.name] = b.matrix_world
# converting mesh data
from . import format_CHUNK
boneAttaches = format_CHUNK.fromWeightData(boneMap,
armatureMeshes,
export_matrix,