This repository has been archived by the owner on Dec 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
SourceMayaTools.py
1482 lines (1203 loc) · 73.9 KB
/
SourceMayaTools.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 2019, Luna 'Ryuko' Zaremba
# SourceMayaTools 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/>.
# -----------------------------------------------------------------------------------------
# VERSION INFO
# VERSION 1.0
# + Original - Initial release
# VERSION 1.0.1
# + Fix scaling issue between different units
# VERSION 1.1
# + Add an option to subtract animation data from a frame
# + Add a config variable to replace the first underscore in joint names with a dot
# VERSION 1.2
# + Experimental scale support
# ------------------------------------------------------------------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------- Customization (You can change these values!) ----------------------------------------------------------
# ------------------------------------------------------------------------------------------------------------------------------------------------------------------
MAX_WARNINGS_SHOWN = 100 # Maximum number of warnings to show per export
EXPORT_WINDOW_NUMSLOTS = 100 # Number of slots in the export windows
REPLACE_FIRST_UNDERSCORE = True # Whether to replace the first underscore in joint names with a dot (example: j_shoulder_le -> j.shoulder_le). This is in order to keep parity with MESA's SMD importer.
# ------------------------------------------------------------------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------- Global ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------------------------------------------------------------------------------------------
import os
import maya.cmds as cmds
import maya.mel as mel
import math
import sys
import datetime
import os.path
import traceback
import maya.OpenMaya as OpenMaya
import maya.OpenMayaAnim as OpenMayaAnim
import urllib2
import socket
import subprocess
import webbrowser
import Queue
import _winreg as reg
import time
import struct
import shutil
import zipfile
import re
from subprocess import Popen, PIPE, STDOUT
WarningsDuringExport = 0 # Number of warnings shown during current export
CM_TO_INCH = 0.3937007874015748031496062992126 # 1cm = 50/127in
PI_CONST = 3.141592
GLOBAL_STORAGE_REG_KEY = (reg.HKEY_CURRENT_USER, "Software\\SourceMayaTools") # Registry path for global data storage
# name : control code name, control friendly name, data storage node name, refresh function, export function
OBJECT_NAMES = {'menu' : ["SourceMayaToolsMenu", "Source Engine Tools", None, None, None],
'progress' : ["SourceMayaToolsProgressbar", "Progress", None, None, None],
'smdmodel': ["SMDModelExportWindow", "Export SMD Model", "SMDModelExporterInfo", "RefreshSMDModelWindow", "ExportSMDModel"],
'smdanim' : ["SMDAnimExportWindow", "Export SMD Anim", "SMDAnimExporterInfo", "RefreshSMDAnimWindow", "ExportSMDAnim"],
}
# UTILITY FUNCTIONS FOR EXPORT
# Thanks to SETools
def __math_matrixtoquat__(maya_matrix):
"""Converts a Maya matrix array to a quaternion"""
quat_x, quat_y, quat_z, quat_w = (0, 0, 0, 1)
trans_remain = maya_matrix[0] + maya_matrix[5] + maya_matrix[10]
if trans_remain > 0:
divisor = math.sqrt(trans_remain + 1.0) * 2.0
quat_w = 0.25 * divisor
quat_x = (maya_matrix[6] - maya_matrix[9]) / divisor
quat_y = (maya_matrix[8] - maya_matrix[2]) / divisor
quat_z = (maya_matrix[1] - maya_matrix[4]) / divisor
elif (maya_matrix[0] > maya_matrix[5]) and (maya_matrix[0] > maya_matrix[10]):
divisor = math.sqrt(
1.0 + maya_matrix[0] - maya_matrix[5] - maya_matrix[10]) * 2.0
quat_w = (maya_matrix[6] - maya_matrix[9]) / divisor
quat_x = 0.25 * divisor
quat_y = (maya_matrix[4] + maya_matrix[1]) / divisor
quat_z = (maya_matrix[8] + maya_matrix[2]) / divisor
elif maya_matrix[5] > maya_matrix[10]:
divisor = math.sqrt(
1.0 + maya_matrix[5] - maya_matrix[0] - maya_matrix[10]) * 2.0
quat_w = (maya_matrix[8] - maya_matrix[2]) / divisor
quat_x = (maya_matrix[4] + maya_matrix[1]) / divisor
quat_y = 0.25 * divisor
quat_z = (maya_matrix[9] + maya_matrix[6]) / divisor
else:
divisor = math.sqrt(
1.0 + maya_matrix[10] - maya_matrix[0] - maya_matrix[5]) * 2.0
quat_w = (maya_matrix[1] - maya_matrix[4]) / divisor
quat_x = (maya_matrix[8] + maya_matrix[2]) / divisor
quat_y = (maya_matrix[9] + maya_matrix[6]) / divisor
quat_z = 0.25 * divisor
# Return the result
return OpenMaya.MQuaternion(quat_x, quat_y, quat_z, quat_w)
def GetJointList():
joints = []
# 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]:
joints.append((node[0], node[1]))
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)))
return joints
def RecursiveCheckIsTopNode(cSelectionList, currentNode): # Checks if the given node has ANY selected parent, grandparent, etc joints
if currentNode.parentCount() == 0:
return True
for i in range(currentNode.parentCount()):
parentDagPath = OpenMaya.MDagPath()
parentNode = OpenMaya.MFnDagNode(currentNode.parent(i))
parentNode.getPath(parentDagPath)
if not parentDagPath.hasFn(OpenMaya.MFn.kJoint): # Not a joint, but still check parents
if not RecursiveCheckIsTopNode(cSelectionList, parentNode):
return False # A parent joint is selected, we're done
else:
continue # No parent joints are selected, ignore this node
if cSelectionList.hasItem(parentDagPath):
return False
else:
if not RecursiveCheckIsTopNode(cSelectionList, parentNode):
return False
return True
def GetMaterialsFromMesh(mesh, dagPath):
textures = {}
# http://rabidsquirrelgames.googlecode.com/svn/trunk/Maya%20plugin/fileExportCmd.py
# The code below gets a dictionary of [material name: material file name], ex: [a_material: a_material.dds]
shaders = OpenMaya.MObjectArray()
shaderIndices = OpenMaya.MIntArray()
mesh.getConnectedShaders(dagPath.instanceNumber(), shaders, shaderIndices)
for i in range(shaders.length()):
shaderNode = OpenMaya.MFnDependencyNode(shaders[i])
shaderPlug = shaderNode.findPlug("surfaceShader")
material = OpenMaya.MPlugArray()
shaderPlug.connectedTo(material, 1, 0)
for j in range(material.length()):
materialNode = OpenMaya.MFnDependencyNode(material[j].node())
colorPlug = materialNode.findPlug("color")
dgIt = OpenMaya.MItDependencyGraph(
colorPlug,
OpenMaya.MFn.kFileTexture,
OpenMaya.MItDependencyGraph.kUpstream,
OpenMaya.MItDependencyGraph.kBreadthFirst,
OpenMaya.MItDependencyGraph.kNodeLevel)
texturePath = ""
try: # If there is no texture, this part can throw an exception
dgIt.disablePruningOnFilter()
textureNode = OpenMaya.MFnDependencyNode(dgIt.currentItem())
texturePlug = textureNode.findPlug("fileTextureName")
texturePath = os.path.basename(texturePlug.asString())
except Exception:
pass
textures[i] = (materialNode.name(), texturePath)
texturesToFaces = []
for i in range(shaderIndices.length()):
if shaderIndices[i] in textures:
texturesToFaces.append(textures[shaderIndices[i]])
else:
texturesToFaces.append(None)
return texturesToFaces
def WriteJointData(f, jointC):
jointNode = jointC[1]
# Get the joint's transform
path = OpenMaya.MDagPath()
jointNode.getPath(path)
transform = OpenMaya.MFnTransform(path)
# Get joint position
pos = transform.getTranslation(OpenMaya.MSpace.kTransform)
# Get scale (almost always 1)
scaleUtil = OpenMaya.MScriptUtil()
scaleUtil.createFromList([1,1,1], 3)
scalePtr = scaleUtil.asDoublePtr()
transform.getScale(scalePtr)
scale = [OpenMaya.MScriptUtil.getDoubleArrayItem(scalePtr, 0), OpenMaya.MScriptUtil.getDoubleArrayItem(scalePtr, 1), OpenMaya.MScriptUtil.getDoubleArrayItem(scalePtr, 2)]
# Get rotation matrix (mat is a 4x4, but the last row and column arn't needed)
jointRotQuat = __math_matrixtoquat__(cmds.getAttr(path.fullPathName()+".matrix"))
eulerRotation = jointRotQuat.asEulerRotation()
joint_offset = (pos.x*CM_TO_INCH, pos.y*CM_TO_INCH, pos.z*CM_TO_INCH)
joint_rotation = (eulerRotation.x,eulerRotation.y,eulerRotation.z)
joint_scale = (scale[0], scale[1], scale[2])
f.write("%f %f %f %f %f %f\n" % (joint_offset[0] * scale[0], joint_offset[1] * scale[1], joint_offset[2] * scale[2], joint_rotation[0], joint_rotation[1], joint_rotation[2]))
def GetJointData(jointC):
jointNode = jointC[1]
# Get the joint's transform
path = OpenMaya.MDagPath()
jointNode.getPath(path)
transform = OpenMaya.MFnTransform(path)
# Get joint position
pos = transform.getTranslation(OpenMaya.MSpace.kTransform)
# Get scale (almost always 1)
scaleUtil = OpenMaya.MScriptUtil()
scaleUtil.createFromList([1,1,1], 3)
scalePtr = scaleUtil.asDoublePtr()
transform.getScale(scalePtr)
scale = [OpenMaya.MScriptUtil.getDoubleArrayItem(scalePtr, 0), OpenMaya.MScriptUtil.getDoubleArrayItem(scalePtr, 1), OpenMaya.MScriptUtil.getDoubleArrayItem(scalePtr, 2)]
# Get rotation matrix (mat is a 4x4, but the last row and column arn't needed)
jointRotQuat = __math_matrixtoquat__(cmds.getAttr(path.fullPathName()+".matrix"))
joint_offset = (pos.x*CM_TO_INCH * scale[0], pos.y*CM_TO_INCH * scale[1], pos.z*CM_TO_INCH * scale[2])
return ( joint_offset, jointRotQuat )
def WriteJointDataSubstracted(f, jointC, jointData):
jointNode = jointC[1]
# Get the joint's transform
path = OpenMaya.MDagPath()
jointNode.getPath(path)
transform = OpenMaya.MFnTransform(path)
# Get joint position
pos = transform.getTranslation(OpenMaya.MSpace.kTransform)
# Get scale (almost always 1)
scaleUtil = OpenMaya.MScriptUtil()
scaleUtil.createFromList([1,1,1], 3)
scalePtr = scaleUtil.asDoublePtr()
transform.getScale(scalePtr)
scale = [OpenMaya.MScriptUtil.getDoubleArrayItem(scalePtr, 0), OpenMaya.MScriptUtil.getDoubleArrayItem(scalePtr, 1), OpenMaya.MScriptUtil.getDoubleArrayItem(scalePtr, 2)]
# Get rotation matrix (mat is a 4x4, but the last row and column arn't needed)
jointRotQuat = __math_matrixtoquat__(cmds.getAttr(path.fullPathName()+".matrix"))
jointInvQuat = __quat_inverse(jointData[1])
jointSubQuat = __quat_multiply(jointInvQuat, jointRotQuat)
eulerRotation = jointSubQuat.asEulerRotation()
joint_offset = (pos.x*CM_TO_INCH * scale[0], pos.y*CM_TO_INCH * scale[1], pos.z*CM_TO_INCH * scale[2])
joint_rotation = (eulerRotation.x,eulerRotation.y,eulerRotation.z)
joint_scale = (scale[0], scale[1], scale[2])
f.write("%f %f %f %f %f %f\n" % (joint_offset[0]-jointData[0][0], joint_offset[1]-jointData[0][1], joint_offset[2]-jointData[0][2], joint_rotation[0], joint_rotation[1], joint_rotation[2]))
def __toMayaQuat(x,y,z,w):
return OpenMaya.MQuaternion(x, y, z, w)
def __QuatToArray(q):
return [q.x, q.y, q.z, q.w]
def __quat_conjugate(quat):
result = OpenMaya.MQuaternion()
result.x = -quat.x
result.y = -quat.y
result.z = -quat.z
result.w = quat.w
return result
def __quat_dotproduct(quat1, quat2):
return quat1.x * quat2.x + quat1.y * quat2.y + quat1.z * quat2.z + quat1.w * quat2.w
def __quat_inverse(quat):
dotp = __quat_dotproduct(quat, quat)
conjugated = __quat_conjugate(quat)
if(dotp > 0):
inv = 1.0 / dotp
conjugated.x *= inv
conjugated.y *= inv
conjugated.z *= inv
conjugated.w *= inv
return conjugated
def __quat_align(p, q):
a = 0
b = 0
result = OpenMaya.MQuaternion()
for i in range(0, 4):
a += (p[i]-q[i])*(p[i]-q[i])
b += (p[i]+q[i])*(p[i]+q[i])
if(a > b):
result.x = -q.x
result.y = -q.y
result.z = -q.z
result.w = -q.w
else:
result.x = q.x
result.y = q.y
result.z = q.z
result.w = q.w
return result
def __quat_multiply(p, q):
q2 = __quat_align(p, q)
result = OpenMaya.MQuaternion()
result.x = p.x * q2.w + p.y * q2.z - p.z * q2.y + p.w * q2.x
result.y = -p.x * q2.z + p.y * q2.w + p.z * q2.x + p.w * q2.y
result.z = p.x * q2.y - p.y * q2.x + p.z * q2.w + p.w * q2.z
result.w = -p.x * q2.x - p.y * q2.y - p.z * q2.z + p.w * q2.w
return result
# Converts a set of vertices (toConvertVertexIndices) from object-relative IDs to face-relative IDs
# vertexIndices is a list of object-relative vertex indices in face order (from polyIter.getVertices)
# toConvertVertexIndices is any set of vertices from the same faces as vertexIndices, not necessarily the same length
# Returns false if a vertex index is unable to be converted (= bad vertex values)
def VerticesObjRelToLocalRel(vertexIndices, toConvertVertexIndices):
# http://svn.gna.org/svn/cal3d/trunk/cal3d/plugins/cal3d_maya_exporter/MayaMesh.cpp
localVertexIndices = OpenMaya.MIntArray()
for i in range(toConvertVertexIndices.length()):
found = False
for j in range(vertexIndices.length()):
if toConvertVertexIndices[i] == vertexIndices[j]:
localVertexIndices.append(j)
found = True
break
if not found:
return False
return localVertexIndices
def GetShapes(joints):
# Vars
meshes = []
verts = []
tris = []
materialDict = {}
materials = []
# Convert the joints to a dictionary, for simple searching for joint indices
jointDict = {}
for i, joint in enumerate(joints):
jointDict[joint[1].partialPathName()] = i
# Get all selected objects
selectedObjects = OpenMaya.MSelectionList()
OpenMaya.MGlobal.getActiveSelectionList(selectedObjects)
# The global vert index at the start of each object
currentStartingVertIndex = 0
# Loop through all objects
for i in range(0, selectedObjects.length()):
# Get data on object
object = OpenMaya.MObject()
dagPath = OpenMaya.MDagPath()
selectedObjects.getDependNode(i, object)
selectedObjects.getDagPath(i, dagPath)
# Ignore dag nodes that aren't shapes or shape transforms
if not dagPath.hasFn(OpenMaya.MFn.kMesh):
ProgressBarStep()
continue
# Lower path to shape node
# Selecting a shape transform or shape will get the same dagPath to the shape using this
dagPath.extendToShape()
# Check for duplicates
if dagPath.partialPathName() in meshes:
ProgressBarStep()
continue
# Add shape to list
meshes.append(dagPath.partialPathName())
# Get mesh
mesh = OpenMaya.MFnMesh(dagPath)
# Get skin cluster
clusterName = mel.eval("findRelatedSkinCluster " + dagPath.partialPathName()) # I couldn't figure out how to get the skin cluster via the API
hasSkin = False
if clusterName != None and clusterName != "" and not clusterName.isspace():
hasSkin = True
selList = OpenMaya.MSelectionList()
selList.add(clusterName)
clusterNode = OpenMaya.MObject()
selList.getDependNode(0, clusterNode)
skin = OpenMayaAnim.MFnSkinCluster(clusterNode)
# Loop through all vertices
vertIter = OpenMaya.MItMeshVertex(dagPath)
while not vertIter.isDone():
if not hasSkin:
verts.append((vertIter.position(OpenMaya.MSpace.kWorld), []))
vertIter.next()
continue
# Get weight values
weightValues = OpenMaya.MDoubleArray()
numWeights = OpenMaya.MScriptUtil() # Need this because getWeights crashes without being passed a count
skin.getWeights(dagPath, vertIter.currentItem(), weightValues, numWeights.asUintPtr())
# Get weight names
weightJoints = OpenMaya.MDagPathArray()
skin.influenceObjects(weightJoints)
# Make sure the list of weight values and names match
if weightValues.length() != weightJoints.length():
PrintWarning("Failed to retrieve vertex weight list on '%s.vtx[%d]'; using default joints." % (dagPath.partialPathName(), vertIter.index()))
# Remove weights of value 0 or weights from unexported joints
finalWeights = []
weightsSize = 0
for i in range(0, weightJoints.length()):
if weightValues[i] < 0.000001: # 0.000001 is the smallest decimal in xmodel exports
continue
jointName = weightJoints[i].partialPathName()
if not jointName in jointDict:
PrintWarning("Unexported joint %s is influencing vertex '%s.vtx[%d]' by %f%%" % (("'%s'" % jointName).ljust(15), dagPath.partialPathName(), vertIter.index(), weightValues[i]*100))
else:
finalWeights.append([jointDict[jointName], weightValues[i]])
weightsSize += weightValues[i]
# Make sure the total weight adds up to 1
if weightsSize > 0:
weightMultiplier = 1 / weightsSize
for weight in finalWeights:
weight[1] *= weightMultiplier
verts.append((
vertIter.position(OpenMaya.MSpace.kWorld), # XYZ position
finalWeights # List of weights
))
# Next vert
vertIter.next()
# Get materials used by this mesh
meshMaterials = GetMaterialsFromMesh(mesh, dagPath)
# Loop through all faces
polyIter = OpenMaya.MItMeshPolygon(dagPath)
currentObjectVertexOffset = 0
while not polyIter.isDone():
# Get this poly's material
polyMaterial = meshMaterials[polyIter.index()]
# Every face must have a material
if polyMaterial == None:
PrintWarning("Found no material on face '%s.f[%d]'; ignoring face" % (dagPath.partialPathName(), polyIter.index()))
polyIter.next()
continue
# Add this poly's material to the global list of used materials
if not polyMaterial[0] in materialDict:
materialDict[polyMaterial[0]] = len(materials)
materials.append(polyMaterial)
# Get vertex indices of this poly, and the vertex indices of this poly's triangles
trianglePoints = OpenMaya.MPointArray()
triangleIndices = OpenMaya.MIntArray()
vertexIndices = OpenMaya.MIntArray()
polyIter.getTriangles(trianglePoints, triangleIndices)
polyIter.getVertices(vertexIndices)
# localTriangleIndices is the same as triangleIndices, except each vertex is listed as the face-relative index intead of the object-realtive index
localTriangleIndices = VerticesObjRelToLocalRel(vertexIndices, triangleIndices)
if localTriangleIndices == False:
return "Failed to convert object-relative vertices to face-relative on poly '%s.f[%d]'" % (dagPath.partialPathName(), polyIter.index())
# Note: UVs, normals, and colors, are "per-vertex per face", because even though two faces may share
# a vertex, they might have different UVs, colors, or normals. So, each face has to contain this info
# for each of it's vertices instead of each vertex alone
Us = OpenMaya.MFloatArray()
Vs = OpenMaya.MFloatArray()
normals = OpenMaya.MVectorArray()
polyIter.getUVs(Us, Vs)
polyIter.getNormals(normals, OpenMaya.MSpace.kWorld)
# Add each triangle in this poly to the global face list
for i in range(triangleIndices.length()/3): # vertexIndices.length() has 3 values per triangle
# Put local indices into an array for easy access
locals = [localTriangleIndices[i*3], localTriangleIndices[i*3+1], localTriangleIndices[i*3+2]]
# Using polyIter.getColors() doesn't always work - sometimes values in the return array would
# be valid Python objects, but when used they would cause Maya to completely crash. No idea
# why that happens, but getting the colors individually fixed the problem.
vert0Color = OpenMaya.MColor()
vert1Color = OpenMaya.MColor()
vert2Color = OpenMaya.MColor()
polyIter.getColor(vert0Color, locals[0])
polyIter.getColor(vert1Color, locals[1])
polyIter.getColor(vert2Color, locals[2])
# Note: Vertices are in 0,2,1 order to make CoD happy
tris.append((
len(meshes)-1, # Shape index
materialDict[polyMaterial[0]], # Matertial index
(currentStartingVertIndex + triangleIndices[i*3], currentStartingVertIndex + triangleIndices[i*3+1], currentStartingVertIndex + triangleIndices[i*3+2]), # Vert indices
((Us[locals[0]], 1-Vs[locals[0]]), (Us[locals[1]], 1-Vs[locals[1]]), (Us[locals[2]], 1-Vs[locals[2]])), # UVs
(vert0Color, vert1Color, vert2Color), # Colors
(OpenMaya.MVector(normals[locals[0]]), OpenMaya.MVector(normals[locals[1]]), OpenMaya.MVector(normals[locals[2]])) # Normals; Must copy the normals into a new container, because the original is destructed at the end of this poltIter iteration.
))
# Next poly
polyIter.next()
# Update starting vertex index
currentStartingVertIndex = len(verts)
ProgressBarStep()
# Error messages
if len(meshes) == 0:
return "No meshes selected to export."
if len(verts) == 0:
return "No vertices found in selected meshes."
if len(tris) == 0:
return "No faces found in selected meshes."
if len(materials) == 0:
return "No materials found on the selected meshes."
# Done!
return {"meshes": meshes, "verts": verts, "faces": tris, "materials": materials}
# EXPORT
def ExportSMDModel(filePath):
currentunit_state = cmds.currentUnit(query=True, linear=True)
currentangle_state = cmds.currentUnit(query=True, angle=True)
cmds.autoKeyframe(state=False)
cmds.currentUnit(linear="cm", angle="deg")
numSelectedObjects = len(cmds.ls(selection=True))
if numSelectedObjects == 0:
return "Error: No objects selected for export"
# Get data
joints = GetJointList()
if len(joints) > 128:
print "Warning: More than 128 joints have been selected. The model might not compile."
shapes = GetShapes(joints)
if type(shapes) == str:
return shapes
# Open file
f = None
try:
# Create export directory if it doesn't exist
directory = os.path.dirname(filePath)
if not os.path.exists(directory):
os.makedirs(directory)
# Create file
f = open(filePath, 'w')
except (IOError, OSError) as e:
typex, value, traceback = sys.exc_info()
return "Unable to create file:\n\n%s" % value.strerror
# Write header
f.write("// Exported with Source Maya Tools\n")
if cmds.file(query=True, exists=True):
f.write("// Scene: '%s'\n" % os.path.normpath(os.path.abspath(cmds.file(query=True, sceneName=True))).encode('ascii', 'ignore')) # Ignore Ascii characters using .encode()
else:
f.write("// Scene: Unsaved\n\n")
f.write("version 1\n")
f.write("nodes\n")
if len(joints) == 0:
f.write("0 \"tag_origin\" -1\n")
else:
for i, joint in enumerate(joints):
name = joint[1].partialPathName().split("|")
name = name[len(name)-1].split(":") # Remove namespace prefixes
if REPLACE_FIRST_UNDERSCORE == True:
name = name[len(name)-1].replace('_', '.', 1)
else:
name = name[len(name)-1]
f.write("%i \"%s\" %i\n" % (i, name, joint[0]))
f.write("end\n")
f.write("skeleton\n")
f.write("time 0\n")
if len(joints) == 0:
f.write("0 0 0 0 0 0 0\n")
else:
for i, joint in enumerate(joints):
f.write("%i " % (i))
WriteJointData(f, joint)
f.write("end\n")
f.write("triangles\n")
verts = shapes["verts"]
materials = shapes["materials"]
for j, face in enumerate(shapes["faces"]):
f.write("%s\n" % (materials[face[1]][0].split(":")[-1]))
for i in range(0, 3):
f.write("0 %f %f %f %f %f %f %f %f " % (
verts[face[2][i]][0].x*CM_TO_INCH, verts[face[2][i]][0].y*CM_TO_INCH, verts[face[2][i]][0].z*CM_TO_INCH,
face[5][i].x, face[5][i].y, face[5][i].z,
face[3][i][0], 1-face[3][i][1]
))
f.write(" %i " % max(len(verts[face[2][i]][1]), 1))
if len(verts[face[2][i]][1]) > 0:
for bone in verts[face[2][i]][1]:
f.write(" %i %f " % (bone[0], bone[1]))
else:
f.write(" 0 1.000000 ")
f.write("\n")
f.write("end\n")
f.close()
cmds.currentUnit(linear=currentunit_state, angle=currentangle_state)
def ExportSMDAnim(filePath):
currentunit_state = cmds.currentUnit(query=True, linear=True)
currentangle_state = cmds.currentUnit(query=True, angle=True)
cmds.autoKeyframe(state=False)
cmds.currentUnit(linear="cm", angle="deg")
numSelectedObjects = len(cmds.ls(selection=True))
if numSelectedObjects == 0:
return "Error: No objects selected for export"
# Get data
joints = GetJointList()
if len(joints) == 0:
return "Error: No joints selected for export"
if len(joints) > 128:
print "Warning: More than 128 joints have been selected. The animation might not compile."
frameStart = cmds.intField(OBJECT_NAMES['smdanim'][0]+"_FrameStartField", query=True, value=True)
frameEnd = cmds.intField(OBJECT_NAMES['smdanim'][0]+"_FrameEndField", query=True, value=True)
substract = cmds.checkBox(OBJECT_NAMES['smdanim'][0]+("_SubstractCheckBox"), query=True, value=True)
substractFrame = cmds.intField(OBJECT_NAMES['smdanim'][0]+("_SubstractFrame"), query=True, value=True)
# Open file
f = None
try:
# Create export directory if it doesn't exist
directory = os.path.dirname(filePath)
if not os.path.exists(directory):
os.makedirs(directory)
# Create file
f = open(filePath, 'w')
except (IOError, OSError) as e:
typex, value, traceback = sys.exc_info()
return "Unable to create file:\n\n%s" % value.strerror
# Write header
f.write("// Exported with Source Maya Tools\n")
if cmds.file(query=True, exists=True):
f.write("// Scene: '%s'\n" % os.path.normpath(os.path.abspath(cmds.file(query=True, sceneName=True))).encode('ascii', 'ignore')) # Ignore Ascii characters using .encode()
else:
f.write("// Scene: Unsaved\n\n")
f.write("version 1\n")
f.write("nodes\n")
if len(joints) == 0:
f.write("0 \"tag_origin\" -1\n")
else:
for i, joint in enumerate(joints):
name = joint[1].partialPathName().split("|")
name = name[len(name)-1].split(":") # Remove namespace prefixes
name = name[len(name)-1].replace('_', '.', 1)
f.write("%i \"%s\" %i\n" % (i, name, joint[0]))
f.write("end\n")
f.write("skeleton\n")
cmds.currentTime(substractFrame)
jointsToSubstract = []
for i, joint in enumerate(joints):
jointsToSubstract.append(GetJointData(joint))
for i in range(int(frameStart), int(frameEnd+1)):
f.write("time %i\n" % (i - frameStart))
cmds.currentTime(i)
if len(joints) == 0:
f.write("0 0 0 0 0 0 0\n")
else:
for j, joint in enumerate(joints):
f.write("%i " % (j))
if(substract == True):
WriteJointDataSubstracted(f, joint, jointsToSubstract[j])
else:
WriteJointData(f, joint)
f.write("end\n")
f.close()
cmds.currentUnit(linear=currentunit_state, angle=currentangle_state)
def GetRootFolder(firstTimePrompt=False, category="none"):
SrcRootPath = ""
try:
storageKey = reg.OpenKey(GLOBAL_STORAGE_REG_KEY[0], GLOBAL_STORAGE_REG_KEY[1])
SrcRootPath = reg.QueryValueEx(storageKey, "RootPath")[0]
reg.CloseKey(storageKey)
except WindowsError:
# First time, create key
storageKey = reg.CreateKey(GLOBAL_STORAGE_REG_KEY[0], GLOBAL_STORAGE_REG_KEY[1])
reg.SetValueEx(storageKey, "RootPath", 0, reg.REG_SZ, "")
reg.CloseKey(storageKey)
if not os.path.isdir(SrcRootPath):
SrcRootPath = ""
return SrcRootPath
def SetRootFolder(msg=None, game="none"):
#if game == "none":
# game = currentGame
#if game == "none":
# res = cmds.confirmDialog(message="Please select the game you're working with", button=['OK'], defaultButton='OK', title="WARNING")
# return None
# Get current root folder (this also makes sure the reg key exists)
srcRootPath = GetRootFolder(False, game)
# Open input box
#if cmds.promptDialog(title="Set Root Path", message=msg or "Change your root path:\t\t\t", text=srcRootPath) != "Confirm":
# return None
srcRootPath = cmds.fileDialog2(fileMode=3, dialogStyle=2)[0] + "/"
# Check to make sure the path exists
if not os.path.isdir(srcRootPath):
MessageBox("Given root path does not exist")
return None
# cmds.promptDialog(title="Set Root Path", message=srcRootPath)
# Set path
# , 0, reg.KEY_SET_VALUE)
storageKey = reg.OpenKey(GLOBAL_STORAGE_REG_KEY[0], GLOBAL_STORAGE_REG_KEY[1], 0, reg.KEY_SET_VALUE)
reg.SetValueEx(storageKey, "RootPath", 0, reg.REG_SZ, srcRootPath)
reg.CloseKey(storageKey)
return srcRootPath
# Windows
# ------------------------------------------------------------------------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------- XModel Export Window ----------------------------------------------------------------------
# ------------------------------------------------------------------------------------------------------------------------------------------------------------------
def CreateSMDModelWindow():
# Create window
if cmds.control(OBJECT_NAMES['smdmodel'][0], exists=True):
cmds.deleteUI(OBJECT_NAMES['smdmodel'][0])
cmds.window(OBJECT_NAMES['smdmodel'][0], title=OBJECT_NAMES['smdmodel'][1], width=340, height=1, retain=True, maximizeButton=False)
form = cmds.formLayout(OBJECT_NAMES['smdmodel'][0]+"_Form")
# Controls
slotDropDown = cmds.optionMenu(OBJECT_NAMES['smdmodel'][0]+"_SlotDropDown", changeCommand=lambda x:RefreshSMDModelWindow(), annotation="Each slot contains different a export path, settings, and saved selection")
for i in range(1, EXPORT_WINDOW_NUMSLOTS+1):
cmds.menuItem(OBJECT_NAMES['smdmodel'][0]+"_SlotDropDown"+("_s%i" % i), label="Slot %i" % i)
separator1 = cmds.separator(style='in', height=16)
separator2 = cmds.separator(style='in')
saveToLabel = cmds.text(label="Save to:", annotation="This is where the .xmodel_export is saved to")
saveToField = cmds.textField(OBJECT_NAMES['smdmodel'][0]+"_SaveToField", height=21, changeCommand=lambda x:GeneralWindow_SaveToField('smdmodel'), annotation="This is where the .xmodel_export is saved to")
fileBrowserButton = cmds.button(label="...", height=21, command=lambda x:GeneralWindow_FileBrowser('smdmodel', "SMD File (*.smd)"), annotation="Open a file browser dialog")
exportSelectedButton = cmds.button(label="Export Selected", command=lambda x:GeneralWindow_ExportSelected('smdmodel', False), annotation="Export all currently selected objects from the scene (current frame)\nWarning: Will automatically overwrite if the export path if it already exists")
saveSelectionButton = cmds.button(label="Save Selection", command=lambda x:GeneralWindow_SaveSelection('smdmodel'), annotation="Save the current object selection")
getSavedSelectionButton = cmds.button(label="Get Saved Selection", command=lambda x:GeneralWindow_GetSavedSelection('smdmodel'), annotation="Reselect the saved selection")
exportMultipleSlotsButton = cmds.button(label="Export Multiple Slots", command=lambda x:GeneralWindow_ExportMultiple('smdmodel'), annotation="Automatically export multiple slots at once, using each slot's saved selection")
exportInMultiExportCheckbox = cmds.checkBox(OBJECT_NAMES['smdmodel'][0]+"_UseInMultiExportCheckBox", label="Use current slot for Export Multiple", changeCommand=lambda x:GeneralWindow_ExportInMultiExport('smdmodel'), annotation="Check this make the 'Export Multiple Slots' button export this slot")
# Setup form
cmds.formLayout(form, edit=True,
attachForm=[(slotDropDown, 'top', 6), (slotDropDown, 'left', 10), (slotDropDown, 'right', 10),
(separator1, 'left', 0), (separator1, 'right', 0),
(separator2, 'left', 0), (separator2, 'right', 0),
(saveToLabel, 'left', 12),
(fileBrowserButton, 'right', 10),
(exportMultipleSlotsButton, 'bottom', 6), (exportMultipleSlotsButton, 'left', 10),
(exportInMultiExportCheckbox, 'bottom', 9), (exportInMultiExportCheckbox, 'right', 6),
(exportSelectedButton, 'left', 10),
(saveSelectionButton, 'right', 10)],
#(exportSelectedButton, 'bottom', 6), (exportSelectedButton, 'left', 10),
#(saveSelectionButton, 'bottom', 6), (saveSelectionButton, 'right', 10),
#(getSavedSelectionButton, 'bottom', 6)],
attachControl=[ (separator1, 'top', 0, slotDropDown),
(saveToLabel, 'bottom', 9, exportSelectedButton),
(saveToField, 'bottom', 5, exportSelectedButton), (saveToField, 'left', 5, saveToLabel), (saveToField, 'right', 5, fileBrowserButton),
(fileBrowserButton, 'bottom', 5, exportSelectedButton),
(exportSelectedButton, 'bottom', 5, separator2),
(saveSelectionButton, 'bottom', 5, separator2),
(getSavedSelectionButton, 'bottom', 5, separator2), (getSavedSelectionButton, 'right', 10, saveSelectionButton),
(separator2, 'bottom', 5, exportMultipleSlotsButton)])
def RefreshSMDModelWindow():
# Refresh/create node
if len(cmds.ls(OBJECT_NAMES['smdmodel'][2])) == 0:
cmds.createNode("renderLayer", name=OBJECT_NAMES['smdmodel'][2], skipSelect=True)
cmds.lockNode(OBJECT_NAMES['smdmodel'][2], lock=False)
if not cmds.attributeQuery("slot", node=OBJECT_NAMES['smdmodel'][2], exists=True):
cmds.addAttr(OBJECT_NAMES['smdmodel'][2], longName="slot", attributeType='short', defaultValue=1)
if not cmds.attributeQuery("paths", node=OBJECT_NAMES['smdmodel'][2], exists=True):
cmds.addAttr(OBJECT_NAMES['smdmodel'][2], longName="paths", multi=True, dataType='string')
cmds.setAttr(OBJECT_NAMES['smdmodel'][2]+".paths", size=EXPORT_WINDOW_NUMSLOTS)
if not cmds.attributeQuery("selections", node=OBJECT_NAMES['smdmodel'][2], exists=True):
cmds.addAttr(OBJECT_NAMES['smdmodel'][2], longName="selections", multi=True, dataType='stringArray')
cmds.setAttr(OBJECT_NAMES['smdmodel'][2]+".selections", size=EXPORT_WINDOW_NUMSLOTS)
if not cmds.attributeQuery("useinmultiexport", node=OBJECT_NAMES['smdmodel'][2], exists=True):
cmds.addAttr(OBJECT_NAMES['smdmodel'][2], longName="useinmultiexport", multi=True, attributeType='bool', defaultValue=False)
cmds.setAttr(OBJECT_NAMES['smdmodel'][2]+".useinmultiexport", size=EXPORT_WINDOW_NUMSLOTS)
cmds.lockNode(OBJECT_NAMES['smdmodel'][2], lock=True)
# Set values
slotIndex = cmds.optionMenu(OBJECT_NAMES['smdmodel'][0]+"_SlotDropDown", query=True, select=True)
path = cmds.getAttr(OBJECT_NAMES['smdmodel'][2]+(".paths[%i]" % slotIndex))
cmds.setAttr(OBJECT_NAMES['smdmodel'][2]+".slot", slotIndex)
cmds.textField(OBJECT_NAMES['smdmodel'][0]+"_SaveToField", edit=True, fileName=path)
useInMultiExport = cmds.getAttr(OBJECT_NAMES['smdmodel'][2]+(".useinmultiexport[%i]" % slotIndex))
cmds.checkBox(OBJECT_NAMES['smdmodel'][0]+"_UseInMultiExportCheckBox", edit=True, value=useInMultiExport)
# ------------------------------------------------------------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------- XAnim Export Window ----------------------------------------------------------------------
# ------------------------------------------------------------------------------------------------------------------------------------------------------------------
def CreateSMDAnimWindow():
# Create window
if cmds.control(OBJECT_NAMES['smdanim'][0], exists=True):
cmds.deleteUI(OBJECT_NAMES['smdanim'][0])
cmds.window(OBJECT_NAMES['smdanim'][0], title=OBJECT_NAMES['smdanim'][1], width=1, height=1, retain=True, maximizeButton=False)
form = cmds.formLayout(OBJECT_NAMES['smdanim'][0]+"_Form")
# Controls
slotDropDown = cmds.optionMenu(OBJECT_NAMES['smdanim'][0]+"_SlotDropDown", changeCommand=lambda x:RefreshSMDAnimWindow(), annotation="Each slot contains different a export path, frame range, notetrack, and saved selection")
for i in range(1, EXPORT_WINDOW_NUMSLOTS+1):
cmds.menuItem(OBJECT_NAMES['smdanim'][0]+"_SlotDropDown"+("_s%i" % i), label="Slot %i" % i)
separator1 = cmds.separator(style='in')
separator2 = cmds.separator(style='in')
separator3 = cmds.separator(style='in')
framesLabel = cmds.text(label="Frames:", annotation="Range of frames to export")
framesStartField = cmds.intField(OBJECT_NAMES['smdanim'][0]+"_FrameStartField", height=21, width=35, minValue=0, changeCommand=SMDAnimWindow_UpdateFrameRange, annotation="Starting frame to export (inclusive)")
framesToLabel = cmds.text(label="to")
framesEndField = cmds.intField(OBJECT_NAMES['smdanim'][0]+"_FrameEndField", height=21, width=35, minValue=0, changeCommand=SMDAnimWindow_UpdateFrameRange, annotation="Ending frame to export (inclusive)")
substractCheckbox = cmds.checkBox(OBJECT_NAMES['smdanim'][0]+"_SubstractCheckBox", label="Substract", changeCommand=SMDAnimWindow_UpdateAnimData, annotation="Check this to substract animation data using a specified frame")
substractFrameField = cmds.intField(OBJECT_NAMES['smdanim'][0]+"_SubstractFrame", height=21, width=35, minValue=0, changeCommand=SMDAnimWindow_UpdateAnimData, annotation="The frame you want to substract ")
saveToLabel = cmds.text(label="Save to:", annotation="This is where .smd is saved to")
saveToField = cmds.textField(OBJECT_NAMES['smdanim'][0]+"_SaveToField", height=21, changeCommand=lambda x:GeneralWindow_SaveToField('smdanim'), annotation="This is where .xanim_export is saved to")
fileBrowserButton = cmds.button(label="...", height=21, command=lambda x:GeneralWindow_FileBrowser('smdanim', "SMD File (*.smd)"), annotation="Open a file browser dialog")
exportSelectedButton = cmds.button(label="Export Selected", command=lambda x:GeneralWindow_ExportSelected('smdanim', False), annotation="Export all currently selected joints from the scene (specified frames)\nWarning: Will automatically overwrite if the export path if it already exists")
saveSelectionButton = cmds.button(label="Save Selection", command=lambda x:GeneralWindow_SaveSelection('smdanim'), annotation="Save the current object selection")
getSavedSelectionButton = cmds.button(label="Get Saved Selection", command=lambda x:GeneralWindow_GetSavedSelection('smdanim'), annotation="Reselect the saved selection")
exportMultipleSlotsButton = cmds.button(label="Export Multiple Slots", command=lambda x:GeneralWindow_ExportMultiple('smdanim'), annotation="Automatically export multiple slots at once, using each slot's saved selection")
exportInMultiExportCheckbox = cmds.checkBox(OBJECT_NAMES['smdanim'][0]+"_UseInMultiExportCheckBox", label="Use current slot for Export Multiple", changeCommand=lambda x:GeneralWindow_ExportInMultiExport('smdanim'), annotation="Check this make the 'Export Multiple Slots' button export this slot")
# Setup form
cmds.formLayout(form, edit=True,
attachForm=[(slotDropDown, 'top', 6), (slotDropDown, 'left', 10), (slotDropDown, 'right', 10),
(separator1, 'left', 0), (separator1, 'right', 0),
(framesLabel, 'left', 10),
(substractCheckbox, 'left', 10),
(separator2, 'left', 0), (separator2, 'right', 0),
(saveToLabel, 'left', 12),
(fileBrowserButton, 'right', 10),
(exportMultipleSlotsButton, 'bottom', 6), (exportMultipleSlotsButton, 'left', 10),
(exportInMultiExportCheckbox, 'bottom', 9), (exportInMultiExportCheckbox, 'right', 6),
(exportSelectedButton, 'left', 10),
(saveSelectionButton, 'right', 10),
(separator3, 'left', 0), (separator3, 'right', 0)],
attachControl=[ (separator1, 'top', 6, slotDropDown),
(framesLabel, 'top', 8, separator1),
(framesStartField, 'top', 5, separator1), (framesStartField, 'left', 4, framesLabel),
(framesToLabel, 'top', 8, separator1), (framesToLabel, 'left', 4+35+4, framesLabel),
(framesEndField, 'top', 5, separator1), (framesEndField, 'left', 4, framesToLabel),
(substractCheckbox, 'bottom', 10, separator2), (substractFrameField, 'left', 10, substractCheckbox), (substractFrameField, 'bottom', 8, separator2),
(separator2, 'bottom', 5, fileBrowserButton),
(saveToLabel, 'bottom', 10, exportSelectedButton),
(saveToField, 'bottom', 5, exportSelectedButton), (saveToField, 'left', 5, saveToLabel), (saveToField, 'right', 5, fileBrowserButton),
(fileBrowserButton, 'bottom', 5, exportSelectedButton),
(exportSelectedButton, 'bottom', 5, separator3),
(saveSelectionButton, 'bottom', 5, separator3),
(getSavedSelectionButton, 'bottom', 5, separator3), (getSavedSelectionButton, 'right', 10, saveSelectionButton),
(separator3, 'bottom', 5, exportMultipleSlotsButton)
])
def SMDAnimWindow_UpdateFrameRange(required_parameter):
slotIndex = cmds.optionMenu(OBJECT_NAMES['smdanim'][0]+"_SlotDropDown", query=True, select=True)
start = cmds.intField(OBJECT_NAMES['smdanim'][0]+"_FrameStartField", query=True, value=True)
end = cmds.intField(OBJECT_NAMES['smdanim'][0]+"_FrameEndField", query=True, value=True)
cmds.setAttr(OBJECT_NAMES['smdanim'][2]+(".frameRanges[%i]" % slotIndex), start, end, type='long2')
def SMDAnimWindow_UpdateFramerate(required_parameter):
slotIndex = cmds.optionMenu(OBJECT_NAMES['smdanim'][0]+"_SlotDropDown", query=True, select=True)
fps = cmds.intField(OBJECT_NAMES['smdanim'][0]+"_FPSField", query=True, value=True)
cmds.setAttr(OBJECT_NAMES['smdanim'][2]+(".framerate[%i]" % slotIndex), fps)
def SMDAnimWindow_UpdateMultiplier(required_parameter):
slotIndex = cmds.optionMenu(OBJECT_NAMES['smdanim'][0]+"_SlotDropDown", query=True, select=True)
fps = cmds.intField(OBJECT_NAMES['smdanim'][0]+"_qualityField", query=True, value=True)
cmds.setAttr(OBJECT_NAMES['smdanim'][2]+(".multiplier[%i]" % slotIndex), fps)
def SMDAnimWindow_UpdateAnimData(required_parameter):
slotIndex = cmds.optionMenu(OBJECT_NAMES['smdanim'][0]+"_SlotDropDown", query=True, select=True)
substractCheckbox = cmds.checkBox(OBJECT_NAMES['smdanim'][0]+"_SubstractCheckBox", query=True, value=True)
substractFrame = cmds.intField(OBJECT_NAMES['smdanim'][0]+"_SubstractFrame", query=True, value=True)
cmds.setAttr(OBJECT_NAMES['smdanim'][2]+(".substract[%i]" % slotIndex), substractCheckbox)
cmds.setAttr(OBJECT_NAMES['smdanim'][2]+(".substractFrames[%i]" % slotIndex), substractFrame)
def SMDAnimWindow_AddNote(required_parameter):
slotIndex = cmds.optionMenu(OBJECT_NAMES['smdanim'][0]+"_SlotDropDown", query=True, select=True)
if cmds.promptDialog(title="Add Note to Slot %i's Notetrack" % slotIndex, message="Enter the note's name:\t\t ") != "Confirm":
return
userInput = cmds.promptDialog(query=True, text=True)
noteName = "".join([c for c in userInput if c.isalnum() or c=="_"]) # Remove all non-alphanumeric characters
if noteName == "":
MessageBox("Invalid note name")