-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_language.py
2632 lines (1888 loc) · 81.7 KB
/
_language.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
"""
BSD 3-Clause License:
Copyright (c) 2023, Eric Vignola
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of copyright holders nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
import maya.mel as mel
import maya.cmds as mc
import maya.api.OpenMaya as om
import re
import pickle
import numbers
import codecs
from functools import wraps
from ._generators import sequences, arguments
from .attributes import _clone_attribute, String, lock
MAYA_VERSION = int(mc.about(version=True))
# Container Options
CREATE_CONTAINER = True
USE_SHORTHAND = True
SKIP_SELECTION = True
PUBLISH_PLUGS = True
class DebugPrint():
def __init__(self, message, execute=True):
self.message = message
self.execute = execute
def __enter__(self):
if self.execute:
print (self.message)
def __exit__(self, *args):
if self.execute:
print ('')
# -------------------------- MEMOIZATION FUNCTIONS --------------------------- #
def _name_to_pickle(node_attr):
""" used to create a unique memo key """
if isinstance(node_attr, (list, set, tuple)):
return [_name_to_pickle(x) for x in node_attr]
split = str(node_attr).split('.')
split[0] = mc.ls(split[0], uid=True)[0]
return '.'.join(split)
def _pickle_to_name(uuid_attr, uid=True):
""" convets a memo key back to a Node """
if isinstance(uuid_attr, (list, set, tuple)):
return [_pickle_to_name(x, uid=uid) for x in uuid_attr]
if uuid_attr is None:
return uuid_attr
split = uuid_attr.split('.')
node = mc.ls(split[0], uid=uid)
if node:
split[0] = node[0]
node_attr = '.'.join(split)
return Node(node_attr)
else:
raise Exception('Node {} no longer in scene.'.format(uuid_attr))
def memoize(func):
""" memoizes a function's return according to both args ans kargs """
# empty namespace to hold data
class namespace():
pass
def _deep_float(*args):
# When memoizing, we don't need to see the difference
# between ints and floats when making keys
args_ = []
for x in args:
if x is None or _is_node(x) or isinstance(x, str):
args_.append(x)
elif isinstance(x, numbers.Real):
args_.append(float(x))
elif _is_sequence(x):
args_.append(_deep_float(*x))
return args_
@wraps(func)
def wrapper(*args, **kargs):
# TODO: clean the cache?
# force all ints to floats to generate a common key
args_ = _deep_float(*args)
kargs_ = dict(zip(kargs.keys(), _deep_float(*kargs.values())))
key = hash(pickle.dumps((args_, kargs_, container.containers[:1])))
if key in cache:
result = cache[key]
if result.uuids:
if len(mc.ls(result.uuids)) == len(result.uuids):
return result.data
else:
cache.pop(key, None)
# result not cashed, memoize the result
result = namespace()
result.data = func(*args, **kargs)
result.uuids = []
if not result.data is None:
if _is_node(result.data):
result.uuids = [str(result.data).split('.')[0]]
elif _is_sequence(result.data):
for item in result.data:
if _is_node(item):
result.uuids.append(str(item).split('.')[0])
# convert to uuids
result.uuids = mc.ls(result.uuids, uuid=True)
cache[key] = result
return result.data
cache = {}
return wrapper
def vectorize(func, favor_index=None):
"""
Decorator that passes assymetric arguments to a function.
if favor_index is not None, vectorization will stop once the
first arg count hits a specified index
"""
@wraps(func)
def wrapper(*args, **kargs):
#depth = lambda L: int(_is_sequence(L) and max(map(depth, L))+1)
#depth = lambda L: int((_is_sequence(L) and max(map(depth, L))+1)\
#or (_is_node(L) and L.__data__.compound is not None))
results = []
# are any args or kargs given?
if args or kargs:
# trigger vectorization only if a List is given
valid_args = args and any([_is_list(x) for x in args])
valid_kargs = kargs and any([_is_list(x) for x in kargs.values()])
if valid_args or valid_kargs:
max_count = None
if not favor_index is None:
max_count = len(args[favor_index])
count = 0
for args_, kargs_ in arguments(*args, **kargs):
res = func(*args_, **kargs_)
if res:
results.append(res)
count += 1
if not favor_index is None and count == max_count:
break
# run the function without vectorization
else:
return func(*args, **kargs)
# run the function on its own
else:
return func()
# if only one item result return single output or List
if results:
if len(results) > 1:
try:
return List(results)
except:
return results
return results[0]
return wrapper
# -------------------------------- UTILITIES --------------------------------- #
def _getPlugType(attr):
try:
if attr.hasFn(om.MFn.kAttribute):
attr_fn = om.MFnAttribute(attr)
kargs = attr_fn.getAddAttrCmd(longFlags=False).split()
if '-at' in kargs:
return re.findall('"([^"]*)"', kargs[kargs.index('-at')+1])[0]
elif '-dt' in kargs:
return re.findall('"([^"]*)"', kargs[kargs.index('-dt')+1])[0]
except:
pass
return None
def _plugIsMatrix(attr):
#attr = plug.attribute()
if attr.hasFn(om.MFn.kTypedAttribute):
attr_fn = om.MFnTypedAttribute(attr)
return attr_fn.attrType() == 5
return False
def _plugIsAny(attr):
#attr = plug.attribute()
if attr.hasFn(om.MFn.kTypedAttribute):
attr_fn = om.MFnTypedAttribute(attr)
return attr_fn.attrType() == 24
return False
def _plugIsCompound(attr):
#attr = plug.attribute()
if attr.hasFn(om.MFn.kCompoundAttribute):
attr_fn = om.MFnCompoundAttribute(attr)
return attr_fn.numChildren()
return None
def _getAttrTypeFromPlug(plug):
"""
Returns the string type name of the given attr. Raises RuntimeError
if the node does not have an attribute of the given name.
**attr_name** str name of attr
**RETURNS** str attribute type
>>> node.getAttrType("myAttr")
>>> #RESULTS: "double"
"""
if self.hasAttr(attr_name):
plug = self._fn_set.findPlug(attr_name, False)
attr = plug.attribute()
# numeric
if attr.hasFn(om.MFn.kNumericAttribute):
attr_fn = om.MFnNumericAttribute(attr)
return self.ATTR_NUM_TYPE_STR_MAP[attr_fn.numericType()]
# unit
elif attr.hasFn(om.MFn.kUnitAttribute):
attr_fn = om.MFnUnitAttribute(attr)
return self.ATTR_UNIT_TYPE_STR_MAP[attr_fn.unitType()]
# typed
elif attr.hasFn(om.MFn.kTypedAttribute):
attr_fn = om.MFnTypedAttribute(attr)
return self.ATTR_TYPED_TYPE_STR_MAP[attr_fn.attrType()]
# enum
elif attr.hasFn(om.MFn.kEnumAttribute):
#attr_fn = om.MFnEnumAttribute(attr)
return self.ATTR_ENUM_STR
# message
if attr.hasFn(om.MFn.kMessageAttribute):
#attr_fn = om.MFnMessageAttribute(attr)
return self.ATTR_MESSAGE_STR
else:
raise RuntimeError(f"{self}.{attr_name} currently unsupported by getAttrType().")
else:
raise RuntimeError(f"{self} does not have an attribute named: {attr_name}")
def _disconnect_attr(*args, **kargs):
"""
if a single argument is given, assume user has given us
destinations and wants to disconnect all incoming connections.
"""
try:
# normal use case: disconnect src to dst
if len(args) > 1:
mc.disconnectAttr(*args, **kargs)
# find incomming connections and disconnect
else:
connections = mc.listConnections(args[0], s=True, d=False, p=True)
if connections:
_disconnect_attr(connections[0], args[0], **kargs)
except:
pass
def _is_basestring(obj):
""" tests for basestring """
try:
return isinstance(obj, basestring) # python 2.7
except:
return isinstance(obj, str) # python 3
def _is_list(obj):
""" tests if given input is a List class """
try:
return getattr(obj.__class__, '__CLASS_TYPE__', None) == 'List'
except Exception:
return False
def _is_node(obj):
""" tests if given input is a Node class """
try:
return getattr(obj.__class__, '__CLASS_TYPE__', None) == 'Node'
except Exception:
return False
def _is_attribute(obj):
""" tests if given input is an Attribute class """
try:
return getattr(obj.__class__, '__CLASS_TYPE__', None) == 'Attribute'
except Exception:
return False
def _is_compound(obj):
""" tests object has compound attrs """
try:
# special case for choice nodes, which must be tested using their input plug
if obj.__data__.choice:
try:
choice_node = str(obj).split('.')[0]
return bool(Node(mc.listConnections(f'{choice_node}.input[0]', p=True, s=True, d=False)[0]).__data__.compound)
except:
pass
return bool(obj.__data__.compound)
except:
pass
return False
#def _is_compound(obj):
#""" tests object has compound attrs """
#try:
#return bool(obj.__data__.compound) or obj.__data__.any
#except:
#return False
def _is_array(obj):
""" tests object has array attrs """
try:
return obj.__data__.array
except:
return False
def _get_attr_type(obj):
try:
return mc.getAttr(str(obj), type=True)
except:
return None
def _get_compound(obj):
""" returns compound component (or sequence) """
try:
#return [Node('{}.{}'.format(obj, att)) for att in obj.__data__.compound]
return List([f'{obj}.{att}' for att in obj.__data__.compound])
except:
if _is_sequence(obj):
return obj
#return [obj]
return List([obj])
def _is_sequence(obj):
""" tests if given input is a sequence """
if _is_basestring(obj):
return False
try:
len(obj)
if isinstance(obj, dict):
return False
except Exception:
return False
return True
def _is_matrix(obj):
try:
return obj.__data__.type == 'matrix'
except:
return False
def _is_quaternion(obj):
try:
if _is_compound(obj):
return len(obj.__data__.compound) == 4
except:
return False
def _is_vector(obj):
try:
if _is_compound(obj):
return len(obj.__data__.compound) == 3
except:
return False
def _is_transform(obj):
try:
return obj.__data__.transform == True
except:
return False
def _is_control_point(obj):
try:
return obj.__data__.point == True
except:
return False
@memoize
def _plus_minus_average(*args, operation=1, name='add1'):
node = container.createNode('plusMinusAverage', name=name)
node.operation << operation
if any([_is_compound(x) for x in args]):
for obj in args:
node.input3D << obj
return node.output3D
else:
for obj in args:
node.input1D << obj
return node.output1D
@memoize
def _multiply_divide(input1, input2, operation=1, name='mult1'):
node = container.createNode('multiplyDivide', name=name)
node.operation << operation
if any([_is_compound(input1), _is_compound(input2)]):
node.input1 << input1
node.input2 << input2
return node.output
else:
node.input1X << input1
node.input2X << input2
return node.outputX
@memoize
def _decompose_matrix(token, rotate_order=None):
node = container.createNode('decomposeMatrix')
node.inputMatrix << token
node.inputRotateOrder << rotate_order
return node.outputTranslate
@memoize
def _compose_matrix(scale=None, rotate=None, translate=None, shear=None, rotate_order=None):
node = container.createNode('composeMatrix')
# plug translate
if not translate is None:
node.inputTranslate << translate
# plug scale
if not scale is None:
node.inputScale << scale
# plug shear
if not shear is None:
node.inputShear << shear
# plug rotate
if not rotate is None:
# is this a quaternion?
quat_test = _get_compound(rotate)
if len(quat_test) == 4:
node.useEulerRotation << 0
node.inputQuat << rotate
# this is euler angle
else:
node.inputRotate << rotate
node.inputRotateOrder << rotate_order
return node.outputMatrix
@memoize
def _quaternion_to_euler(quat, rotate_order=None):
node = container.createNode('quatToEuler')
node.inputQuat << quat
node.inputRotateOrder << rotate_order
return node.outputRotate
@memoize
def _euler_to_quaternion(token, rotate_order=None):
node = container.createNode('eulerToQuat')
node.inputRotate << token
node.inputRotateOrder << rotate_order
return node.outputQuat
@memoize
def _matrix_multiply(*tokens, **kargs):
local = ([kargs.pop(x) for x in list(kargs.keys()) if x in ['local']] or [None] )[-1]
if kargs:
raise Exception('Unsupported keyword args: {}'.format(kargs.keys()))
# are we doing point matrix mult?
if len(tokens) == 2:
count = 0
matrix_index = 0
vector_index = 0
for i, obj in enumerate(tokens):
if _is_matrix(obj):
matrix_index = i
count +=1
else:
vector_index = i
if count == 1:
node = container.createNode('pointMatrixMult')
node.inMatrix << tokens[matrix_index]
node.inPoint << tokens[vector_index]
node.vectorMultiply << local
return node.output
# do a straight matrix sum operation
node = container.createNode('multMatrix')
for obj in tokens:
node.matrixIn << obj
return node.matrixSum
@memoize
def _matrix_add(*tokens, **kargs):
weights = ([kargs.pop(x) for x in list(kargs.keys()) if x in ['weights']] or [None] )[-1]
if kargs:
raise Exception('Unsupported keyword args: {}'%kargs.keys())
if weights is None:
node = container.createNode('addMatrix')
for obj in tokens:
node.matrixIn << obj
else:
if isinstance(weights, numbers.Real) or _is_node(weights):
weights = [weights]
node = container.createNode('wtAddMatrix')
index = 0
for obj, w in sequences(tokens, weights):
node.wtMatrix[index].matrixIn << obj
node.wtMatrix[index].weightIn << w
index+=1
return node.matrixSum
@memoize
def _matrix_inverse(token):
node = container.createNode('inverseMatrix')
node.inputMatrix << token
return node.outputMatrix
@memoize
def _quaternion_add(quat1, quat2):
node = container.createNode('quatAdd')
node.input1Quat << quat1
node.input2Quat << quat2
return node.outputQuat
@memoize
def _quaternion_multiply(quat1, quat2):
node = container.createNode('quatProd')
node.input1Quat << quat1
node.input2Quat << quat2
return node.outputQuat
@memoize
def _quaternion_subtract(quat1, quat2):
node = container.createNode('quatSub')
node.input1Quat << quat1
node.input2Quat << quat2
return node.outputQuat
@memoize
def _condition_op(input0, op, input1):
"""
Defines the basic condition operators and returns a simple True/False output.
This can then be used in condition (cond) function that operates like an "if" statement
such as cond(<condition_op>, <if_true>, <if_false>)
ex: cond(Node('pCube1').t > 5, Node('pCube2').t, Node('pCube3').t)
"""
# make sure condition operator is valid
OPERATORS = {'==' : 0,
'!=' : 1,
'>' : 2,
'>=' : 3,
'<' : 4,
'<=' : 5}
NAMES = {'==' : 'equal1',
'!=' : 'not_equal1',
'>' : 'greater1',
'>=' : 'greater_or_equal1',
'<' : 'lesser1',
'<=' : 'lesser_or_equal1'}
if op not in OPERATORS:
raise Exception('Unsupported condition operator. given: {}'.format(op))
# if neither input0 or input1 are compound attrs, just do a straight up setup
if not _is_compound(input0) and not _is_compound(input1):
node = container.createNode('condition', name=NAMES[op])
node.firstTerm << input0 # set or connect first term
node.secondTerm << input1 # set or connect second term
node.operation << OPERATORS[op] # set condition
node.colorIfTrue << 1 # True
node.colorIfFalse << 0 # False
return node.outColorR
# build a setup and pipe the output to a vector
else:
with container(NAMES[op]):
# create pass through plugs
compound_input0 = _get_compound(input0)
compound_input1 = _get_compound(input1)
count0 = len(compound_input0)
count1 = len(compound_input1)
count = max(count0, count1)
output_plug = _constant([0]*count, name='output_plug1')
output_plugs = _get_compound(output_plug)
# publish the plugs
index = 0
for input0, input1 in sequences(compound_input0, compound_input1):
node = container.createNode('condition', name=NAMES[op], ss=True)
node.firstTerm << input0 # set or connect first term
node.secondTerm << input1 # set or connect second term
node.operation << OPERATORS[op] # set condition
node.colorIfTrue << 1
node.colorIfFalse << 0
output_plugs[index] << node.outColorR
index += 1
return output_plug
@vectorize
@memoize
def condition(condition_op, if_true, if_false):
"""
cond(<condition_op>, <token if true>, <token if false>)
Creates condition node to solve "if" statements.
Examples
--------
>>> cond(pCube1.t > pCube2.t, 0, pCube3.t)
>>> cond(pCube1.rx < 45, pCube1.rx, 45)
"""
if isinstance(condition_op, numbers.Real):
if condition_op:
return if_true
else:
return if_false
# if condition_op is a compound attrs, just do a straight up setup
if not _is_compound(condition_op):
node = container.createNode('condition', name='condition1')
node.firstTerm << condition_op # set or connect first term
node.secondTerm << 1 # set or connect second term
node.operation << 0 # set condition
node.colorIfTrue << if_true # True
node.colorIfFalse << if_false # False
if _is_compound(if_true) or _is_compound(if_false):
return node.outColor
return node.outColorR
# build a setup and pipe the output to a vector
else:
with container('condition1'):
# create pass through plugs
compound_op = _get_compound(condition_op)
compound_input0 = _get_compound(if_true)
compound_input1 = _get_compound(if_false)
# if the operator is all numbers
if all([isinstance(x, numbers.Real) for x in compound_op]):
result = []
for op, if_true, if_false in sequences(compound_op, compound_input0, compound_input1):
if op:
result.append(is_true)
else:
result.append(is_false)
return result
# else, build a tree and publish the plugs
index = 0
count0 = len(compound_input0)
count1 = len(compound_input1)
count2 = len(compound_op)
count = max(count0, count1, count2)
# this will create a neat output plug when publishing nodes
if container.create_container and count == 3:
output_plug = container.createNode('plusMinusAverage', name='output_plug1').output3D
output_plugs = _get_compound(output_plug)
input_plugs = _get_compound(output_plug.input3D)
elif container.create_container and count == 1:
output_plug = container.createNode('plusMinusAverage', name='output_plug1').output1D
output_plugs = _get_compound(output_plug)
input_plugs = _get_compound(output_plug.input1D)
elif container.create_container and count == 2:
output_plug = container.createNode('plusMinusAverage', name='output_plug1').output2D
output_plugs = _get_compound(output_plug)
input_plugs = _get_compound(output_plug.input2D)
# use a constant
else:
output_plug = _constant([0]*count, name='output_plug1')
output_plugs = _get_compound(output_plug)
input_plugs = output_plugs
for op, if_true, if_false in sequences(compound_op, compound_input0, compound_input1):
if isinstance(op, numbers.Real):
if op:
input_plugs[index] << if_true
else:
input_plugs[index] << if_false
else:
node = container.createNode('condition', name='condition1', ss=True)
node.firstTerm << op # set or connect first term
node.secondTerm << 1 # set or connect second term
node.operation << 0 # set condition
node.colorIfTrue << if_true
node.colorIfFalse << if_false
input_plugs[index] << node.outColorR
index += 1
return output_plug
# -------------------------- INIT container MANAGER -------------------------- #
class Container():
"""
A class that tracks the container depth and tracks created nodes and connections.
"""
def __init__(self):
self.containers = [] # keep track of container depth
self.published = None
self.create_container = CREATE_CONTAINER
self.skip_selection = SKIP_SELECTION
self.use_shorthand = USE_SHORTHAND
self.publish_plugs = PUBLISH_PLUGS
self.debug = True
def __call__(self, name):
""" Sets the desired container name which will be created
when the create_node method is invoked
"""
if self.create_container:
new_container = None
if not self.containers:
new_container = Node(mc.createNode('container', name=name))
self.containers.append(new_container)
return self
def __enter__(self):
# enter the container creation interface
return self
def __exit__(self, exception_type, exception_val, trace):
# upon exiting the interace, create an inventory of the contained
# nodes and their published attrs or future node explorer interface
if self.containers and len(self.containers) == 1:
data = {}
attrs = mc.container(self.containers[0], query=True, bindAttr=True)
data['plugs'] = [_name_to_pickle(x) for x in attrs[0::2]] if attrs else None
data['names'] = attrs[1::2] if attrs else None
data['nodes'] = mc.container(self.containers[0], query=True, nodeList=True)
data['nodes'] = [_name_to_pickle(x) for x in data['nodes']] if data['nodes'] else None
data = codecs.encode(pickle.dumps(data, protocol=pickle.HIGHEST_PROTOCOL), "base64").decode()
self.containers[0] << String('__container_data__', h=True)
self.containers[0].__container_data__ << data << lock
# manage scope
self.containers = self.containers[:-1]
# set published state
if not self.containers:
self.published = None
def _cleanup_unit_conversion(self, plugs):
# include any conversion nodes into the leaf container
if plugs and self.containers:
unit_conversion_nodes = mc.listConnections(plugs, s=True, d=False, type='unitConversion') or None
if unit_conversion_nodes:
self.add(unit_conversion_nodes)
def shorthand(self, src, dst):
# --- GRACEFULLY HANDLES SHORTHAND NODE CONNECTIONS --- #
def _matrix_to_transform(src, dst):
attr = '.'.join(str(dst).split('.')[1:])
node = _decompose_matrix(src, rotate_order=dst.ro)
if not attr:
self.inject(node.outputScale, dst.s)
self.inject(node.outputRotate, dst.r)
self.inject(node.outputTranslate, dst.t)
self.inject(node.outputShear, dst.shear)
else:
if attr in ['scale', 'scaleX', 'scaleY', 'scaleZ']:
self.inject(node.outputScale, dst)
elif attr in ['rotate', 'rotateX', 'rotateY', 'rotateZ']:
self.inject(node.outputRotate, dst)
elif attr in ['translate', 'translateX', 'translateY', 'translateZ']:
self.inject(node.outputTranslate, dst)
elif attr in ['shear', 'shearXY', 'shearXZ', 'shearYZ']:
self.inject(node.outputShear, dst)
else:
return False
return True
def _matrix_to_quaternion(src, dst):
node = _decompose_matrix(src)
self.inject(node.outputQuat, dst)
return True
def _matrix_to_vector(src, dst):
node = _decompose_matrix(src, rotate_order=dst.ro)