-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathbaseSkeletonBuilder.py
2409 lines (1886 loc) · 76.6 KB
/
baseSkeletonBuilder.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 maya.cmds import *
from names import Parity, Name, camelCaseToNice
from vectors import Vector, Colour
from control import attrState, NORMAL, HIDE, LOCK_HIDE, NO_KEY
from apiExtensions import asMObject, castToMObjects, cmpNodes
from mayaDecorators import d_unifyUndo
from maya.OpenMaya import MGlobal
from referenceUtils import ReferencedNode
import names
import filesystem
import typeFactories
import inspect
import meshUtils
import maya.cmds as cmd
import profileDecorators
#now do maya imports and maya specific assignments
import api
import maya.cmds as cmd
import rigUtils
from rigUtils import ENGINE_FWD, ENGINE_UP, ENGINE_SIDE
from rigUtils import MAYA_SIDE, MAYA_FWD, MAYA_UP
from rigUtils import Axis, resetSkinCluster
mel = api.mel
AXES = Axis.BASE_AXES
eval = __builtins__[ 'eval' ] #restore the eval function to point to python's eval
mayaVar = float( mel.eval( 'getApplicationVersionAsFloat()' ) )
TOOL_NAME = 'skeletonBuilder'
CHANNELS = ('x', 'y', 'z')
TYPICAL_HEIGHT = 70 #maya units
HUD_NAME = 'skeletonBuilderJointCountHUD'
#these are the symbols to use as standard rotation axes on bones...
BONE_AIM_VECTOR = ENGINE_FWD #this is the axis the joint should bank around, in general the axis the "aims" at the child joint
BONE_ROTATE_VECTOR = ENGINE_SIDE #this is the axis of "primary rotation" for the joint. for example, the elbow would rotate primarily in this axis, as would knees and fingers
BONE_AIM_AXIS = Axis.FromVector( BONE_AIM_VECTOR )
BONE_ROTATE_AXIS = Axis.FromVector( BONE_ROTATE_VECTOR )
_tmp = BONE_AIM_AXIS.otherAxes()
_tmp.remove( BONE_ROTATE_AXIS )
BONE_OTHER_AXIS = _tmp[0] #this is the "other" axis - ie the one thats not either BONE_AIM_AXIS or BONE_ROTATE_AXIS
BONE_OTHER_VECTOR = BONE_OTHER_AXIS.asVector()
del( _tmp )
getLocalAxisInDirection = rigUtils.getLocalAxisInDirection
getPlaneNormalForObjects = rigUtils.getPlaneNormalForObjects
#try to load the zooMirror.py plugin
try:
loadPlugin( 'zooMirror.py', quiet=True )
except:
import zooToolbox
zooToolbox.loadZooPlugin( 'zooMirror.py' )
def getScaleFromMeshes():
'''
determines a scale based on the visible meshes in the scene. If no visible
meshes are found, the TYPICAL_HEIGHT value is returend
'''
def isVisible( node ):
if not getAttr( '%s.v' % node ):
return False
for p in iterParents( node ):
if not getAttr( '%s.v' % p ): return False
return True
visibleMeshes = [ m for m in (ls( type='mesh' ) or []) if isVisible( m ) ]
if not visibleMeshes:
return TYPICAL_HEIGHT
return rigUtils.getObjsScale( visibleMeshes )
def getScaleFromSkeleton():
#lets see if there is a Root part already
scale = 0
for root in Root.IterAllParts():
t = Vector( getAttr( '%s.t' % root[0] )[0] )
scale = t.y
scale *= 1.75 #the root is roughly 4 head heights from the ground and the whole body is about 7 head heights - hence 1.75 (7/4)
#lets see if there is a spine part - between the root and the spine, we can get a
#pretty good idea of the scale for most anatomy types
scaleFromSpine = 0
spineCls = SkeletonPart.GetNamedSubclass( 'Spine' )
if spineCls is not None:
numSpines = 0
for spine in spineCls.IterAllParts():
items = spine.items
items.append( spine.getParent() )
mnx, mny, mnz, mxx, mxy, mxz = rigUtils.getTranslationExtents( items )
XYZ = mxx-mnx, mxy-mny, mxz-mnz
maxLen = max( XYZ ) * 1.5
scaleFromSpine += maxLen
numSpines += 1
#if there were spine parts found, average their scales, add them to the root scale and average them again
if numSpines:
scaleFromSpine /= float( numSpines )
scaleFromSpine *= 2.3 #ths spine is roughly 3 head heights, while the whole body is roughly 7 head heights - hence 2.3 (7/3)
scale += scaleFromSpine
scale /= 2.0
if not scale:
return getScaleFromMeshes()
return scale
def getItemScale( item ):
'''
returns the non-skinned "scale" of a joint (or skeleton part "item")
This scale uses a few metrics to determine the scale - first, the
bounds of any children are calculated and the max side of the bounding
box is found, and if non-zero returned. If the item has no children
then the radius of the joint is used (if it exists) otherwise the
magnitude of the joint translation is used.
If all the above tests fail, 1 is returned.
'''
scale = 0
children = listRelatives( item, type='transform' )
if children:
scales = []
bb = rigUtils.getTranslationExtents( children )
XYZ = bb[3]-bb[0], bb[4]-bb[1], bb[5]-bb[2]
scale = max( XYZ )
if not scale:
if objExists( '%s.radius' % item ):
scale = getAttr( '%s.radius' % item )
if not scale:
pos = Vector( getAttr( '%s.t' % item )[0] )
scale = pos.get_magnitude()
return scale or 1
def getNodeParent( obj ):
parent = listRelatives( obj, p=True, pa=True )
if parent is None:
return None
return parent[ 0 ]
def iterParents( obj, until=None ):
parent = getNodeParent( obj )
while parent is not None:
yield parent
if until is not None:
if parent == until:
return
parent = getNodeParent( parent )
def sortByHierarchy( objs ):
sortedObjs = []
for o in objs:
pCount = len( list( iterParents( o ) ) )
sortedObjs.append( (pCount, o) )
sortedObjs.sort()
return [ o[ 1 ] for o in sortedObjs ]
def getAlignSkipState( item ):
attrPath = '%s._skeletonPartSkipAlign' % item
if not objExists( attrPath ):
return False
return getAttr( attrPath )
def setAlignSkipState( item, state ):
'''
will flag a joint as user aligned - which means it will get skipped
by the alignment functions
'''
attrPath = '%s._skeletonPartSkipAlign' % item
if state:
if not objExists( attrPath ):
addAttr( item, ln='_skeletonPartSkipAlign', at='bool' )
setAttr( attrPath, True )
else:
deleteAttr( attrPath )
def d_restoreLocksAndNames(f):
'''
this decorator is for the alignment functions - it basically takes care of ensuring the children
are unparented before alignment happens, re-parented after the fact, channel unlocking and re-locking,
freezing transforms etc...
NOTE: this function gets called a lot. basically this decorator wraps all alignment functions, and
generally each joint in the skeleton has at least one alignment function run on it. Beware!
'''
def newF( item, *args, **kwargs ):
if getAlignSkipState( item ):
return
attrs = 't', 'r', 'ra'
#unparent and children in place, and store the original name, and lock
#states of attributes - we need to unlock attributes as this item will
#most likely change its orientation
children = castToMObjects( listRelatives( item, typ='transform', pa=True ) or [] ) #cast to mobjects as re-parenting can change and thus invalidate node name strings...
childrenPreStates = {}
for child in [ item ] + children:
lockStates = []
for a in attrs:
for c in CHANNELS:
attrPath = '%s.%s%s' % (child, a, c)
lockStates.append( (attrPath, getAttr( attrPath, lock=True )) )
try:
setAttr( attrPath, lock=False )
except: pass
originalChildName = str( child )
if not cmpNodes( child, item ):
child = cmd.parent( child, world=True )[0]
childrenPreStates[ child ] = originalChildName, lockStates
#make sure the rotation axis attribute is zeroed out - NOTE: we need to do this after children have been un-parented otherwise it could affect their positions
for c in CHANNELS:
setAttr( '%s.ra%s' % (item, c), 0 )
f( item, children=children, *args, **kwargs )
makeIdentity( item, a=True, r=True )
#now re-parent children
for child, (originalName, lockStates) in childrenPreStates.iteritems():
if child != item:
child = cmd.parent( child, item )[0]
child = rename( child, originalName.split( '|' )[-1] )
for attrPath, lockState in lockStates:
try:
setAttr( attrPath, lock=lockState )
except: pass
newF.__name__ = f.__name__
newF.__doc__ = f.__doc__
return newF
@d_restoreLocksAndNames
def autoAlignItem( item, invertAimAndUp=False, upVector=BONE_ROTATE_VECTOR, worldUpVector=MAYA_SIDE, worldUpObject='', upType='vector', children=None, debug=False ):
'''
for cases where there is no strong preference about how the item is aligned, this function will determine the best course of action
'''
numChildren = len( children )
#if there is more than one child, see if there is only one JOINT child...
childJoints = ls( children, type='joint' )
if len( childJoints ) == 1:
children = childJoints
#if there is only one child, aim the x-axis at said child, and aim the z-axis toward scene-up
### WARNING :: STILL NEED TO DEAL WITH CASE WHERE JOINT IS CLOSE TO AIMING AT SCENE UP
invertMult = -1 if invertAimAndUp else 1
if len( children ) == 1:
kw = { 'aimVector': BONE_AIM_VECTOR * invertMult,
'upVector': upVector * invertMult,
'worldUpVector': worldUpVector,
'worldUpType': upType }
if worldUpObject:
kw[ 'worldUpObject' ] = worldUpObject
c = aimConstraint( children[ 0 ], item, **kw )
if not debug: delete( c )
else:
for a in [ 'jo', 'r' ]:
for c in CHANNELS:
attrPath = '%s.%s%s' % (item, a, c)
if not getAttr( attrPath, settable=True ):
continue
setAttr( attrPath, 0 )
@d_restoreLocksAndNames
def alignAimAtItem( item, aimAtItem, invertAimAndUp=False, upVector=BONE_ROTATE_VECTOR, worldUpVector=MAYA_SIDE, worldUpObject='', upType='vector', children=None, debug=False ):
'''
aims the item at a specific transform in the scene. the aim axis is always BONE_AIM_VECTOR, but the up axis can be set to whatever is required
'''
invertMult = -1 if invertAimAndUp else 1
kw = { 'aimVector': BONE_AIM_VECTOR * invertMult,
'upVector': upVector * invertMult,
'worldUpVector': worldUpVector,
'worldUpType': upType }
if worldUpObject:
kw[ 'worldUpObject' ] = worldUpObject
c = aimConstraint( aimAtItem, item, **kw )
if debug: raise Exception
if not debug: delete( c )
@d_restoreLocksAndNames
def alignItemToWorld( item, children=None, skipX=False, skipY=False, skipZ=False ):
'''
aligns the item to world space axes, optionally skipping individual axes
'''
rotate( -90, -90, 0, item, a=True, ws=True )
if skipX: rotate( 0, 0, 0, item, a=True, os=True, rotateX=True )
if skipY: rotate( 0, 0, 0, item, a=True, os=True, rotateY=True )
if skipZ: rotate( 0, 0, 0, item, a=True, os=True, rotateZ=True )
@d_restoreLocksAndNames
def alignItemToLocal( item, children=None, skipX=False, skipY=False, skipZ=False ):
'''
aligns the item to local space axes, optionally skipping individual axes
'''
for skip, axis in zip( (skipX, skipY, skipZ), CHANNELS ):
if skipX:
setAttr( '%s.r%s' % (item, axis), 0 )
setAttr( '%s.jo%s' % (item, axis), 0 )
@d_restoreLocksAndNames
def alignPreserve( item, children=None ):
pass
def getCharacterMeshes():
'''
returns all "character meshes" found in the scene. These are basically defined as meshes that aren't
parented to a joint - where joints are
'''
meshes = ls( type='mesh', r=True )
meshes = set( listRelatives( meshes, p=True, pa=True ) ) #removes duplicates...
characterMeshes = set()
for mesh in meshes:
isUnderJoint = False
for parent in iterParents( mesh ):
if nodeType( parent ) == 'joint':
isUnderJoint = True
break
if not isUnderJoint:
characterMeshes.add( mesh )
return list( characterMeshes )
class SkeletonError(Exception): pass
class NotFinalizedError(SkeletonError): pass
class SceneNotSavedError(SkeletonError): pass
def getSkeletonSet():
'''
returns the "master" set used for storing skeleton parts in the scene - this isn't actually used for
anything but organizational purposes - ie the skeleton part sets are members of _this_ set, but at
no point does the existence or non-existence of this make any functional difference
'''
existing = [ node for node in ls( type='objectSet', r=True ) or [] if sets( node, q=True, text=True ) == TOOL_NAME ]
if existing:
return existing[ 0 ]
else:
skeletonParts = createNode( 'objectSet', n='skeletonParts' )
sets( skeletonParts, e=True, text=TOOL_NAME )
return skeletonParts
def createSkeletonPartContainer( name ):
'''
'''
theSet = sets( em=True, n=name, text='skeletonPrimitive' )
sets( theSet, e=True, add=getSkeletonSet() )
return theSet
def isSkeletonPartContainer( node ):
'''
tests whether the given node is a skeleton part container or not
'''
if objectType( node, isType='objectSet' ):
return sets( node, q=True, text=True ) == 'skeletonPrimitive'
return False
def getSkeletonPartContainers():
'''
returns a list of all skeleton part containers in the scene
'''
return [ node for node in ls( type='objectSet', r=True ) or [] if sets( node, q=True, text=True ) == 'skeletonPrimitive' ]
def buildSkeletonPartContainer( typeClass, kwDict, items ):
'''
builds a container for the given skeleton part items, and tags it with the various attributes needed
to track the state for a skeleton part.
'''
#if typeClass is an instance, then set its container attribute, otherwise instantiate an instance and return it
if isinstance( typeClass, SkeletonPart ):
theInstance = typeClass
typeClass = type( typeClass )
#build the container, and add the special attribute to it to
if 'idx' in kwDict:
idx = kwDict[ 'idx' ]
else:
kwDict[ 'idx' ] = idx = typeClass.GetUniqueIdx()
theContainer = createSkeletonPartContainer( 'a%sPart_%s' % (typeClass.__name__, idx) )
addAttr( theContainer, ln='_skeletonPrimitive', attributeType='compound', numberOfChildren=7 )
addAttr( theContainer, ln='typeName', dt='string', parent='_skeletonPrimitive' )
addAttr( theContainer, ln='version', at='long', parent='_skeletonPrimitive' )
addAttr( theContainer, ln='script', dt='string', parent='_skeletonPrimitive' )
addAttr( theContainer, ln='buildKwargs', dt='string', parent='_skeletonPrimitive' ) #stores the kwarg dict used to build this part
addAttr( theContainer, ln='rigKwargs', dt='string', parent='_skeletonPrimitive' ) #stores the kwarg dict to pass to the rig method
addAttr( theContainer, ln='items',
multi=True,
indexMatters=False,
attributeType='message',
parent='_skeletonPrimitive' )
addAttr( theContainer, ln='placers',
multi=True,
indexMatters=False,
attributeType='message',
parent='_skeletonPrimitive' )
#now set the attribute values...
setAttr( '%s._skeletonPrimitive.typeName' % theContainer, typeClass.__name__, type='string' )
setAttr( '%s._skeletonPrimitive.version' % theContainer, typeClass.__version__ )
setAttr( '%s._skeletonPrimitive.script' % theContainer, inspect.getfile( typeClass ), type='string' )
setAttr( '%s._skeletonPrimitive.buildKwargs' % theContainer, str( kwDict ), type='string' )
#now add all the items
items = map( str, items )
for item in set( items ):
if nodeType( item ) == 'joint':
sets( item, e=True, add=theContainer )
#if the node is a rig part container add it to this container otherwise skip it
elif objectType( item, isAType='objectSet' ):
if isSkeletonPartContainer( item ):
sets( item, e=True, add=theContainer )
#and now hook up all the controls
for idx, item in enumerate( items ):
if item is None:
continue
connectAttr( '%s.message' % item, '%s._skeletonPrimitive.items[%d]' % (theContainer, idx), f=True )
return theContainer
def d_disconnectJointsFromSkinning( f ):
'''
Will unhook all skinning before performing the decorated method - and re-hooks it up after the
fact. Basically decorating anything with this function will allow you do perform operations
that would otherwise cause maya to complain about skin clusters being attached
'''
def new( *a, **kw ):
#for all skin clusters iterate through all their joints and detach them
#so we can freeze transforms - make sure to store initial state so we can
#restore connections afterward
skinClustersConnections = []
skinClusters = ls( typ='skinCluster' ) or []
for c in skinClusters:
cons = listConnections( c, destination=False, plugs=True, connections=True )
if cons is None:
print 'WARNING - no connections found on the skinCluster %s' % c
continue
conIter = iter( cons )
for tgtConnection in conIter:
srcConnection = conIter.next() #cons is a list of what should be tuples, but maya just returns a flat list - basically every first item is the destination plug, and every second is the source plug
#if the connection is originating from a joint delete the connection - otherwise leave it alone - we only want to disconnect joints from the skin cluster
node = srcConnection.split( '.' )[0]
if nodeType( node ) == 'joint':
disconnectAttr( srcConnection, tgtConnection )
skinClustersConnections.append( (srcConnection, tgtConnection) )
try:
f( *a, **kw )
#ALWAYS restore connections...
finally:
#re-connect all joints to skinClusters, and reset them
for srcConnection, tgtConnection in skinClustersConnections:
connectAttr( srcConnection, tgtConnection, f=True )
if skinClustersConnections:
for skinCluster in skinClusters:
resetSkinCluster( skinCluster )
new.__name__ = f.__name__
new.__doc__ = f.__doc__
return new
def d_disableDrivingRelationships( f ):
'''
tries to unhook all driver/driven relationships first, and re-hook them up afterwards
NOTE: needs to wrap a SkeletonPart method
'''
def new( self, *a, **kw ):
#store any driving or driven part, so when we're done we can restore the relationships
driver = self.getDriver()
drivenParts = self.getDriven()
#break driving relationships
self.breakDriver()
for part in drivenParts:
part.breakDriver()
try:
f( self, *a, **kw )
#restore driver/driven relationships...
finally:
#restore any up/downstream relationships if any...
if driver:
driver.driveOtherPart( self )
for part in drivenParts:
try:
self.driveOtherPart( part )
except AssertionError: continue #the parts may have changed size since the initial connection, so if they differ in size just ignore the assertion...
new.__name__ = f.__name__
new.__doc__ = f.__doc__
return new
def d_performInSkeletonPartScene( f ):
def new( self, *a, **kw ):
assert isinstance( self, SkeletonPart )
#if the part isn't referenced - nothing to do! execute the function as usual
if not self.isReferenced():
return f( self, *a, **kw )
partContainerFilepath = filesystem.Path( referenceQuery( self.getContainer(), filename=True ) )
curScene = filesystem.Path( file( q=True, sn=True ) )
if not curScene.exists():
raise TypeError( "This scene isn't saved! Please save this scene somewhere before executing the decorated method!" )
initialContainer = ReferencedNode( self.getContainer() )
self.setContainer( initialContainer.getUnreferencedNode() )
if not curScene.getWritable():
curScene.edit()
file( save=True, f=True )
file( partContainerFilepath, open=True, f=True )
try:
return f( self, *a, **kw )
finally:
self.setContainer( initialContainer.getNode() )
if not partContainerFilepath.getWritable():
partContainerFilepath.edit()
file( save=True, f=True )
file( curScene, open=True, f=True )
new.__name__ = f.__name__
new.__doc__ = f.__doc__
return new
class SkeletonPart(typeFactories.trackableClassFactory()):
__version__ = 0
#parity is "sided-ness" of the part. Ie if the part can exist on the left OR right side of the skeleton, the part has parity. the spine
#is an example of a part that has no parity, as is the head
HAS_PARITY = True
PART_SCALE = TYPICAL_HEIGHT
AUTO_NAME = True
AVAILABLE_IN_UI = True #determines whether this part should appear in the UI or not...
#some variables generally used by the auto volume creation methods
AUTO_VOLUME_SIDES = 8 #number of cylinder sides
#this list should be overridden for sub classes require named end placers such as feet
PLACER_NAMES = []
RigTypes = ()
def __new__( cls, partContainer ):
if cls is SkeletonPart:
clsName = getAttr( '%s._skeletonPrimitive.typeName' % partContainer )
cls = cls.GetNamedSubclass( clsName )
if cls is None:
raise TypeError( "Cannot determine the part class for the given part container!" )
return object.__new__( cls, partContainer )
def __init__( self, partContainer ):
if partContainer is not None:
assert isSkeletonPartContainer( partContainer ), "Must pass a valid skeleton part container! (received %s - a %s)" % (partContainer, nodeType( partContainer ))
self._container = partContainer
self._items = None
def __unicode__( self ):
return u"%s( %r )" % (self.__class__.__name__, self._container)
__str__ = __unicode__
def __repr__( self ):
return repr( unicode( self ) )
def __hash__( self ):
return hash( self._container )
def __eq__( self, other ):
return self._container == other.getContainer()
def __neq__( self, other ):
return not self == other
def __getitem__( self, idx ):
return self.getItems().__getitem__( idx )
def __getattr__( self, attr ):
if attr in self.__dict__:
return self.__dict__[ attr ]
if attr not in self.PLACER_NAMES:
raise AttributeError( "No such attribute %s" % attr )
idx = list( self.PLACER_NAMES ).index( attr )
cons = listConnections( '%s._skeletonPrimitive.placers[%d]' % (self.base, n), d=False )
if cons:
return cons[ 0 ]
return None
def __len__( self ):
return len( self.getItems() )
def __iter__( self ):
return iter( self.getItems() )
def getContainer( self ):
return self._container
def setContainer( self, container ):
self._container = container
self._items = None
def getItems( self ):
if self._items is not None:
return self._items[:]
self._items = items = []
idxs = getAttr( '%s._skeletonPrimitive.items' % self._container, multiIndices=True ) or []
for idx in idxs:
cons = listConnections( '%s._skeletonPrimitive.items[%d]' % (self._container, idx), d=False )
if cons:
assert len( cons ) == 1, "More than one joint was found!!!"
items.append( cons[ 0 ] )
#items = castToMObjects( items )
return items[:] #return a copy...
items = property( getItems )
@property
def version( self ):
try:
return getAttr( '%s._skeletonPrimitive.version' % self._container )
except: return None
def isDisabled( self ):
'''
returns whether the part has been disabled for rigging or not
'''
rigKwargs = self.getRigKwargs()
return 'disable' in rigKwargs
def getPlacers( self ):
placerAttrpath = '%s._skeletonPrimitive.placers' % self._container
if not objExists( placerAttrpath ):
return []
placers = []
placerIdxs = getAttr( placerAttrpath, multiIndices=True )
if placerIdxs:
for idx in placerIdxs:
cons = listConnections( '%s[%d]' % (placerAttrpath, idx), d=False )
if cons:
placers.append( cons[ 0 ] )
return placers
def verifyPart( self ):
'''
this is merely a "hook" that can be used to fix anything up should the way
skeleton parts are defined change
'''
#make sure all items have the appropriate attributes on them
baseItem = self[ 0 ]
for n, item in enumerate( self ):
delete( '%s.inverseScale' % item, icn=True ) #remove the inverse scale relationship...
setAttr( '%s.segmentScaleCompensate' % item, False )
if not objExists( '%s._skeletonPartName' % item ):
addAttr( item, ln='_skeletonPartName', dt='string' )
if not objExists( '%s._skeletonPartArgs' % item ):
addAttr( item, ln='_skeletonPartArgs', dt='string' )
if n:
if not isConnected( '%s._skeletonPartName' % baseItem, '%s._skeletonPartName' % item ):
connectAttr( '%s._skeletonPartName' % baseItem, '%s._skeletonPartName' % item, f=True )
if not isConnected( '%s._skeletonPartArgs' % baseItem, '%s._skeletonPartArgs' % item ):
connectAttr( '%s._skeletonPartArgs' % baseItem, '%s._skeletonPartArgs' % item, f=True )
def convert( self, buildKwargs ):
'''
called when joints built outside of skeleton builder are converted to a skeleton builder part
'''
if not buildKwargs:
for argName, value in self.GetDefaultBuildKwargList():
buildKwargs[ argName ] = value
if 'idx' not in buildKwargs:
idx = self.GetUniqueIdx()
buildKwargs[ 'idx' ] = idx
if 'parent' in buildKwargs:
buildKwargs.pop( 'parent' )
self.setBuildKwargs( buildKwargs )
#lock scale
attrState( self.items, ['s'], lock=True, keyable=False, show=True )
#lock rotate axis
attrState( self.items, ['rotateAxis'], lock=True, keyable=False, show=False )
#build placers...
self.buildPlacers()
def hasParity( self ):
return self.HAS_PARITY
def isReferenced( self ):
return referenceQuery( self._container, inr=True )
@classmethod
def ParityMultiplier( cls, idx ):
return Parity( idx ).asMultiplier()
@classmethod
def GetPartName( cls ):
'''
can be used to get a "nice" name for the part class
'''
return camelCaseToNice( cls.__name__ )
def getIdx( self ):
'''
returns the index of the part - all parts have a unique index associated
with them
'''
return self.getBuildKwargs()[ 'idx' ]
def getBuildScale( self ):
return self.getBuildKwargs().get( 'partScale', self.PART_SCALE )
def getParity( self ):
return Parity( self.getIdx() )
def getParityColour( self ):
parity = self.getParity()
if parity == Parity.LEFT:
return Colour( 'green' )
if parity == Parity.RIGHT:
return Colour( 'red' )
if parity == Parity.NONE:
return Colour( 'darkblue' )
return Colour( 'black' )
getParityColor = getParityColour
def getParityMultiplier( self ):
return self.getParity().asMultiplier()
def getOppositePart( self ):
'''
Finds the opposite part - if any - in the scene to this part. If no opposite part is found None is returned.
The opposite part is defined as the part that has opposite parity - the part with the closest index is
returned if there are multiple parts with opposite parity in the scene.
If this part has no parity None is returned.
'''
#is this a parity part? if not then there is no such thing as an opposite part...
if not self.hasParity():
return None
#get some data about this part
thisIdx = self.getIdx()
thisParity = self.getParity()
#is this a left or right parity part?
isLeft = thisIdx == Parity.LEFT
possibleMatches = []
for part in self.IterAllParts( True ):
parity = part.getParity()
if parity.isOpposite( thisParity ):
idx = part.getIdx()
#if "self" is a left part then its exact opposite will be self.getIdx() + 1, otherwise if "self" is a right
#sided part then its exact opposite will be self.getIdx() - 1. So figure out the "index delta" and use it
#as a sort metric to find the most appropriate match for the cases where there are multiple, non-ideal matches
idxDelta = 0
if isLeft:
idxDelta = idx - thisIdx
else:
idxDelta = thisIdx - idx
if idxDelta == 1:
return part
possibleMatches.append( (idxDelta, part) )
possibleMatches.sort()
if possibleMatches:
return possibleMatches[0][1]
return None
@property
def base( self ):
return self[ 0 ]
@property
def bases( self ):
'''
returns all the bases for this part - bases are joints with parents who don't belong to this part
'''
allItems = set( self )
bases = []
for item in self:
itemParent = getNodeParent( item )
if itemParent not in allItems:
bases.append( item )
return bases
@property
def end( self ):
return self[ -1 ]
@property
def ends( self ):
'''
returns all the ends for the part - ends are joints that either have no children, or have children
that don't belong to this part
'''
allItems = set( self )
ends = []
for item in self:
itemChildren = listRelatives( item, pa=True )
#so if the item has children, see if any of them are in allItems - if not, its an end
if itemChildren:
childrenInAllItems = allItems.intersection( set( itemChildren ) )
if not childrenInAllItems:
ends.append( item )
#if it has no children, its an end
else:
ends.append( item )
return ends
@property
def chains( self ):
'''
returns a list of hierarchy "chains" in the current part - parts that have
more than one base are comprised of "chains": ie hierarchies that don't have
a parent as a member of this part
For a hand part for example, this method will return a list of finger
hierarchies
NOTE: the chains are ordered hierarchically
'''
bases = set( self.bases )
chains = []
for end in self.ends:
currentChain = [ end ]
p = getNodeParent( end )
while p:
currentChain.append( p )
if p in bases:
break
p = getNodeParent( p )
currentChain.reverse()
chains.append( currentChain )
return chains
@property
def endPlacer( self ):
try:
return self.getPlacers()[ 0 ]
except IndexError:
return None
@classmethod
def GetIdxStr( cls, idx ):
'''
returns an "index string". For parts with parity this index string increments
with pairs (ie a left and a right) while non-parity parts always increment
'''
#/2 because parts are created in pairs so arm 2 and 3 are prefixed with "Arm1", and the first arm is simply "Arm"
if cls.HAS_PARITY:
return str( idx / 2 ) if idx > 1 else ''
return str( idx ) if idx else ''
def getBuildKwargs( self ):
'''
returns the kwarg dict that was used to create this particular part
'''
buildFunc = self.GetBuildFunction()
#get the default build kwargs for the part
argNames, vArgs, vKwargs, defaults = inspect.getargspec( buildFunc )
if defaults is None:
defaults = []
argNames = argNames[ 1: ] #strip the first arg - which is the class arg (usually cls)
kw = {}
for argName, default in zip( argNames, defaults ):
kw[ argName ] = default
#now update the default kwargs with the actual kwargs
argStr = getAttr( '%s._skeletonPrimitive.buildKwargs' % self._container )
kw.update( eval( argStr ) )
return kw
def setBuildKwargs( self, kwargs ):
'''
returns the kwarg dict that was used to create this particular part
'''
setAttr( '%s._skeletonPrimitive.buildKwargs' % self._container, str( kwargs ), type='string' )
def getRigKwargs( self ):
'''
returns the kwarg dict that should be used to create the rig for this part
'''
try:
argStr = getAttr( '%s._skeletonPrimitive.rigKwargs' % self._container )
except:
return {}
if argStr is None:
return {}
kw = eval( argStr )
return kw
def setRigKwargs( self, kwargs ):
setAttr( '%s._skeletonPrimitive.rigKwargs' % self._container, str( kwargs ), type='string' )
def updateRigKwargs( self, **kw ):
currentKwargs = self.getRigKwargs()
currentKwargs.update( kw )
self.setRigKwargs( currentKwargs )