-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcodmayatools.py
3293 lines (2836 loc) · 158 KB
/
codmayatools.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
# Copyright 2016, Ray1235
# CoDMayaTools is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# -----------------------------------------------------------------------------------------
#
# Change log now available on Github!
#
# ------------------------------------------------------------------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------- Customization (You can change these values!) ----------------------------------------------------------
# ------------------------------------------------------------------------------------------------------------------------------------------------------------------
# Maximum number of warnings to show per export
MAX_WARNINGS_SHOWN = 1
# Number of slots in the export windows
EXPORT_WINDOW_NUMSLOTS = 100
# To export any black vertices as white, set to 'True'. Otherwise, set to 'False'.
CONVERT_BLACK_VERTS_TO_WHITE = False
# Enable Support for ExportX/Export2Bin
USE_EXPORT_X = False
# ------------------------------------------------------------------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------- Global ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------------------------------------------------------------------------------------------
import os
import maya.cmds as cmds
import maya.mel as mel
import math
import sys
sys.path.append('C:\Python39\Lib\site-packages')
import datetime
import os.path
import traceback
import maya.OpenMaya as OpenMaya
import maya.OpenMayaAnim as OpenMayaAnim
import urllib.request as urllib2
import socket
import subprocess
import webbrowser
import queue
import winreg as reg
import time
import struct
import shutil
import zipfile
import re
import json
from pycod import xmodel as xModel
from pycod import xanim as xAnim
from array import array
from subprocess import Popen, PIPE, STDOUT
WarningsDuringExport = 0 # Number of warnings shown during current export
CM_TO_INCH = 0.3937007874015748031496062992126 # 1cm = 50/127in
M_PI = 3.14159265359
FILE_VERSION = 2.9
VERSION_CHECK_URL = "https://raw.githubusercontent.com/Ray1235/CoDMayaTools/master/version"
# Registry path for global data storage
GLOBAL_STORAGE_REG_KEY = (reg.HKEY_CURRENT_USER, "Software\\CoDMayaTools")
# name : control code name, control friendly name, data storage node name, refresh function, export function
OBJECT_NAMES = {'menu' : ["CoDMayaToolsMenu", "Call of Duty Tools", None, None, None],
'progress' : ["CoDMayaToolsProgressbar", "Progress", None, None, None],
'xmodel': ["CoDMayaXModelExportWindow", "Export XModel", "XModelExporterInfo", "RefreshXModelWindow", "ExportXModel"],
'xanim' : ["CoDMayaXAnimExportWindow", "Export XAnim", "XAnimExporterInfo", "RefreshXAnimWindow", "ExportXAnim"],
'xcam' : ["CoDMayaXCamExportWindow", "Export XCam", "XCamExporterInfo", "RefreshXCamWindow", "ExportXCam"]}
# Working Directory
WORKING_DIR = os.path.dirname(os.path.realpath(__file__))
# Current Game
currentGame = "none"
# Format (JOINT, PARENTNAME) : NEWNAME
# Leave parent to None to rename regardless.
RENAME_DICTONARY = {("tag_weapon", "tag_torso") : "tag_weapon_right",
("tag_weapon1", "tag_torso") : "tag_weapon_left",
("j_gun", None) : "tag_weapon",
("j_gun1", None) : "tag_weapon_le",
("tag_flash1", "j_gun1") : "tag_flash_le",
("tag_brass1", None) : "tag_brass_le",
}
# Tags to attach
GUN_BASE_TAGS = ["j_gun", "j_gun1", "j_gun", "j_gun1", "tag_weapon", "tag_weapon1"]
VIEW_HAND_TAGS = ["t7:tag_weapon_right", "t7:tag_weapon_left", "tag_weapon", "tag_weapon1", "tag_weapon_right", "tag_weapon_left"]
# Supported xModel Versions for importing.
SUPPORTED_XMODELS = [25, 62]
# xModel Versions based off games
XMODEL_VERSION = {
"CoD1" : 5,
"CoD2" : 6,
"CoD4" : 6,
"CoD5" : 6,
"CoD7" : 6,
"CoD12": 7
}
# ------------------------------------------------------------------------------------------------------------------------------------------------------------------
# ------------------------------------------------------------------------------ Init ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------------------------------------------------------------------------------------------
def CreateMenu():
cmds.setParent(mel.eval("$temp1=$gMainWindow"))
if cmds.control(OBJECT_NAMES['menu'][0], exists=True):
cmds.deleteUI(OBJECT_NAMES['menu'][0], menu=True)
menu = cmds.menu(OBJECT_NAMES['menu'][0],
label=OBJECT_NAMES["menu"][1],tearOff=True)
# Export tools
cmds.menuItem(label=OBJECT_NAMES['xmodel'][1]+"...",
command="CoDMayaTools.ShowWindow('xmodel')")
cmds.menuItem(label=OBJECT_NAMES['xanim'][1]+"...",
command="CoDMayaTools.ShowWindow('xanim')")
cmds.menuItem(label=OBJECT_NAMES['xcam'][1]+"...",
command="CoDMayaTools.ShowWindow('xcam')")
# Import tools
cmds.menuItem(divider=True)
cmds.menuItem(label="Import XModel...",
subMenu=True)
cmds.menuItem(label="...from CoD7",
command="CoDMayaTools.ImportXModel('CoD7')")
cmds.menuItem(label="...from CoD5",
command="CoDMayaTools.ImportXModel('CoD5')")
cmds.menuItem(label="...from CoD4",
command="CoDMayaTools.ImportXModel('CoD4')")
cmds.setParent(menu,
menu=True)
cmds.menuItem(divider=True)
# Utilities Menu
util_menu = cmds.menuItem(label="Utilities",
subMenu=True)
cmds.menuItem(divider=True)
# Rays Animation Toolkit
cmds.menuItem(label="Ray's Camera Animation Toolkit",
subMenu=True)
cmds.menuItem(label="Mark as camera",
command="CoDMayaTools.setObjectAlias('camera')")
cmds.menuItem(label="Mark as weapon",
command="CoDMayaTools.setObjectAlias('weapon')")
cmds.menuItem(divider=True)
cmds.menuItem(label="Generate camera animation",
command="CoDMayaTools.GenerateCamAnim()")
cmds.menuItem(divider=True)
cmds.menuItem(label="Remove camera animation in current range",
command=RemoveCameraKeys)
cmds.menuItem(label="Reset camera",
command=RemoveCameraAnimData)
cmds.setParent(util_menu,
menu=True)
# Attach Weapon To Rig
cmds.menuItem(divider=True)
cmds.menuItem(label="Attach Weapon to Rig", command=lambda x:WeaponBinder())
# IWIxDDS
cmds.menuItem(divider=True)
cmds.menuItem(label="Convert IWI to DDS",
command=lambda x:IWIToDDSUser())
# Viewmodel Tools
cmds.menuItem(label="ViewModel Tools", subMenu=True)
cmds.menuItem(label="Create New Gunsleeve Maya File",
command=lambda x:CreateNewGunsleeveMayaFile())
cmds.menuItem(label="Create New ViewModel Rig File",
command=lambda x:CreateNewViewmodelRigFile())
cmds.menuItem(label="Switch Gun in Current Rig File",
command=lambda x:SwitchGunInCurrentRigFile())
cmds.setParent(menu, menu=True)
# Settings
cmds.menuItem(divider=True)
settings_menu = cmds.menuItem(label="Settings", subMenu=True)
# Game/Game Folder Settings
cmds.menuItem(label="Game Settings", subMenu=True)
cmds.menuItem(label="Set CoD 1 Root Folder", command=lambda x:SetRootFolder(None, 'CoD1'))
cmds.menuItem(label="Set CoD 2 Root Folder", command=lambda x:SetRootFolder(None, 'CoD2'))
cmds.menuItem(label="Set MW Root Folder", command=lambda x:SetRootFolder(None, 'CoD4'))
cmds.menuItem(label="Set WaW Root Folder", command=lambda x:SetRootFolder(None, 'CoD5'))
cmds.menuItem(label="Set Bo1 Root Folder", command=lambda x:SetRootFolder(None, 'CoD7'))
cmds.menuItem(label="Set Bo3 Root Folder", command=lambda x:SetRootFolder(None, 'CoD12'))
cmds.menuItem(divider=True)
cmds.radioMenuItemCollection()
games = GetCurrentGame(True)
cmds.menuItem( label="Current Game:")
cmds.menuItem( label='CoD 1', radioButton=games["CoD1"], command=lambda x:SetCurrentGame("CoD1"))
cmds.menuItem( label='CoD 2', radioButton=games["CoD2"], command=lambda x:SetCurrentGame("CoD2"))
cmds.menuItem( label='CoD MW', radioButton=games["CoD4"], command=lambda x:SetCurrentGame("CoD4"))
cmds.menuItem( label='CoD WaW', radioButton=games["CoD5"], command=lambda x:SetCurrentGame("CoD5"))
cmds.menuItem( label='CoD Bo1', radioButton=games["CoD7"], command=lambda x:SetCurrentGame("CoD7"))
cmds.menuItem( label='CoD Bo3', radioButton=games["CoD12"] , command=lambda x:SetCurrentGame("CoD12"))
cmds.setParent(settings_menu, menu=True)
# ExportX/Export2Bin Options (Deprecated)
if(USE_EXPORT_X):
cmds.menuItem("E2B", label='Use ExportX', checkBox=QueryToggableOption('E2B'), command=lambda x:SetToggableOption('E2B') )
cmds.menuItem(label="Set Path to ExportX", command=lambda x:SetExport2Bin())
# Misc. Options.
cmds.menuItem(divider=True)
cmds.menuItem("AutomaticRename", label='Automatically rename joints (J_GUN, etc.)', checkBox=QueryToggableOption('AutomaticRename'), command=lambda x:SetToggableOption('AutomaticRename') )
cmds.menuItem("PrefixNoteType", label='Automatically prefix notetracks with type (sndnt# or rmbnt#)', checkBox=QueryToggableOption('PrefixNoteType'), command=lambda x:SetToggableOption('PrefixNoteType') )
cmds.menuItem("MeshMerge", label='Merge Meshes on export', checkBox=QueryToggableOption('MeshMerge'), command=lambda x:SetToggableOption('MeshMerge') )
cmds.menuItem("AutoUpdate", label='Auto Updates', checkBox=QueryToggableOption('AutoUpdate'), command=lambda x:SetToggableOption('AutoUpdate') )
# cmds.menuItem("PrintExport", label='Print xmodel_export information.', checkBox=QueryToggableOption('PrintExport'), command=lambda x:SetToggableOption('PrintExport')" )
cmds.setParent(menu, menu=True)
cmds.menuItem(divider=True)
# For easy script updating
cmds.menuItem(label="Reload Script", command="reload(CoDMayaTools)")
# Tools Info
cmds.menuItem(label="About", command=lambda x:AboutWindow())
def SetCurrentGame(game=None):
if game is None:
return
try:
storageKey = reg.OpenKey(GLOBAL_STORAGE_REG_KEY[0], GLOBAL_STORAGE_REG_KEY[1], 0, reg.KEY_ALL_ACCESS)
except WindowsError:
storageKey = reg.CreateKey(GLOBAL_STORAGE_REG_KEY[0], GLOBAL_STORAGE_REG_KEY[1])
storageKey = reg.OpenKey(GLOBAL_STORAGE_REG_KEY[0], GLOBAL_STORAGE_REG_KEY[1], 0, reg.KEY_ALL_ACCESS)
reg.SetValueEx(storageKey, "CurrentGame", 0, reg.REG_SZ, game )
def GetCurrentGame(return_dict=False):
games = {
"CoD1" : False,
"CoD2" : False,
"CoD4" : False,
"CoD5" : False,
"CoD7" : False,
"CoD12" : False
}
# Try get the current game set.
try:
storageKey = reg.OpenKey(GLOBAL_STORAGE_REG_KEY[0], GLOBAL_STORAGE_REG_KEY[1], 0, reg.KEY_ALL_ACCESS)
game = reg.QueryValueEx(storageKey, "CurrentGame")[0]
except WindowsError:
# Failed, create it and fall back to Bo3
storageKey = reg.OpenKey(GLOBAL_STORAGE_REG_KEY[0], GLOBAL_STORAGE_REG_KEY[1], 0, reg.KEY_ALL_ACCESS)
try:
reg.SetValueEx(storageKey, "CurrentGame", 0, reg.REG_SZ , 0 ,"CoD12")
game = reg.QueryValueEx(storageKey, "CurrentGame")[0]
except:
# Fall back to Black Ops III if a game isn't set, and we can't create one.
game = "CoD12"
games[game] = True
# Return dictonary for radio buttons
if return_dict:
return games
# Return current game for everything else
else:
return game
# ------------------------------------------------------------------------------------------------------------------------------------------------------------------
# ------------------------------------------------------------------------- Import Common --------------------------------------------------------------------------
# ------------------------------------------------------------------------------------------------------------------------------------------------------------------
def ImportFileSelectDialog(codRootPath, type):
print(codRootPath)
importFrom = None
if cmds.about(version=True)[:4] == "2012": # There is a bug in later versions of Maya with the file browser dialog and files with no extension
importFrom = cmds.fileDialog2(fileMode=1, fileFilter="%s Files (*)" % type, caption="Import %s" % type, startingDirectory=os.path.join(codRootPath, "raw/%s/" % type.lower()))
else:
importFrom = cmds.fileDialog2(fileMode=1, dialogStyle=1, fileFilter="%s Files (*)" % type, caption="Import %s" % type, startingDirectory=os.path.join(codRootPath, "raw/%s/" % type.lower()))
if importFrom == None or len(importFrom) == 0 or importFrom[0].strip() == "":
return None
path = importFrom[0].strip()
pathSplit = os.path.splitext(path) # Fix bug with Maya 2013
if pathSplit[1] == ".*":
path = pathSplit
return path
def UnitQuaternionToDegrees(x, y, z):
w = math.sqrt(1 - x*x - y*y - z*z) # The 4th component of a quaternion can be found from the other 3 components in unit quaternions
euler = OpenMaya.MQuaternion(x, y, z, w).asEulerRotation()
return (math.degrees(euler.x), math.degrees(euler.y), math.degrees(euler.z))
def ReadJointRotation(f):
rot = struct.unpack('<hhh', f.read(6))
# Rotation is stored as a unit quaternion, but only the X, Y, and Z components are given, as integers scaled to -32768 to 32767
rot = UnitQuaternionToDegrees(rot[0] / 32768.0, rot[1] / 32768.0, rot[2] / 32768.0)
return rot
def ReadNullTerminatedString(f):
byte = f.read(1)
string = ""
while struct.unpack('B', byte)[0] != 0:
string += byte
byte = f.read(1)
return string
def AutoCapsJointName(name):
if name.startswith("tag"):
return name.upper()
name = name.capitalize()
name = name.replace("_le_", "_LE_")
name = name.replace("_ri_", "_RI_")
if name[-3:] == "_le":
name = name[:-3] + "_LE"
if name[-3:] == "_ri":
name = name[:-3] + "_RI"
# Capitalize the letter after each underscore
indices = set([m.start() for m in re.finditer("_", name)])
return "".join(c.upper() if (i-1) in indices else c for i, c in enumerate(name))
# ------------------------------------------------------------------------------------------------------------------------------------------------------------------
# -------------------------------------------------------------------------- Import XAnim --------------------------------------------------------------------------
# ------------------------------------------------------------------------------------------------------------------------------------------------------------------
def ImportXAnim(game):
codRootPath = GetRootFolder(None, game) # Only call this once, because it might create a dialog box
xanimPath = ImportFileSelectDialog(codRootPath, "XAnim")
if not xanimPath:
return
print("Importing XAnim '%s'" % os.path.basename(xanimPath))
with open(xanimPath, "rb") as f:
# Check file version
version = f.read(2)
if len(version) == 0 or struct.unpack('H', version)[0] != 17:
MessageBox("ERROR: Not a valid XAnim file")
return
# Header
numFrames = struct.unpack('<H', f.read(2))[0]
numJoints = struct.unpack('<H', f.read(2))[0]
fileInfoBitfield = struct.unpack('<H', f.read(2))[0]
framerate = struct.unpack('<H', f.read(2))[0]
# Get anim type as string
animType = "absolute"
if fileInfoBitfield & 2:
animType = "delta"
elif fileInfoBitfield & 256:
animType = "relative"
elif fileInfoBitfield & 1024:
animType = "additive"
# ???
if animType == "absolute":
f.read(2) # ???
else:
print("Cannot read anim type '%s'" % animType)
return
# Read joint names
joints = []
for i in range(numJoints):
joints.append(ReadNullTerminatedString(f))
print(joints)
# Read joint frame data
for i in range(numJoints):
numRotations = struct.unpack('<H', f.read(2))[0]
for j in range(numRotations):
rot = ReadJointRotation(f)
numPositions = struct.unpack('<H', f.read(2))[0]
for j in range(numPositions):
pos = struct.unpack('<fff', f.read(12))
print(pos)
# ------------------------------------------------------------------------------------------------------------------------------------------------------------------
# -------------------------------------------------------------------------- Import XModel -------------------------------------------------------------------------
# ------------------------------------------------------------------------------------------------------------------------------------------------------------------
def ImportXModel(game):
codRootPath = GetRootFolder(None, game) # Only call this once, because it might create a dialog box
xmodelPath = ImportFileSelectDialog(codRootPath, "XModel")
if not xmodelPath:
return
# Show progress bar
if cmds.control("w"+OBJECT_NAMES['progress'][0], exists=True):
cmds.deleteUI("w"+OBJECT_NAMES['progress'][0])
progressWindow = cmds.window("w"+OBJECT_NAMES['progress'][0], title=OBJECT_NAMES['progress'][1], width=302, height=22)
cmds.columnLayout()
progressControl = cmds.progressBar(OBJECT_NAMES['progress'][0], width=300, progress=0)
cmds.showWindow(progressWindow)
cmds.refresh() # Force the progress bar to be drawn
try:
print("Importing XModel '%s'" % os.path.basename(xmodelPath))
with open(xmodelPath, "rb") as f:
version = f.read(2)
if len(version) == 0 or struct.unpack('H', version)[0] not in SUPPORTED_XMODELS:
MessageBox("ERROR: Not a valid XModel file")
print("")
if game == "CoD4":
f.read(25) # ???
ReadNullTerminatedString(f)
elif game == "CoD5":
f.read(26) # ???
ReadNullTerminatedString(f)
elif game == "CoD7":
f.read(28) # ???
ReadNullTerminatedString(f)
ReadNullTerminatedString(f)
f.read(5)
print(f.tell())
lods = []
for i in range(4): # 4 is possible number of lods
someInt = struct.unpack('<I', f.read(4))
lodFileName = ReadNullTerminatedString(f)
if lodFileName != "":
lods.append({"name":lodFileName})
if len(lods) == 0:
MessageBox("ERROR: This XModel has no data (no LOD files)!")
return
f.read(4) # Spacer if next int isn't 0, otherwise ???
count = struct.unpack('<I', f.read(4))[0]
print(count)
for i in range(count):
subcount = struct.unpack('<I', f.read(4))[0]
f.read((subcount * 48) + 36) # ???
for lod in lods:
materials = []
numMaterials = struct.unpack('<H', f.read(2))[0]
for i in range(numMaterials):
materials.append(ReadNullTerminatedString(f))
lod["materials"] = materials
# Load joint data (24 bytes per joint) ???
lodToLoad = lods[0]
if len(lods) > 1:
buttons = []
lodDict = {}
for lod in lods:
buttons.append(lod["name"])
lodDict[lod["name"]] = lod
buttons.sort()
result = cmds.confirmDialog(title="Select LOD level", message="This model has more than one LOD level. Select which one to import:", button=buttons, defaultButton=buttons[0], dismissString="EXIT")
if result in lodDict:
lodToLoad = lodDict[result]
lodToLoad["transformGroup"] = cmds.group(empty=True, name=lodToLoad["name"])
lodToLoad["materialMaps"] = LoadMaterials(lodToLoad, codRootPath)
lodToLoad["joints"] = LoadJoints(lodToLoad, codRootPath)
LoadSurfaces(lodToLoad, codRootPath, game)
AutoIKHandles(lodToLoad)
cmds.select(lodToLoad["transformGroup"], replace=True)
finally:
# Delete progress bar
cmds.deleteUI(progressWindow, window=True)
def LoadSurfaces(lod, codRootPath, game):
print("Loading XModel surface '%s'" % lod["name"])
with open(os.path.join(codRootPath, "raw/xmodelsurfs/%s" % lod["name"]), "rb") as f:
version = f.read(2)
if len(version) == 0 or struct.unpack('H', version)[0] not in SUPPORTED_XMODELS:
MessageBox("ERROR: Not a valid XModel surface file")
return
numMeshes = struct.unpack('<H', f.read(2))[0]
if numMeshes != len(lod["materials"]):
MessageBox("ERROR: Different number of meshes and materials on LOD '%s'" % lod["name"])
return
meshesCreated = []
cmds.progressBar(OBJECT_NAMES['progress'][0], edit=True, maxValue=numMeshes*5+1, progress=0)
for i in range(numMeshes):
cmds.window("w"+OBJECT_NAMES['progress'][0], edit=True, title="Loading mesh %i..." % i)
# Read mesh header
a = struct.unpack('<B', f.read(1))[0] # ???
b = struct.unpack('<H', f.read(2))[0] # ???
numVerts = struct.unpack('<H', f.read(2))[0]
numTris = struct.unpack('<H', f.read(2))[0]
numVerts2 = struct.unpack('<H', f.read(2))[0]
physiqued = numVerts != numVerts2
if physiqued:
f.read(2) # ???
print("\tMesh %i is physiqued... this may not load correctly" % i)
if numVerts2 != 0:
while struct.unpack('H', f.read(2))[0] != 0: # Search for next 0 short ???
pass
f.read(2) # ???
else:
# If a mesh is being influenced by only 1 vert
# then it only stores vert. index. with 1.0
# influence.
bone = struct.unpack('<I', f.read(4)) # ???
single_joint_bind = lod["joints"][bone[0]]["name"]
vertexArray = OpenMaya.MFloatPointArray()
uArray = OpenMaya.MFloatArray()
vArray = OpenMaya.MFloatArray()
polygonCounts = OpenMaya.MIntArray(numTris, 3)
polygonConnects = OpenMaya.MIntArray()
normals = []
vertsWeights = []
ProgressBarStep()
bones = []
# Read vertices
for j in range(numVerts):
# f.read(12) # ???
normal = struct.unpack('<fff', f.read(12)) # ???
normal = OpenMaya.MVector(normal[0], normal[1], normal[2])
color = struct.unpack('<BBBB', f.read(4))
uv = struct.unpack('<ff', f.read(8))
if game == "CoD7":
f.read(28)
else:
f.read(24)
numWeights = 0
finalBoneNumber = 0
if physiqued:
numWeights = struct.unpack('<B', f.read(1))[0]
finalBoneNumber = struct.unpack('<H', f.read(2))[0]
pos = struct.unpack('<fff', f.read(12))
totalWeight = 0
weights = []
for k in range(numWeights):
weight = struct.unpack('<HH', f.read(4)) # [0] = bone number, [1] = weight mapped to integer (range 0-(2^16))
totalWeight += weight[1] / 65536.0
joint = lod["joints"][weight[0]]["name"]
weights.append((joint, weight[1] / 65536.0))
weights.append((lod["joints"][finalBoneNumber]["name"], 1 - totalWeight)) # Final bone gets remaining weight
vertsWeights.append(weights)
vertexArray.append(pos[0]/CM_TO_INCH, pos[1]/CM_TO_INCH, pos[2]/CM_TO_INCH)
normals.append(normal)
uArray.append(uv[0])
vArray.append(1-uv[1])
# Read face indices
tris_list = OpenMaya.MIntArray()
vert_list = OpenMaya.MIntArray()
_normals = OpenMaya.MVectorArray()
for j in range(numTris):
face = struct.unpack('<HHH', f.read(6))
tris_list.append(j)
tris_list.append(j)
tris_list.append(j)
polygonConnects.append(face[0])
polygonConnects.append(face[2])
polygonConnects.append(face[1])
vert_list.append(face[0])
vert_list.append(face[2])
vert_list.append(face[1])
_normals.append(normals[face[0]])
_normals.append(normals[face[2]])
_normals.append(normals[face[1]])
ProgressBarStep()
# Create mesh
mesh = OpenMaya.MFnMesh()
transform = mesh.create(numVerts, numTris, vertexArray, polygonCounts, polygonConnects)
mesh.setFaceVertexNormals(_normals, tris_list, vert_list)
# UV map
mesh.setUVs(uArray, vArray)
mesh.assignUVs(polygonCounts, polygonConnects)
# Rename mesh
transformDagPath = OpenMaya.MDagPath()
OpenMaya.MDagPath.getAPathTo(transform, transformDagPath)
newPath = cmds.parent(transformDagPath.fullPathName(), lod["transformGroup"])
newPath = cmds.rename(newPath, "mesh%i" % i)
meshesCreated.append(newPath)
ProgressBarStep()
# Joint weights
# TODO: Make this faster!!! Soooo sloowwwwwww
if physiqued:
skin = cmds.skinCluster(lod["joints"][0]["name"], newPath)[0] # Bind the mesh to the root joint for now
for j, vertWeights in enumerate(vertsWeights):
cmds.skinPercent(skin, "%s.vtx[%i]" % (newPath, j), zeroRemainingInfluences=True, transformValue=vertWeights)
else:
skin = cmds.skinCluster(single_joint_bind, newPath,tsb=True, mi=1)[0]
ProgressBarStep()
# Apply textures
shader = cmds.shadingNode("lambert", name=lod["materials"][i], asShader=True)
cmds.select(newPath)
cmds.hyperShade(assign=shader)
colorMap = cmds.shadingNode("file", name=lod["materials"][i] + "_colorMap", asTexture=True)
cmds.connectAttr("%s.outColor" % colorMap, "%s.color" % shader)
if "colorMap" in lod["materialMaps"][lod["materials"][i]]:
cmds.setAttr("%s.fileTextureName" % colorMap, os.path.join(codRootPath, "raw/images/%s/%s.dds" % (lod["name"], lod["materialMaps"][lod["materials"][i]]["colorMap"])), type="string")
# Merge duplicates
mel.eval("polyMergeVertex -d 0.01 -am 1 -ch 0 %s;" % newPath) # Merge duplicate verts
mel.eval("polyMergeUV -d 0.01 -ch 0 %s;" % newPath) # Merge duplicate UVs
ProgressBarStep()
if len(f.read(1)) != 0: # Check if it's at the end of the file
MessageBox("The export completed, however it's quite likely that at least one of the meshes did not import correctly. See the Script Editor output for more information.")
ProgressBarStep()
def LoadJoints(lod, codRootPath):
print("Loading XModel joints '%s'" % lod["name"])
cmds.window("w"+OBJECT_NAMES['progress'][0], edit=True, title="Loading joints...")
joints = []
if not os.path.exists(os.path.join(codRootPath, "raw/xmodelparts/%s" % lod["name"])):
# cmds.joint("tag_origin", orientation=(0,0,0), position=(0,0,0), relative=True)
return
with open(os.path.join(codRootPath, "raw/xmodelparts/%s" % lod["name"]), "rb") as f:
version = f.read(2)
if len(version) == 0 or struct.unpack('H', version)[0] not in SUPPORTED_XMODELS:
MessageBox("ERROR: Not a valid XModel parts file")
return
# Number of bones
numJoints = struct.unpack('<H', f.read(2))[0]
cmds.progressBar(OBJECT_NAMES['progress'][0], edit=True, maxValue=numJoints*2+1, progress=0)
if numJoints == 0: # Special case
joints.append({"parent": -1, "pos": (0.0,0.0,0.0), "rot": (0.0,0.0,0.0), "name": "TAG_ORIGIN"})
cmds.select(clear=True)
cmds.joint(name=joints[0]["name"], orientation=(0.0,0.0,0.0), position=(0.0,0.0,0.0), relative=True)
ProgressBarStep()
return joints
f.read(2) # ???
# Joint data
joints.append({"parent": -1, "pos": (0.0,0.0,0.0), "rot": (0.0,0.0,0.0)}) # parent joint
for i in range(numJoints):
parentJoint = struct.unpack('<B', f.read(1))[0]
pos = struct.unpack('<fff', f.read(12))
rot = ReadJointRotation(f)
joints.append({"parent": parentJoint, "pos": pos, "rot": rot})
ProgressBarStep()
for i in range(numJoints+1):
joints[i]["name"] = ReadNullTerminatedString(f).lower()
for joint in joints:
if joint["parent"] >= 0: # Select parent
cmds.select(joints[joint["parent"]]["name"], replace=True)
else:
cmds.select(clear=True)
cmds.joint(name=joint["name"], orientation=joint["rot"], position=(joint["pos"][0]/CM_TO_INCH, joint["pos"][1]/CM_TO_INCH, joint["pos"][2]/CM_TO_INCH), relative=True)
ProgressBarStep()
ProgressBarStep()
return joints
def LoadMaterials(lod, codRootPath):
noDupMaterials = list(set(lod["materials"]))
cmds.window("w"+OBJECT_NAMES['progress'][0], edit=True, title="Loading materials...")
cmds.progressBar(OBJECT_NAMES['progress'][0], edit=True, maxValue=len(noDupMaterials)*2+1, progress=0)
iwdImages = LoadMainIWDImages(codRootPath)
ProgressBarStep()
# Create output folder
if not os.path.exists(os.path.join(codRootPath, "raw/images/%s/" % lod["name"])):
os.makedirs(os.path.join(codRootPath, "raw/images/%s/" % lod["name"]))
# Create material info file
infofile = open(os.path.join(codRootPath, "raw/images/%s/%s" % (lod["name"], "%s Material Info.txt" % lod["name"])), "w")
# Load materials
outMaterialList = {}
for material in noDupMaterials:
materialMaps = {}
# http://www.diegologic.net/diegologic/Programming/CoD4%20Material.html
path = os.path.join(codRootPath, "raw/materials/%s" % material)
path = os.path.normpath(path)
print("Loading material '%s'" % material)
if not os.path.exists(path):
print("Failed loading material, path does not exist.")
continue
with open(path, "rb") as f:
f.read(48) # Skip start of header
numMaps = struct.unpack('<H', f.read(2))[0]
f.read(14) # Skip the rest of header
for i in range(numMaps):
mapTypeOffset = struct.unpack('<I', f.read(4))[0]
f.read(4) # Skip
mapNameOffset = struct.unpack('<I', f.read(4))[0]
current = f.tell()
f.seek(mapTypeOffset)
mapType = ReadNullTerminatedString(f)
f.seek(mapNameOffset)
mapName = ReadNullTerminatedString(f)
f.seek(current)
materialMaps[mapType] = mapName
infofile.write("Material: %s\n" % material)
for type, mapName in materialMaps.items():
infofile.write("\t%s: %s\n" % (type, mapName))
infofile.write("\n")
outMaterialList[material] = materialMaps
ProgressBarStep()
# Gather .iwis
rawImages = os.listdir(os.path.join(codRootPath, "raw/images/"))
for type, mapName in materialMaps.items():
outPath = os.path.join(codRootPath, "raw/images/%s/%s%s" % (lod["name"], mapName, ".iwi"))
if os.path.exists(outPath):
continue
if (mapName + ".iwi") in rawImages:
shutil.copy(os.path.join(codRootPath, "raw/images/%s%s" % (mapName, ".iwi")), os.path.join(codRootPath, "raw/images/%s/" % lod["name"]))
elif (mapName + ".iwi") in iwdImages:
iwdName = iwdImages[mapName + ".iwi"]
zip = zipfile.ZipFile(os.path.join(codRootPath, "main/%s" % iwdName), "r")
# Extract from zip
source = zip.open("images/%s%s" % (mapName, ".iwi"))
target = file(outPath, "wb")
shutil.copyfileobj(source, target)
source.close()
target.close()
if type == "colorMap":
try:
IWIToDDS(outPath)
except:
print(traceback.format_exc())
ProgressBarStep()
infofile.close()
return outMaterialList
def AutoIKHandles(lod):
if len(lod["joints"]) < 2:
return
result = cmds.confirmDialog(title="Auto IK Handles", message="Is this a character (player or AI) model?", button=["Yes", "No"], defaultButton="No", dismissString="No")
if result == "Yes":
# Arms
SafeIKHandle("IK_Arm_LE", "J_Shoulder_LE", "J_Wrist_LE")
SafeIKHandle("IK_Arm_RI", "J_Shoulder_RI", "J_Wrist_RI")
# Left hand
SafeIKHandle("IK_Index_LE", "J_Index_LE_1", "J_Index_LE_3")
SafeIKHandle("IK_Mid_LE", "J_Mid_LE_1", "J_Mid_LE_3")
SafeIKHandle("IK_Ring_LE", "J_Ring_LE_1", "J_Ring_LE_3")
SafeIKHandle("IK_Pinky_LE", "J_Pinky_LE_1", "J_Pinky_LE_3")
SafeIKHandle("IK_Thumb_LE", "J_Thumb_LE_1", "J_Thumb_LE_3")
# Right hand
SafeIKHandle("IK_Index_RI", "J_Index_RI_1", "J_Index_RI_3")
SafeIKHandle("IK_Mid_RI", "J_Mid_RI_1", "J_Mid_RI_3")
SafeIKHandle("IK_Ring_RI", "J_Ring_RI_1", "J_Ring_RI_3")
SafeIKHandle("IK_Pinky_RI", "J_Pinky_RI_1", "J_Pinky_RI_3")
SafeIKHandle("IK_Thumb_RI", "J_Thumb_RI_1", "J_Thumb_RI_3")
# Legs
SafeIKHandle("IK_Leg_LE", "J_Hip_LE", "J_Ankle_LE")
SafeIKHandle("IK_Leg_RI", "J_Hip_RI", "J_Ankle_RI")
def SafeIKHandle(name, joint1, joint2):
# Only apply the IK Handle if both joints exist
if cmds.objExists(joint1) and cmds.nodeType(joint1) == 'joint' and cmds.objExists(joint2) and cmds.nodeType(joint2) == 'joint':
cmds.ikHandle(name=name, startJoint=joint1, endEffector=joint2)
def LoadMainIWDImages(codRootPath):
iwdImages = {}
if not os.path.exists(os.path.join(codRootPath, "main/")):
return iwdImages
iwds = os.listdir(os.path.join(codRootPath, "main/"))
for iwd in iwds:
if not iwd.endswith(".iwd"):
continue
zip = zipfile.ZipFile(os.path.join(codRootPath, "main/") + iwd, "r")
images = zip.namelist()
images = [x for x in images if x.startswith("images/")]
for i in range(len(images)):
imageName = images[i][7:]
if len(imageName) > 0:
iwdImages[imageName] = iwd
return iwdImages
# ------------------------------------------------------------------------------------------------------------------------------------------------------------------
# --------------------------------------------------------------------------- IWI to DDS ---------------------------------------------------------------------------
# ------------------------------------------------------------------------------------------------------------------------------------------------------------------
def IWIToDDS(inIWIPath):
splitPath = os.path.splitext(inIWIPath)
outDDSPath = splitPath[0] + ".dds"
supported_headers = [6, 13]
print("Converting %s to DDS" % os.path.basename(inIWIPath))
iwi_data = {}
# Offsets are different for V13 IWIs
iwi_data[6] = [8, 7]
iwi_data[13] = [9, 8]
if not os.path.exists(inIWIPath):
return False
with open(inIWIPath, 'rb') as inf:
# http://www.matejtomcik.com/Public/Projects/IWIExtractor/
if inf.read(3) != "IWi": # Read file identifier
print("\tERROR: Not a valid IWI file")
return False
header = struct.unpack('<BBBHHBBIIII', inf.read(25))
print("Header Version: %i" % header[0])
if header[0] not in supported_headers: # Make sure it's V6 or V13 IWI
print("\tERROR: Unsupported IWI version")
return False
imageType = None
if header[1] == 0xB: # DXT1
imageType = "DXT1"
elif header[1] == 0xC: # DXT3
imageType = "DXT3"
elif header[1] == 0xD: # DXT5
imageType = "DXT5"
else:
print("\tERROR: Unknown image format")
return False
print("Writing_DDS")
with open(outDDSPath, 'wb') as outf:
# http://msdn.microsoft.com/en-us/library/windows/desktop/bb943991(v=vs.85).aspx
outf.write("DDS ") # File indentifier
print("Written that stuff1")
# DDS_HEADER size, flags, height, width, pitch, depth, mipmap count
outf.write(struct.pack('<7I', 124, 659463, header[4], header[3], 0, 0, 1))
outf.write(struct.pack('<11I', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)) # Reserved
# DDS_PIXELFORMAT size, flags, type, masks
outf.write(struct.pack('II4s5I', 32, 4, imageType, 0, 0, 0, 0, 0))
# DDS_HEADER caps1
outf.write(struct.pack('5I', 4198408, 0, 0, 0, 0))
print("Written that stuff")
# Copy Images
# MIPMAP 0
inf.seek(header[iwi_data[header[0]][0]])
outf.write(inf.read(header[iwi_data[header[0]][1]] - header[iwi_data[header[0]][0]]))
# # MIPMAP 1
# inf.seek(header[9])
# outf.write(inf.read(header[8] - header[9]))
# # MIPMAP 2
# inf.seek(header[10])
# outf.write(inf.read(header[9] - header[10]))
return True
def IWIToDDSUser():
codRootPath = GetRootFolder() # Only call this once, because it might create a dialog box
files = cmds.fileDialog2(fileMode=4, fileFilter="IWI Images (*.iwi)", caption="Select IWI file", startingDirectory=os.path.join(codRootPath, "raw/images/"))
if files == None or len(files) == 0 or files[0].strip() == "":
return
success = True
for file in files:
if not IWIToDDS(file):
success = False
if not success:
MessageBox("One or more of the IWIs failed to convert. See the Script Editor output for more information.")
# ------------------------------------------------------------------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------- Export Joints (XModel and XAnim) ----------------------------------------------------------------
# ------------------------------------------------------------------------------------------------------------------------------------------------------------------
def GetJointList(export_type=None):
# Joints list.
joints = []
# Try get the cosmetic bone.
if export_type == "xmodel":
try:
# Get it.
cosmeticBone = cmds.getAttr(OBJECT_NAMES["xmodel"][2]+ ".Cosmeticbone").split("|")[-1].split(":")[-1]
# Does it exist in scene?
if not cmds.objExists(cosmeticBone):
# If it doesn't, don't assign a cosmetic bone.
cosmeticBone = None
else:
cosmeticBone = cosmeticBone.split("|")[-1].split(":")[-1]
except:
# No cosmetic set.
cosmeticBone = None
# Cosmetic Bones List
cosmetic_list = []
# Cosmetic Bone ID (for xmodel_export)
cosmetic_id = None
else:
# No cosmetic set.
cosmeticBone = None
# Cosmetic Bones List
cosmetic_list = []
# Cosmetic Bone ID (for xmodel_export)
cosmetic_id = None
# Get selected objects
selectedObjects = OpenMaya.MSelectionList()
OpenMaya.MGlobal.getActiveSelectionList(selectedObjects)
for i in range(selectedObjects.length()):
# Get object path and node
dagPath = OpenMaya.MDagPath()
selectedObjects.getDagPath(i, dagPath)
dagNode = OpenMaya.MFnDagNode(dagPath)
# Ignore nodes that aren't joints or arn't top-level
if not dagPath.hasFn(OpenMaya.MFn.kJoint) or not RecursiveCheckIsTopNode(selectedObjects, dagNode):
continue
# Breadth first search of joint tree
searchQueue = Queue.Queue(0)
searchQueue.put((-1, dagNode, True)) # (index = child node's parent index, child node)
while not searchQueue.empty():
node = searchQueue.get()
index = len(joints)
if node[2]:
# Don't use main root bone.
if node[0] > -1:
# Name of the bones parent, none for Root bone. Split it to remove dagpath seperator and namespace.
bone_parentname = joints[node[0]][1].split("|")[-1].split(":")[-1]
else:
# Skip.
bone_parentname = None
# Name of the bone. Split it to remove dagpath seperator and namespace.
bone_name = node[1].partialPathName().split("|")[-1].split(":")[-1]
# Check for automatic rename.
if QueryToggableOption("AutomaticRename"):
# Run over dictonary for possible joints to rename.
for potjoints, new_name in RENAME_DICTONARY.iteritems():
# Found one
if bone_name == potjoints[0]:
# Check if it's a child bone of what we want, None to rename regardless.
if potjoints[1] is None or potjoints[1] == bone_parentname:
bone_name = new_name
# Check if we have cosmetic bone.
if cosmeticBone is not None and bone_parentname == cosmeticBone:
# Append it.
cosmetic_list.append((node[0], bone_name, node[1]))
else:
# Not a cosmetic, add it to normal joints.
joints.append((node[0], bone_name, node[1]))
# Our cosmetic parent.
if bone_name == cosmeticBone:
cosmetic_id = index
else:
index = node[0]
for i in range(node[1].childCount()):
dagPath = OpenMaya.MDagPath()
childNode = OpenMaya.MFnDagNode(node[1].child(i))
childNode.getPath(dagPath)
searchQueue.put((index, childNode, selectedObjects.hasItem(dagPath) and dagPath.hasFn(OpenMaya.MFn.kJoint)))