/
general.py
6338 lines (5367 loc) · 232 KB
/
general.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
"""
Contains general node and attribute functions, as well as the main `PyNode` base class.
For the rest of the class hierarchy, including `DependNode <pymel.core.nodetypes.DependNode>`, `Transform <pymel.core.nodetypes.Transform>`,
and `Attribute <pymel.core.nodetypes.Attribute>`, see :mod:`pymel.core.nodetypes`.
"""
import sys
import os
import re
import itertools
import inspect
import collections
import pymel.internal.pmcmds as cmds
import pymel.util as _util
import pymel.internal.factories as _factories
import pymel.internal.pwarnings as _warnings
import pymel.internal.startup as _startup
import pymel.api as _api
import pymel.versions as _versions
import pymel.core.system as system
import datatypes
from maya.cmds import about as _about
from pymel.internal import getLogger as _getLogger
_logger = _getLogger(__name__)
# TODO: factories.functionFactory should automatically handle conversion of output to PyNodes...
# ...so we shouldn't always have to do it here as well?
# Get config settings for checking if an attribute is referenced before changing the lock state
CHECK_ATTR_BEFORE_LOCK = _startup.pymel_options.get('check_attr_before_lock', False)
def _getPymelTypeFromObject(obj, name):
if obj.hasFn(_api.MFn.kDependencyNode):
fnDepend = _api.MFnDependencyNode(obj)
mayaType = fnDepend.typeName()
import nodetypes
# make sure that if we have a dag node, we return at least DagNode
# instead of DependNode - otherwise, we will end up with
# __apiobjects__ = {'MDagPath':MDagPath(...)}, but a pymel type of
# DependNode... and DependNode.__apihandle__() always assumes that
# MObjectHandle is always in __apiobjects__
pymelTypeName = nodetypes.mayaTypeNameToPymelTypeName.get(
mayaType,
'DagNode' if obj.hasFn(_api.MFn.kDagNode) else 'DependNode')
pymelType = getattr(nodetypes, pymelTypeName)
pymelType = _factories.virtualClasses.getVirtualClass(pymelType, obj, name, fnDepend)
elif obj.hasFn(_api.MFn.kComponent):
compTypes = _factories.apiEnumsToPyComponents.get(obj.apiType(), None)
if compTypes is None:
_logger.raiseLog(_logger.DEBUG, 'Got an instance of a component which could not be mapped to a pymel class: %s' % obj.apiTypeStr())
compTypes = [Component]
if len(compTypes) != 1:
_logger.raiseLog(_logger.WARNING, 'Got an instance of a component with more than one possible PyNode type: %s' % obj.apiTypeStr())
pymelType = compTypes[0]
elif obj.hasFn(_api.MFn.kAttribute):
pymelType = AttributeDefaults
else:
raise RuntimeError('Could not determine pymel type for object of type %s' % obj.apiTypeStr())
return pymelType
def _getPymelType(arg, name):
""" Get the correct Pymel Type for an object that can be a MObject, PyNode or name of an existing Maya object,
if no correct type is found returns DependNode by default.
If the name of an existing object is passed, the name and MObject will be returned
If a valid MObject is passed, the name will be returned as None
If a PyNode instance is passed, its name and MObject will be returned
"""
obj = None
results = {}
isAttribute = False
#--------------------------
# API object testing
#--------------------------
if isinstance(arg, _api.MObject):
results['MObjectHandle'] = _api.MObjectHandle(arg)
obj = arg
elif isinstance(arg, _api.MObjectHandle):
results['MObjectHandle'] = arg
obj = arg.object()
elif isinstance(arg, _api.MDagPath):
results['MDagPath'] = arg
obj = arg.node()
elif isinstance(arg, _api.MPlug):
isAttribute = True
obj = arg
results['MPlug'] = obj
if _api.isValidMPlug(arg):
pymelType = Attribute
else:
raise MayaAttributeError, "Unable to determine Pymel type: the passed MPlug is not valid"
# #---------------------------------
# # No Api Object : Virtual PyNode
# #---------------------------------
# elif objName :
# # non existing node
# pymelType = DependNode
# if '.' in objName :
# # TODO : some better checking / parsing
# pymelType = Attribute
else:
raise ValueError("Unable to determine Pymel type for %r" % (arg,))
if not isAttribute:
pymelType = _getPymelTypeFromObject(obj, name)
return pymelType, results
#-----------------------------------------------
# Enhanced Commands
#-----------------------------------------------
# TODO: possible bugfix for 'parent'?
# Docs state 'If there is only a single object specified then the selected objects are parented to that object. '
# ...but actual behavior is to parent the named object (and any other selected objects) to the last selected object
#-----------------------
# Object Manipulation
#-----------------------
def select(*args, **kwargs):
"""
Modifications:
- passing an empty list no longer causes an error.
instead, the selection is cleared if the selection mod is replace (the default);
otherwise, it does nothing
"""
try:
cmds.select(*args, **kwargs)
except TypeError, msg:
if args == ([],):
for modeFlag in ('add', 'af', 'addFirst',
'd', 'deselect',
'tgl', 'toggle'):
if kwargs.get(modeFlag, False):
return
# The mode is replace, clear the selection
cmds.select(cl=True)
else:
raise TypeError, msg
#select.__doc__ = mel.help('select') + select.__doc__
# TODO: make it handle multiple objects, like original command
def move(*args, **kwargs):
"""
Modifications:
- allows any iterable object to be passed as first argument::
move("pSphere1", [0,1,2])
NOTE: this command also reorders the argument order to be more intuitive, with the object first
"""
obj = None
if args and isinstance(args[0], (basestring, PyNode)):
obj = args[0]
args = args[1:]
if len(args) == 1 and _util.isIterable(args[0]):
args = tuple(args[0])
if obj is not None:
args = args + (obj,)
return cmds.move(*args, **kwargs)
def scale(obj, *args, **kwargs):
"""
Modifications:
- allows any iterable object to be passed as first argument::
scale("pSphere1", [0,1,2])
NOTE: this command also reorders the argument order to be more intuitive, with the object first
"""
if len(args) == 1 and _util.isIterable(args[0]):
args = tuple(args[0])
args = args + (obj,)
return cmds.scale(*args, **kwargs)
def rotate(obj, *args, **kwargs):
"""
Modifications:
- allows any iterable object to be passed as first argument::
rotate("pSphere1", [0,1,2])
NOTE: this command also reorders the argument order to be more intuitive, with the object first
"""
if len(args) == 1 and _util.isIterable(args[0]):
args = tuple(args[0])
args = args + (obj,)
return cmds.rotate(*args, **kwargs)
#-----------------------
# Attributes
#-----------------------
def connectAttr(source, destination, **kwargs):
"""
Maya Bug Fix:
- even with the 'force' flag enabled, the command would raise an error if the connection already existed.
"""
if kwargs.get('force', False) or kwargs.get('f', False):
try:
cmds.connectAttr(source, destination, **kwargs)
except RuntimeError, e:
if str(e) != 'Maya command error':
# we only want to pass on a certain connection error. all others we re-raise
raise e
else:
cmds.connectAttr(source, destination, **kwargs)
def disconnectAttr(source, destination=None, inputs=None, outputs=None,
**kwargs):
"""
Modifications:
- If no destination is passed, then all inputs will be disconnected if inputs
is True, and all outputs will be disconnected if outputs is True; if
neither are given (or both are None), both all inputs and all outputs
will be disconnected
"""
if destination:
if inputs:
raise ValueError('inputs/outputs flags may not be used in combination with a destination')
cmds.disconnectAttr(source, destination, **kwargs)
else:
disconnectionDirs = []
if inputs is None and outputs is None:
inputs = True
outputs = True
if inputs:
disconnectionDirs.append('inputs')
if outputs:
disconnectionDirs.append('outputs')
for disconnectDir in disconnectionDirs:
disconnectingInputs = (disconnectDir == 'inputs')
connections = cmds.listConnections(source,
source=disconnectingInputs,
destination=(not disconnectingInputs),
connections=True,
plugs=True)
# stupid maya.cmds returns None instead of []...
if connections is None:
continue
# if disconnectingInputs, results from listConnections will be returned in dest, src order -
# reverse the list to flip this to src, dest
if disconnectingInputs:
connections.reverse()
for src, dest in _util.pairIter(connections):
cmds.disconnectAttr(src, dest, **kwargs)
def getAttr(attr, default=None, **kwargs):
"""
Maya Bug Fix:
- maya pointlessly returned vector results as a tuple wrapped in a list ( ex. '[(1,2,3)]' ). This command unpacks the vector for you.
Modifications:
- casts double3 datatypes to `Vector`
- casts matrix datatypes to `Matrix`
- casts vectorArrays from a flat array of floats to an array of Vectors
- when getting a multi-attr, maya would raise an error, but pymel will return a list of values for the multi-attr
- added a default argument. if the attribute does not exist and this argument is not None, this default value will be returned
- added support for getting message attributes
"""
def listToMat(l):
return datatypes.Matrix(
[[l[0], l[1], l[2], l[3]],
[l[4], l[5], l[6], l[7]],
[l[8], l[9], l[10], l[11]],
[l[12], l[13], l[14], l[15]]])
def listToVec(l):
vecRes = []
for i in range(0, len(res), 3):
vecRes.append(datatypes.Vector(res[i:i + 3]))
return vecRes
# stringify fix
if isinstance(attr, Attribute):
attr = attr.name(placeHolderIndices=False)
else:
attr = unicode(attr)
try:
res = cmds.getAttr(attr, **kwargs)
if isinstance(res, list) and len(res):
if isinstance(res[0], tuple):
typ = cmds.getAttr(attr, type=1)
if typ == 'pointArray':
return [datatypes.Point(x) for x in res]
elif typ == 'vectorArray':
return [datatypes.Vector(x) for x in res]
res = res[0]
if typ == 'double3':
return datatypes.Vector(list(res))
# elif cmds.getAttr( attr, type=1) == 'matrix':
# return listToMat(res)
else:
try:
return {
'matrix': listToMat,
'vectorArray': listToVec
}[cmds.getAttr(attr, type=1)](res)
except KeyError:
pass
return res
# perhaps it error'd because it's a mixed compound, or a multi attribute
except RuntimeError, e:
try:
pyattr = Attribute(attr)
# mixed compound takes precedence, because by default, compound attributes are returned by getAttr, but
# mixed compounds cannot be expressed in a mel array.
if pyattr.isCompound():
return [child.get() for child in pyattr.getChildren()]
elif pyattr.isMulti():
if pyattr.type() == 'message':
return pyattr.listConnections()
return [pyattr[i].get() for i in range(pyattr.numElements())]
# re-raise error
elif pyattr.type() == 'message':
connects = pyattr.listConnections()
if connects:
return connects[0]
else:
return None
raise
except AttributeError:
if default is not None:
return default
# raise original RuntimeError
raise e
class AmbiguityWarning(Warning):
pass
# getting and setting
def setAttr(attr, *args, **kwargs):
"""
Maya Bug Fix:
- setAttr did not work with type matrix.
Modifications:
- No need to set type, this will automatically be determined
- Adds support for passing a list or tuple as the second argument for datatypes such as double3.
- When setting stringArray datatype, you no longer need to prefix the list with the number of elements - just pass a list or tuple as with other arrays
- Added 'force' kwarg, which causes the attribute to be added if it does not exist.
- if no type flag is passed, the attribute type is based on type of value being set (if you want a float, be sure to format it as a float, e.g. 3.0 not 3)
- currently does not support compound attributes
- currently supported python-to-maya mappings:
============ ===========
python type maya type
============ ===========
float double
------------ -----------
int long
------------ -----------
str string
------------ -----------
bool bool
------------ -----------
Vector double3
------------ -----------
Matrix matrix
------------ -----------
[str] stringArray
============ ===========
>>> addAttr( 'persp', longName= 'testDoubleArray', dataType='doubleArray')
>>> setAttr( 'persp.testDoubleArray', [0,1,2])
>>> setAttr( 'defaultRenderGlobals.preMel', 'sfff')
- Added ability to set enum attributes using the string values; this may be
done either by setting the 'asString' kwarg to True, or simply supplying
a string value for an enum attribute.
"""
datatype = kwargs.get('type', kwargs.get('typ', None))
# if there is only one argument we do our special pymel tricks
if len(args) == 1:
arg = args[0]
# force flag
force = kwargs.pop('force', kwargs.pop('f', False))
# asString flag
asString = kwargs.pop('asString', None)
# vector, matrix, and arrays
if _util.isIterable(arg):
if datatype is None:
# if using force flag and the attribute does not exist
# we can infer the type from the passed value
#attr = Attribute(attr)
if force and not cmds.objExists(attr): # attr.exists():
import pymel.util.nameparse as nameparse
attrName = nameparse.parse(attr)
assert attrName.isAttributeName(), "passed object is not an attribute"
try:
if isinstance(arg[0], (basestring, _util.ProxyUnicode)):
datatype = 'stringArray'
elif isinstance(arg[0], (list, datatypes.Vector)):
datatype = 'vectorArray'
elif isinstance(arg[0], (list, datatypes.Point)):
datatype = 'pointArray'
elif isinstance(arg, datatypes.Vector):
datatype = 'double3'
elif isinstance(arg, datatypes.Matrix):
datatype = 'matrix'
elif isinstance(arg[0], int):
datatype = 'Int32Array'
elif isinstance(arg[0], float):
datatype = 'doubleArray'
if len(arg) == 3:
_logger.warn(
"The supplied value will be interperted as a 'doubleArray' and not as a 'double3' (vector). "
"Supply an explicit 'datatype' argument to avoid this warning.")
else:
raise ValueError, "pymel.core.setAttr: %s is not a supported type for use with the force flag" % type(arg[0])
#_logger.debug("adding %r as %r", attr, datatype)
addAttr(attrName.nodePath, ln=attrName.attribute, dt=datatype)
# empty array is being passed
# if the attribute exists, this is ok
except IndexError:
raise ValueError, "pymel.core.setAttr: when setting 'force' keyword to create a new array attribute, you must provide an array with at least one element"
except TypeError:
raise ValueError, "pymel.core.setAttr: %s is not a supported type" % type(args)
else:
if isinstance(arg, datatypes.Vector):
datatype = 'double3'
elif isinstance(arg, datatypes.Matrix):
datatype = 'matrix'
else:
datatype = getAttr(attr, type=1)
if not datatype:
datatype = addAttr(attr, q=1, dataType=1) # [0] # this is returned as a single element list
if datatype:
kwargs['type'] = datatype
try:
arg = arg.__melobject__()
except AttributeError:
pass
if datatype == 'stringArray':
# string arrays:
# first arg must be the length of the array being set
# ex:
# setAttr('loc.strArray',["first", "second", "third"] )
# becomes:
# cmds.setAttr('loc.strArray',3,"first", "second", "third",type='stringArray')
args = tuple([len(arg)] + arg)
elif datatype in ['vectorArray', 'pointArray']:
if _versions.current() < _versions.v2011:
# vector arrays:
# first arg must be the length of the array being set
# empty values are placed between vectors
# ex:
# setAttr('loc.vecArray',[1,2,3],[4,5,6],[7,8,9] )
# becomes:
# cmds.setAttr('loc.vecArray',3,[1,2,3],"",[4,5,6],"",[7,8,9],type='vectorArray')
arg = list(arg)
size = len(arg)
try:
tmpArgs = [arg.pop(0)]
for filler, real in zip([""] * (size - 1), arg):
tmpArgs.append(filler)
tmpArgs.append(real)
except IndexError:
tmpArgs = []
args = tuple([size] + tmpArgs)
else:
# vector arrays:
# first arg must be the length of the array being set
# empty values are placed between vectors
# ex:
# setAttr('loc.vecArray',[1,2,3],[4,5,6],[7,8,9] )
# becomes:
# cmds.setAttr('loc.vecArray',3,[1,2,3],[4,5,6],[7,8,9],type='vectorArray')
arg = list(arg)
size = len(arg)
args = tuple([size] + arg)
# print args
elif datatype in ['Int32Array', 'doubleArray']:
# int32 and double arrays:
# actually fairly sane
# ex:
# setAttr('loc.doubleArray',[1,2,3] )
# becomes:
# cmds.setAttr('loc.doubleArray',[1,2,3],type='doubleArray')
args = (tuple(arg),)
else:
# others: short2, short3, long2, long3, float2, etc...
# args must be expanded
# ex:
# setAttr('loc.foo',[1,2,3] )
# becomes:
# cmds.setAttr('loc.foo',1,2,3 )
args = tuple(arg)
# non-iterable types
else:
if datatype is None:
#attr = Attribute(attr)
if force and not cmds.objExists(attr): # attr.exists():
import pymel.util.nameparse as nameparse
attrName = nameparse.parse(attr)
assert attrName.isAttributeName(), "passed object is not an attribute"
if isinstance(arg, basestring):
addAttr(attrName.nodePath, ln=attrName.attribute, dt='string')
kwargs['type'] = 'string'
elif isinstance(arg, int):
addAttr(attrName.nodePath, ln=attrName.attribute, at='long')
elif isinstance(arg, float):
addAttr(attrName.nodePath, ln=attrName.attribute, at='double')
elif isinstance(arg, bool):
addAttr(attrName.nodePath, ln=attrName.attribute, at='bool')
else:
raise TypeError, "%s.setAttr: %s is not a supported type for use with the force flag" % (__name__, type(arg))
elif isinstance(arg, (basestring, _util.ProxyUnicode)):
if asString is None:
if isinstance(attr, Attribute):
attrType = attr.type()
else:
attrType = cmds.getAttr(attr, type=1)
asString = (attrType == 'enum')
if asString:
val = getEnums(attr).get(arg)
if val is None:
raise MayaAttributeEnumError(attr, arg)
arg = val
args = (val,)
else:
kwargs['type'] = 'string'
# stringify fix
attr = unicode(attr)
try:
# print args, kwargs
cmds.setAttr(attr, *args, **kwargs)
except TypeError, msg:
val = kwargs.pop('type', kwargs.pop('typ', False))
typ = addAttr(attr, q=1, at=1)
if val == 'string' and typ == 'enum':
enums = addAttr(attr, q=1, en=1).split(":")
index = enums.index(args[0])
args = (index, )
cmds.setAttr(attr, *args, **kwargs)
else:
raise TypeError, msg
except RuntimeError, msg:
# normally this is handled in pmcmds, but setAttr error is different for some reason
# can't use 'startswith' because of Autodesk test strings wrapped in commas
if 'No object matches name: ' in str(msg):
raise _objectError(attr)
else:
# re-raise
raise
def addAttr(*args, **kwargs):
"""
Modifications:
- allow python types to be passed to set -at type
str string
float double
int long
bool bool
Vector double3
- when querying dataType, the dataType is no longer returned as a list
- when editing hasMinValue, hasMaxValue, hasSoftMinValue, or hasSoftMaxValue the passed boolean value was ignored
and the command instead behaved as a toggle. The behavior is now more intuitive::
>>> addAttr('persp', ln='test', at='double', k=1)
>>> addAttr('persp.test', query=1, hasMaxValue=True)
False
>>> addAttr('persp.test', edit=1, hasMaxValue=False)
>>> addAttr('persp.test', query=1, hasMaxValue=True)
False
>>> addAttr('persp.test', edit=1, hasMaxValue=True)
>>> addAttr('persp.test', query=1, hasMaxValue=True)
True
- allow passing a list or dict instead of a string for enumName
- allow user to pass in type and determine whether it is a dataType or
attributeType. Types that may be both, such as float2, float3, double2,
double3, long2, long3, short2, and short3 are all treated as
attributeTypes. In addition, as a convenience, since these attributeTypes
are actually treated as compound attributes, the child attributes are
automatically created, with X/Y/Z appended, unless usedAsColor is set, in
which case R/G/B is added. Alternatively, the suffices can explicitly
specified with childSuffixes:
>>> addAttr('persp', ln='autoDouble', type='double', k=1)
>>> addAttr('persp.autoDouble', query=1, attributeType=1)
u'double'
>>> addAttr('persp.autoDouble', query=1, dataType=1)
u'TdataNumeric'
>>> addAttr('persp', ln='autoMesh', type='mesh', k=1)
>>> addAttr('persp.autoMesh', query=1, attributeType=1)
u'typed'
>>> addAttr('persp.autoMesh', query=1, dataType=1)
u'mesh'
>>> addAttr('persp', ln='autoDouble3Vec', type='double3', k=1)
>>> [x.attrName() for x in PyNode('persp').listAttr() if 'autoDouble3' in x.name()]
[u'autoDouble3Vec', u'autoDouble3VecX', u'autoDouble3VecY', u'autoDouble3VecZ']
>>> addAttr('persp', ln='autoFloat3Col', type='float3', usedAsColor=1)
>>> [x.attrName() for x in PyNode('persp').listAttr() if 'autoFloat3' in x.name()]
[u'autoFloat3Col', u'autoFloat3ColR', u'autoFloat3ColG', u'autoFloat3ColB']
>>> addAttr('persp', ln='autoLong2', type='long2', childSuffixes=['_first', '_second'])
>>> [x.attrName() for x in PyNode('persp').listAttr() if 'autoLong2' in x.name()]
[u'autoLong2', u'autoLong2_first', u'autoLong2_second']
"""
attributeTypes = [ 'bool', 'long', 'short', 'byte', 'char', 'enum',
'float', 'double', 'doubleAngle', 'doubleLinear',
'compound', 'message', 'time', 'fltMatrix', 'reflectance',
'spectrum', 'float2', 'float3', 'double2', 'double3', 'long2',
'long3', 'short2', 'short3', datatypes.Vector ]
dataTypes = [ 'string', 'stringArray', 'matrix', 'reflectanceRGB',
'spectrumRGB', 'doubleArray', 'Int32Array', 'vectorArray',
'nurbsCurve', 'nurbsSurface', 'mesh', 'lattice', 'pointArray' ]
type = kwargs.pop('type', kwargs.pop('typ', None ))
childSuffixes = kwargs.pop('childSuffixes', None)
if type is not None:
if type in attributeTypes:
kwargs['at'] = type
elif type in dataTypes:
kwargs['dt'] = type
else:
raise TypeError, "type not supported"
at = kwargs.pop('attributeType', kwargs.pop('at', None))
if at is not None:
try:
at = {
float: 'double',
int: 'long',
bool: 'bool',
datatypes.Vector: 'double3',
str: 'string',
unicode: 'string'
}[at]
except KeyError:
pass
kwargs['at'] = at
if kwargs.get('e', kwargs.get('edit', False)):
for editArg, value in kwargs.iteritems():
if editArg not in ('e', 'edit') and value:
break
if editArg in ('hasMinValue', 'hnv', 'hasMaxValue', 'hxv', 'hasSoftMinValue', 'hsn', 'hasSoftMaxValue', 'hsx'):
# bugfix: hasM*Value works as a toggle, regardless of whether you specify True or False
if bool(value) != bool(cmds.addAttr(*args, **{'query': True, editArg: True})):
return cmds.addAttr(*args, **kwargs)
else:
# otherwise, don't do anything, bc the value is already correct
return
# translate dict or list for enumName
enums = kwargs.pop('en', kwargs.pop('enumName', None))
if enums is not None:
kwargs['enumName'] = _toEnumStr(enums)
# MObject stringify Fix
#args = map(unicode, args)
res = cmds.addAttr(*args, **kwargs)
if kwargs.get('q', kwargs.get('query', False)):
# When addAttr is queried, and has multiple other query flags - ie,
# addAttr('joint1.sweetpea', q=1, parent=1, dataType=1)
# ... it seems to ignore every kwarg but the 'first'
for queriedArg, value in kwargs.iteritems():
if queriedArg not in ('q', 'query') and value:
break
if queriedArg in ('dt', 'dataType'):
# If the attr is not a dynamic attribute, maya.cmds prints:
# Error: '...' is not a dynamic attribute of node '...'.
# ...but does NOT raise an exception
# Because it will be more consistent with maya.cmds, and because
# attributeType already behaves like this, we will do the same -
# allow maya.cmds to print it's error message, and return None, but
# not raise an exception
if res is not None:
res = res[0]
elif queriedArg in ('p', 'parent'):
node = None
if args:
node = PyNode(args[0])
else:
node = ls(sl=1)[0]
if isinstance(node, Attribute):
node = node.node()
res = node.attr(res)
elif not kwargs.get('e', kwargs.get('edit', False)):
# if we were creating an attribute, and used "type", check if we
# made a compound type...
if type is not None and at:
# string parse the attributeType, because the type may be an
# actual python type...
baseType = at[:-1]
num = at[-1]
if (baseType in ('float', 'double', 'short', 'long')
and num in ('2', '3')):
num = int(num)
if childSuffixes is None:
if kwargs.get('usedAsColor', kwargs.get('uac')):
childSuffixes = 'RGB'
else:
childSuffixes = 'XYZ'
baseLongName = kwargs.get('longName', kwargs.get('ln'))
baseShortName = kwargs.get('shortName', kwargs.get('sn'))
childKwargs = dict(kwargs)
for kwarg in (
'longName', 'ln',
'shortName', 'sn',
'attributeType', 'at',
'dataType', 'dt',
'multi', 'm',
'indexMatters', 'im',
'parent', 'p',
'numberOfChildren', 'nc',
'usedAsColor', 'uac',
):
childKwargs.pop(kwarg, None)
childKwargs['attributeType'] = baseType
childKwargs['parent'] = baseLongName
for i in xrange(num):
suffix = childSuffixes[i]
childKwargs['longName'] = baseLongName + suffix
if baseShortName:
childKwargs['shortName'] = baseShortName + suffix
cmds.addAttr(*args, **childKwargs)
# else:
# # attempt to gather Attributes we just made
# # this is slightly problematic because compound attributes are invalid
# # until all of their children are created, as in these example from the docs
#
# #addAttr( longName='sampson', numberOfChildren=5, attributeType='compound' )
# #addAttr( longName='homeboy', attributeType='matrix', parent='sampson' )
# #addAttr( longName='midge', attributeType='message', parent='sampson' )
# #addAttr( longName='damien', attributeType='double', parent='sampson' )
# #addAttr( longName='elizabeth', attributeType='double', parent='sampson' )
# #addAttr( longName='sweetpea', attributeType='double', parent='sampson' )
#
#
# if not args:
# args=cmds.ls(sl=1,l=1)
# longName = kwargs.pop( 'longName', kwargs.get('ln',None) )
# shortName = kwargs.pop( 'shortName', kwargs.get('sn',None) )
# name = longName if longName else shortName
# assert name, "could not determine name of attribute"
# res = [ Attribute(x + '.' + name) for x in args]
return res
def hasAttr(pyObj, attr, checkShape=True):
"""convenience function for determining if an object has an attribute.
If checkShape is enabled, the shape node of a transform will also be checked for the attribute.
:rtype: `bool`
"""
if not isinstance(pyObj, PyNode):
raise TypeError, "hasAttr requires a PyNode instance and a string"
import nodetypes
if isinstance(pyObj, nodetypes.Transform):
try:
pyObj.attr(attr, checkShape=checkShape)
return True
except AttributeError:
return False
try:
pyObj.attr(attr)
return True
except AttributeError:
return False
#-----------------------
# Attr Enums
#-----------------------
def _toEnumStr(enums):
if isinstance(enums, dict):
firstKey = enums.iterkeys().next()
firstVal = enums.itervalues().next()
if isinstance(firstKey, basestring) and isinstance(firstVal, int):
enums = ['%s=%s' % (key, val) for key, val in enums.iteritems()]
elif isinstance(firstKey, int) and isinstance(firstVal, basestring):
enums = ['%s=%s' % (val, key) for key, val in enums.iteritems()]
else:
raise ValueError('dict must map from strings to ints, or vice-versa')
if isinstance(enums, basestring):
enumStr = enums
else:
enumStr = ":".join(enums)
return enumStr
def setEnums(attr, enums):
"""
Set the enumerators for an enum attribute.
"""
cmds.addAttr(attr, e=1, en=_toEnumStr(enums))
def getEnums(attr):
"""
Get the enumerators for an enum attribute.
:rtype: `util.enum.EnumDict`
>>> addAttr( "persp", ln='numbers', at='enum', enumName="zero:one:two:thousand=1000:three")
>>> numbers = Attribute('persp.numbers').getEnums()
>>> sorted(numbers.items())
[(u'one', 1), (u'thousand', 1000), (u'three', 1001), (u'two', 2), (u'zero', 0)]
>>> numbers[1]
u'one'
>>> numbers['thousand']
1000
"""
if isinstance(attr, Attribute):
attrName = attr.attrName()
node = attr.node().name()
else:
node, attrName = unicode(attr).rsplit('.', 1)
enum_list = cmds.attributeQuery(attrName, node=node,
listEnum=True)[0].split(':')
enum_dict = {}
index = 0
for enum in enum_list:
try:
name, value = enum.split(u'=')
index = int(value)
enum = name
except:
pass
enum_dict[enum] = index
index += 1
return _util.enum.EnumDict(enum_dict)
#-----------------------
# List Functions
#-----------------------
# def listAttr(*args, **kwargs):
# """
# Modifications:
# - returns an empty list when the result is None
# """
# return _util.listForNone(cmds.listAttr(*args, **kwargs))
def listConnections(*args, **kwargs):
"""
Modifications:
- returns an empty list when the result is None
- returns an empty list (with a warning) when the arg is an empty list, tuple,
set, or frozenset, making it's behavior consistent with when None is
passed, or no args and nothing is selected (would formerly raise a
TypeError)
- When 'connections' flag is True, (and 'plugs' is True) the attribute pairs are returned in a 2D-array::
[['checker1.outColor', 'lambert1.color'], ['checker1.color1', 'fractal1.outColor']]
Note that if 'plugs' is False (the default), for backward compatibility, the returned pairs are somewhat less intuitive attrs + nodes::
[['checker1.outColor', 'lambert1'], ['checker1.color1', 'fractal1']]
- added sourceFirst keyword arg. when sourceFirst is true and connections is also true,
the paired list of plugs is returned in (source,destination) order instead of (thisnode,othernode) order.
this puts the pairs in the order that disconnectAttr and connectAttr expect.
- added ability to pass a list of types
:rtype: `PyNode` list
"""
# We need to force casting to Attribute, as opposed to just Pynode,
# if we are returning plugs, because PyNode will prefer component
# objects over attributes when there is amibiguity - ie,
# PyNode('myNode.rotatePivot') will give a component
args = tuple(None if isinstance(x, (list, tuple, set, frozenset)) and not x
else x for x in args)
plugs = kwargs.get('plugs', kwargs.get('p', False))
if plugs:
CastObj = Attribute
else:
CastObj = PyNode
def makePairs(l):
if l is None:
return []
return [(CastObj(a), CastObj(b)) for (a, b) in _util.pairIter(l)]
# group the core functionality into a funcion, so we can call in a loop when passed a list of types
def doIt(**kwargs):
if kwargs.get('connections', kwargs.get('c', False)):
if kwargs.pop('sourceFirst', False):
source = kwargs.get('source', kwargs.get('s', True))
dest = kwargs.get('destination', kwargs.get('d', True))
if source:
if not dest:
return [(s, d) for d, s in makePairs(cmds.listConnections(*args, **kwargs))]
else:
res = []
kwargs.pop('destination', None)
kwargs['d'] = False
res = [(s, d) for d, s in makePairs(cmds.listConnections(*args, **kwargs))]
kwargs.pop('source', None)
kwargs['s'] = False
kwargs['d'] = True
return makePairs(cmds.listConnections(*args, **kwargs)) + res
# if dest passes through to normal method
return makePairs(cmds.listConnections(*args, **kwargs))
else:
return map(CastObj, _util.listForNone(cmds.listConnections(*args, **kwargs)))
# if passed a list of types, concatenate the resutls
# NOTE: there may be duplicate results if a leaf type and it's parent are both passed: ex. animCurve and animCurveTL
types = kwargs.get('type', kwargs.get('t', None))
if _util.isIterable(types):
types = list(set(types)) # remove dupes from types list
kwargs.pop('type', None)
kwargs.pop('t', None)
res = []
for type in types:
ikwargs = kwargs.copy()
ikwargs['type'] = type
res += doIt(**ikwargs)
return res
else:
return doIt(**kwargs)
def listHistory(*args, **kwargs):
"""
Modifications:
- returns an empty list when the result is None
- raises a RuntimeError when the arg is an empty list, tuple, set, or
frozenset, making it's behavior consistent with when None is passed, or
no args and nothing is selected (would formerly raise a TypeError)
- added a much needed 'type' filter
- added an 'exactType' filter (if both 'exactType' and 'type' are present, 'type' is ignored)
:rtype: `DependNode` list
"""
args = tuple(None if isinstance(x, (list, tuple, set, frozenset)) and not x
else x for x in args)
type = exactType = None
if 'type' in kwargs:
type = kwargs.pop('type')
if 'exactType' in kwargs:
exactType = kwargs.pop('exactType')