def ar_shiftInputOutputConnections(sourceInp, sourceOut, destInp, destOut): """ @ get connections from source and connect with destination. Args: sourceInp (str): source input shape. sourceOut (str): source output shape. destInp (str): destination input shape. destOut (str): destination output shape. Returns: bool. """ sourceInp = pm.PyNode(sourceInp) sourceOut = pm.PyNode(sourceOut) destInp = pm.PyNode(destInp) destOut = pm.PyNode(destOut) # set intermediate objects. destInp.setIntermediateObject(False) destOut.setIntermediateObject(True) # output connection. outConn = pm.connectionInfo(sourceOut + '.worldMesh[0]', dfs=True) pm.connectAttr(destOut + '.worldMesh[0]', outConn[0], f=True) # input connection. inpConn = pm.connectionInfo(sourceInp + '.inMesh', sfd=True) pm.connectAttr(inpConn, destInp + '.inMesh', f=True) return True
def mip_populate_image_list(imageListDropdown, *args, **kwargs): ''' ''' global defaultString imageListDropdown.clear() imageListDropdown.addItems([defaultString]) sel = pm.ls(type='imagePlane') for IP in sel: #maya 2013+ made changes to image planes IPlist = str(IP).split('>') if len(IPlist) > 1: IP = IPlist[1] print 'imagePlane: {0}'.format(IP) #clean up expressions expressions = pm.connectionInfo(IP+'.displayMode', sourceFromDestination=True) if expressions: expName = expressions.split('.')[0] expInput = pm.connectionInfo(expName+'.input[0]', sourceFromDestination=True) if not expInput: pm.delete(expName) #add unconnected image planes to list connections = pm.connectionInfo(IP+'.message', destinationFromSource=True) for item in connections: allowedCams = ['front', 'side', 'top'] print 'item: {0}'.format(item) for cam in allowedCams: if item.split('Shape.')[0] == cam: activeConn = pm.connectionInfo(IP+'.displayMode', sourceFromDestination=True) print 'activeConn: {0}'.format(activeConn) if not activeConn: imageListDropdown.addItems([IP])
def __init__(self, name, baseObj, parentGrpName): self.name = name self.baseObj = baseObj self.parentGrpName = parentGrpName # Duplicate muscle control pm.duplicate(self.baseObj.name, n=self.name) # Delete the child squash and stretch curves. (Cross sections do not have.) children = pm.listRelatives(self.name, type='transform', path=True) # listRelatives returns a list if children: pm.delete(children) # Unlock transforms for reparenting attrList = [ 'translateX', 'translateY', 'translateZ', 'rotateX', 'rotateY', 'rotateZ', 'scaleX', 'scaleY', 'scaleZ' ] for attr in attrList: pm.setAttr('%s.%s' % (self.name, attr), lock=False) # Make visible visibility = '%s.visibility' % self.name pm.setAttr(visibility, keyable=True) if pm.connectionInfo(visibility, isDestination=True): source = pm.connectionInfo(visibility, sourceFromDestination=True) pm.disconnectAttr(source, visibility) # Parent to parent grp pm.parent(self.name, parentGrpName) # Add muscle cross target to muscle controls's target list self.baseObj.addTarget(self.name)
def deleteConnection(plug): if pm.connectionInfo(plug, isDestination=True): plug = pm.connectionInfo(plug, getExactDestination=True) readOnly = pm.ls(plug, ro=True) #delete -icn doesn't work if destination attr is readOnly if readOnly: source = pm.connectionInfo(plug, sourceFromDestination=True) pm.disconnectAttr(source, plug) else: pm.delete(plug, icn=True)
def reconnectAnimationCurves(self, src, dst): for transform in ['translate', 'rotate']: for axis in ['X', 'Y', 'Z']: # If attribute has a connection (anim curve) means it's animated src_attr = '%s.%s%s'%(src, transform, axis) dst_attr = '%s.%s%s'%(dst, transform, axis) if pc.connectionInfo(src_attr, id=True): conn = pc.connectionInfo(src_attr, sfd=True) pc.connectAttr(conn, dst_attr) pc.disconnectAttr(conn, src_attr) else: pc.setAttr(dst_attr, pc.getAttr(src_attr))
def reconnectAnimationCurves(self, src, dst): for transform in ['translate', 'rotate']: for axis in ['X', 'Y', 'Z']: # If attribute has a connection (anim curve) means it's animated src_attr = '%s.%s%s' % (src, transform, axis) dst_attr = '%s.%s%s' % (dst, transform, axis) if pc.connectionInfo(src_attr, id=True): conn = pc.connectionInfo(src_attr, sfd=True) pc.connectAttr(conn, dst_attr) pc.disconnectAttr(conn, src_attr) else: pc.setAttr(dst_attr, pc.getAttr(src_attr))
def getNextAvailableIndexDefault(node, attribute_name, default, start_index=0): """ Gets the first available index in which the given attribute is open and equal to the given default. Args: node (pm.nodetypes.DependNode): Node to get index of attribute. attribute_name (string): Name of attribute with "[{}]" so that index search can occur. default (any): Default value to attribute will have to know it is available. start_index (integer): index to start searching for the available attribute.. Returns: (integer): First available attribute index. """ i = start_index max_iterations = 65535 # typical c++ unsigned int range while i < max_iterations: attribute = node.attr(attribute_name.format(str(i))) plug = pm.connectionInfo(attribute, sfd=True) if not plug and attribute.get() == default: return i i += 1 return 0
def deleteIntermediateShapes(obj): geos = obj.getShapes() for geo in geos: if geo.isIntermediate(): cntWMAux = pm.connectionInfo(geo + '.worldMesh[0]', isSource=True) if not cntWMAux: pm.delete(geo) return obj
def deleteIntermediateShapes(*args): geos = pm.ls(type='mesh') for geo in geos: if geo.isIntermediate(): cntWMAux = pm.connectionInfo(geo + '.worldMesh[0]', isSource=True) if not cntWMAux: pm.delete(geo) return 'ok'
def disconnectFromMWBevelSet(bevelSetName, meshTransform): bevelSet = pm.ls(bevelSetName, type='objectSet') meshTransformNode = pm.ls(meshTransform) if len(bevelSet) and len(meshTransformNode): meshNode = meshTransformNode[0].getShape() if isinstance( meshTransformNode[0], pm.nt.Transform) else meshTransformNode[0] meshAttr = None bevelSetAttr = bevelSet[0].name() + '.memberWireframeColor' for destinationAttr in pm.connectionInfo(bevelSetAttr, dfs=True): if destinationAttr.startswith(meshNode.name()): meshAttr = destinationAttr.rpartition('.')[0] pm.disconnectAttr(bevelSetAttr, destinationAttr) break if meshAttr is not None: for destinationAttr in pm.connectionInfo(meshAttr, dfs=True): if destinationAttr.startswith(bevelSet[0].name()): pm.disconnectAttr(meshAttr, destinationAttr) break
def findParentModule(self): ''' Define routine to find hook object using hook constraint for targetObject. ''' hook_constraint = self.userSpecifiedName + ":targetParent_pointConstraint" source_attr = pm.connectionInfo(hook_constraint + ".target[0].targetParentMatrix", sourceFromDestination=True) source_node = str(source_attr).rpartition(".")[0] return source_node
def generateProfileCurve(self, profile_node): count = profile_node.outMainCurveCount.get() crv_list = [] for i in range(count): attr = profile_node.outMainCurves[i] if pm.connectionInfo(attr, isSource=1): continue crv = pm.createNode("nurbsCurve") pm.connectAttr(attr, "%s.create" % crv, f=1) attr.disconnect(crv.create) crv_list.append(crv.getParent()) return crv_list
def shaderTransform(): global nameSpaceInput,PATH nameSpaceInput = mc.textFieldGrp('nameSpaceInput',text = 1,q=1) PATH = mc.textFieldGrp('PATH',text = 1,q=1) impShader = pm.importFile(PATH,i = 1,typ = 'mayaAscii',iv = 1, ra = 1,mnc = 0,ns = nameSpaceInput,op = 'v=0;p=17;f=0',pr = 1) impFiles = mc.ls(nameSpaceInput + ':*') impFileList = [] #which include some unmaterial List# repeatShadedList = [] #temp Trash List # shadedList = [] #objectShaded in the old file# oldMaterialList = [] #objectShaded material in the old file# newMaterialList = [] #new material which use for the old file# for impFileString in impFiles: impFile = impFileString.split(':') impFileList.append(impFile[1]) for impFile in impFileList: pm.hyperShade(objects=impFile) shadedObjShape = pm.ls(sl = 1)[0] shadedObj = shadedObjShape.getParent() repeatShadedList.append(shadedObj) shadedList = list(set(repeatShadedList)) for shadedObj in shadedList: shadingEngine = pm.listConnections(shadedObj.getShape(),type = 'shadingEngine') if pm.connectionInfo(shadingEngine[0] + '.surfaceShader',isDestination=True): oldMaterial = pm.connectionInfo(shadingEngine[0] + '.surfaceShader',sourceFromDestination=True) oldMaterialList.append(oldMaterial.split('.')[0]) for oldMaterial in oldMaterialList: newPreShadedMaterial = nameSpaceInput + ':' + oldMaterial newMaterialList.append(newPreShadedMaterial) for num,newMaterial in enumerate(newMaterialList): pm.select(shadedList[num]) SG= mc.sets(renderable=True,noSurfaceShader=True,empty=True,n = newMaterial + 'SG') mc.connectAttr('%s.outColor' %newMaterial ,'%s.surfaceShader' %SG) mc.sets(e = 1, fe = SG)
def FindFirstFreeConnection(_attribute): found = False index = 0 while not found: if pm.connectionInfo("%s[%d]" %(_attribute, index), isDestination = True): index += 1 else: found = True return index
def assignShader (cls, shader, objs, *args, **kwargs): ''' assign the shader to the list ''' shadingGroup = pm.connectionInfo(shader.outColor, dfs=True) try: shadingGroup = shadingGroup[0].split('.')[0] except: pm.warning('This Shader has no Shading Group') if objs: for obj in objs: pm.select(obj, r=True) pm.sets(shadingGroup, edit=True, forceElement=True) pm.select(clear=True)
def revertToLambert(cls, shader, textureSampler='.diffuseMapSampler', *args, **kwargs): """ create lambert copies of all the cgfx shaders and connect the diffuse texture """ if pm.getAttr(shader+'.shader'): diffuseTexNode = pm.connectionInfo(shader+textureSampler, sourceFromDestination=True) lambert = pm.shadingNode('lambert', asShader=True, name='L_'+shader ) lambertSG = pm.sets(renderable=True, noSurfaceShader=True, empty=True, name='L_'+shader+'SG' ) pm.connectAttr(lambert+'.outColor', lambertSG+'.surfaceShader', force=True) if diffuseTexNode: pm.connectAttr(diffuseTexNode, lambert+'.color', force=True) pm.hyperShade(objects=shader) pm.sets(lambertSG, edit=True, forceElement=True) pm.select(clear=True)
def noIntermediateShapes(): geos = pm.ls(type='mesh') nameErr = False for geo in geos: if geo.isIntermediate(): cntWMAux = pm.connectionInfo(geo + '.worldMesh[0]', isSource=True) if not cntWMAux: nameErr = True break return nameErr
def selectIntermediateShapes(*args): pm.select(cl=True) geos = pm.ls(type='mesh') for geo in geos: if geo.isIntermediate(): cntWMAux = pm.connectionInfo(geo + '.worldMesh[0]', isSource=True) if not cntWMAux: obj = geo.listRelatives(p=True, type='transform')[0] pm.select(obj, add=True) return 'select'
def mip_populate_image_list(imageListDropdown, *args, **kwargs): ''' ''' global defaultString imageListDropdown.clear() imageListDropdown.addItems([defaultString]) sel = pm.ls(type='imagePlane') for IP in sel: #maya 2013+ made changes to image planes IPlist = str(IP).split('>') if len(IPlist) > 1: IP = IPlist[1] print 'imagePlane: {0}'.format(IP) #clean up expressions expressions = pm.connectionInfo(IP + '.displayMode', sourceFromDestination=True) if expressions: expName = expressions.split('.')[0] expInput = pm.connectionInfo(expName + '.input[0]', sourceFromDestination=True) if not expInput: pm.delete(expName) #add unconnected image planes to list connections = pm.connectionInfo(IP + '.message', destinationFromSource=True) for item in connections: allowedCams = ['front', 'side', 'top'] print 'item: {0}'.format(item) for cam in allowedCams: if item.split('Shape.')[0] == cam: activeConn = pm.connectionInfo(IP + '.displayMode', sourceFromDestination=True) print 'activeConn: {0}'.format(activeConn) if not activeConn: imageListDropdown.addItems([IP])
def returnDrivenAttribute(attribute, skipConversionNodes=False): """ Returns the drivenAttribute of an attribute if there is one :param attribute: pymel obj :param skipConversionNodes: bool :return: list || False """ if (pm.connectionInfo(attribute, isSource=True)) == True: destinationBuffer = pm.listConnections(attribute, scn=skipConversionNodes, s=False, d=True, plugs=True) if not destinationBuffer: destinationBuffer = pm.connectionInfo(attribute, destinationFromSource=True) if destinationBuffer: returnList = [] for lnk in destinationBuffer: returnList.append(str(pm.ls(lnk)[0])) return returnList return False return False
def disconnect_layers( layers ): layer_nodes = [ ] for layer in layers: node = get_bake_layer( layer ) if not node == False: layer_nodes.append( node ) for layer in layer_nodes: connect_attr = layer.attr( HIGH_CONNECT_ATTR ) for plug in pmc.connectionInfo( connect_attr, destinationFromSource = True ): if pmc.PyNode( plug.split( '.' )[ 0 ] ) in layer_nodes: pmc.disconnectAttr( connect_attr, plug )
def remove_from_bake_layer( layer, objects = None ): if objects == None: objects = pmc.ls( sl = True ) node = get_bake_layer( layer ) if node == False: pmc.error( 'You must specify a Bake Layer for this command' ) return False connect_attr = node.attr( LAYER_MEMBERS_ATTR ) for plug in pmc.connectionInfo( connect_attr, destinationFromSource = True ): if pmc.PyNode( plug.split( '.' )[ 0 ] ) in objects: pmc.disconnectAttr( connect_attr, plug )
def ar_ikFootLiftToeReOrient(ctlOffGrp, orientSample, rotateAxis='.rz', reverseConnections=False): """ @ re orient ikLiftToe controllers. Args: ctlOffGrp (str): controller offset group. orientSample (str): orientation sample. rotateAxis (str): rotation axis with "." in prefix. reverseConnections: bool Returns: bool. """ ctlOffGrp = pm.PyNode(ctlOffGrp) orientSample = pm.PyNode(orientSample) # offsetGroup changes. pm.select(cl=True) jt = pm.joint(n=ctlOffGrp[:-2] + 'Extra' + ctlOffGrp[-2:]) pm.select(cl=True) jtTemp = pm.joint(n=ctlOffGrp + 'ConnTemp') pm.delete(pm.parentConstraint(orientSample, jt)) parentGrp = ctlOffGrp.getParent() pm.parent(jt, parentGrp) pm.makeIdentity(jt, apply=True, t=1, r=1, s=1, n=0, pn=1) # query connection. connections = pm.connectionInfo(ctlOffGrp.rx, sfd=True) # attach connection. pm.connectAttr(connections, jtTemp + rotateAxis) pm.disconnectAttr(connections, ctlOffGrp.rx) # parent. child = ctlOffGrp.getChildren() pm.parent(child, jt) jtNewName = str(ctlOffGrp) pm.delete(ctlOffGrp) jt.rename(jtNewName) if reverseConnections: mdn = pm.createNode('multiplyDivide', n='multiplyDivideReverse' + jt) mdn.input2X.set(-1) pm.connectAttr(connections, mdn.input1X) mdn.outputX.connect(jt + rotateAxis) connName = pm.PyNode(connections.split('.')[0]) if type(connName) == pm.nodetypes.UnitConversion: connName.conversionFactor.set(1) else: pm.connectAttr(connections, jt + rotateAxis) # delete tempJoint. pm.delete(jtTemp)
def wireup(cvp, ctrl, scale, mirror): """ """ def spaceScale(attr, cvNew, scale): """ """ # Translate if attr.startswith('translate'): pm.scaleKey(cvNew, vs= scale, vp= 0, ssk= False) # Scale if attr.startswith('scale'): pm.scaleKey(cvNew, vs= scale, vp= 1, ssk= False) def keyMirror(attr, cvNew, mirror): """ """ for axis in mirror: # Translate if axis.startswith('t') and attr.startswith('translate' + axis[-1].upper()): pm.scaleKey(cvNew, vs= -1, vp= 0, ssk= False) # Rotation if axis.startswith('r') and attr.startswith('rotate' + axis[-1].upper()): pm.scaleKey(cvNew, vs= -1, vp= 0, ssk= False) for cat in cvp: attr = cat.split('.')[1] if pm.attributeQuery(attr, node= ctrl, exists= True): disCat = ctrl + '.' + attr if not pm.connectionInfo(disCat, id= True): lock = False if pm.getAttr(disCat, l= True): lock = True pm.setAttr(disCat, l= False) cvNew = cg.amcveRebuild(cat.replace('.', '_'), cvp[cat]) pm.connectAttr(cvNew.output, disCat) if scale: spaceScale(attr, cvNew, scale) if mirror: keyMirror(attr, cvNew, mirror) if lock: pm.setAttr(disCat, l= True) else: pass return 0
def setDefaultPose( self,*args): objs = pm.ls( sl=True ) for obj in objs: allAttrs = pm.listAttr( obj, keyable=True, unlocked=True ) userAttrs = pm.listAttr(obj, ud=True, unlocked=True) for attr in allAttrs: if pm.connectionInfo( obj.attr(attr), isDestination=True ): pass if attr in userAttrs:# match main attributes try: value = obj.attr(attr).get() pm.addAttr( obj.attr(attr) , e=True, dv=value ) except: pm.warning( "ehm_tools...setDefaultPose: Could not set some of user defined attributes, skipped! \t %s" %obj )
def getConstraintTargets(cst): """ Return a dict of {index: tagetNode} """ cst= str(cst) indices = MC.getAttr('%s.target' % cst, mi=1) targets = {} for index in indices: attrs = MC.attributeQuery('target', listChildren=1, n=cst) nonMatrixAttrs = [x for x in attrs if 'Matrix' not in x] cnct = pm.connectionInfo("%s.target[%i].%s" % (cst, index, nonMatrixAttrs[0]), sfd=1) if cnct: node = cnct.split('.')[0] targets[index] = pm.PyNode(node) return targets
def __selPartialSkinJoint(self,*args): pm.select(cl = 1) partialJointList = [] metaT = pm.optionMenu(self.partialSkinJointMenu, q = 1,v = 1) meta = pm.ls(metaT)[0] jointStrs = pm.connectionInfo(meta.partialSkinJoints, destinationFromSource=True) pm.select(cl = 1) for jointStr in jointStrs : joint = jointStr.split('.') pm.select(joint[0],add = 1) partialJointList.append(joint[0]) print 'Partial Skin joint from ' + metaT + ' are :' print print partialJointList print print 'Number of ' + metaT + ' is ' + str(len(partialJointList))
def __selMetaCtrlShape(self,*args): pm.select(cl = 1) ctrlList = [] metaT = pm.optionMenu(self.ctrlShapeSelMenu, q = 1,v = 1) meta = pm.ls(metaT)[0] ctrlStrs = pm.connectionInfo(meta.controls, destinationFromSource=True) pm.select(cl = 1) for ctrlStr in ctrlStrs : ctrl = ctrlStr.split('.') pm.select(ctrl[0],add = 1) ctrlList.append(ctrl[0]) print 'ctrlShapes from ' + metaT + ' are :' print print ctrlList print print 'Number of ' + metaT + ' is ' + str(len(ctrlList))
def produceOverrides(self, object): """Check what overrides it's possible to get from this object.""" nodeType = pm.nodeType(object) if nodeType == 'displacementShader': return [(object, OVERRIDE_DISPLACEMENT)] elif nodeType == 'walterOverride': return [(object, OVERRIDE_ATTRIBUTE)] elif nodeType == 'shadingEngine': # Get the shaders of this shading group. result = [] types = [("surfaceShader", OVERRIDE_SHADER), ("displacementShader", OVERRIDE_DISPLACEMENT)] for a, t in types: child = pm.connectionInfo("%s.%s" % (object, a), sourceFromDestination=True) if not child: continue result.append((child.split('.')[0], t)) return result return [(object, OVERRIDE_SHADER)]
def __selAllMetaSkinJoint(self, *args): pm.select(cl = 1) metaList = [] allSkinJoint = [] metaStr = pm.ls('*META*',type = 'lightInfo') for meta in metaStr: jointsStr = pm.connectionInfo(meta.skinJoints, destinationFromSource=True) for jointStr in jointsStr: joint = jointStr.split('.') pm.select(joint[0],add = 1) allSkinJoint.append(joint[0]) print 'Skin joint from ALL metas are :' print print allSkinJoint print print 'Number of ALL meta is ' + str(len(allSkinJoint))
def disAttr(): # NOTE 获取当前通道盒选择的属性 attr_list = pm.channelBox('mainChannelBox', q=1, sma=1) # NOTE 没有选择跳过执行 if not attr_list: return for sel in pm.ls(sl=1): for attr in attr_list: if not hasattr(sel, attr): continue attr = pm.PyNode("%s.%s" % (sel, attr)) des = pm.PyNode(pm.connectionInfo(attr, ged=1)) if des == attr: attr.disconnect() else: # NOTE 如果获取的属性不相等说明是 Translate类似集合 的上层链接 src = des.listConnections(d=0, s=1, p=1)[0] des.disconnect() for d_attr, s_attr in zip(des.getChildren(), src.getChildren()): if d_attr != attr: s_attr.connect(d_attr)
def makeJointHair(self, sel, hairSystem): simDuped = pm.duplicate(sel, n='sim_%s' % sel.nodeName())[0] mixDuped = pm.duplicate(sel, n='mix_%s' % sel.nodeName())[0] wgtDuped = pm.duplicate(sel, n='weight_%s' % sel.nodeName())[0] selJointList = self.getJointChainList(sel) simJointList = self.getJointChainList(simDuped) mixJointList = self.getJointChainList(mixDuped) wgtJointList = self.getJointChainList(wgtDuped) if not (selJointList and simJointList and mixJointList): return False num = len(selJointList) pos = sel.getTranslation(space='world') ctrlGrp = pm.group(n='%s_ctrls#' % sel.nodeName(), em=1) axis, circle = self.makeXformController( '%s_top_ctrl#' % sel.nodeName(), '%s_top_ctrl_axis#' % sel.nodeName(), selJointList[0]) circle.addAttr('space', at='enum', en='World:Local', k=1, dv=self.dnspRBGval - 1) circle.addAttr('ctrl_size', at='double', k=1, dv=1.0) circle.attr('ctrl_size') >> circle.attr('scaleX') circle.attr('ctrl_size') >> circle.attr('scaleY') circle.attr('ctrl_size') >> circle.attr('scaleZ') pntMatrix = [] skclList = list(set(sel.outputs(type='skinCluster'))) for i in xrange(num): if i != 0: pm.rename(simJointList[i], 'sim_%s' % simJointList[i].nodeName()) pm.rename(mixJointList[i], 'mix_%s' % mixJointList[i].nodeName()) pos = selJointList[i].getTranslation(space='world') ofstJoint = pm.rename( pm.insertJoint(mixJointList[i]), mixJointList[i].nodeName().replace('mix', 'offset')) pntMatrix.append(pos) attrList = ['tx', 'ty', 'tz', 'rx', 'ry', 'rz'] for attr in attrList: simJointList[i].attr(attr) >> mixJointList[i].attr(attr) pm.parentConstraint(ofstJoint, selJointList[i], mo=True) mixJointList[i].attr('radius').set(0.0) ofstJoint.attr('radius').set(0.0) if not (i == num - 1 and not self.pctlCBXval): ''' # If on, no controllers will be created to the joints which does't have any skinCluster for skcl in skclList: if selJointList[i] in skcl.getInfluence(): break else: continue ''' if self.ctshRBGval == 1: ctrl = self.makeCircleController( '%s_ctrl' % selJointList[i].nodeName()) elif self.ctshRBGval == 2: ctrl = self.makePinController('%s_ctrl' % selJointList[i].nodeName()) elif self.ctshRBGval == 3: ctrl = self.makeOctaController('%s_ctrl' % selJointList[i].nodeName()) ctrl.attr('overrideEnabled').set(1) ctrl.attr('overrideColor').set((self.colrPLTval)) ctrlAxis = pm.group(ctrl, n='%s_ctrl_axis' % selJointList[i].nodeName()) ctrlAxis.attr('rotatePivot').set([0, 0, 0]) ctrlAxis.attr('scalePivot').set([0, 0, 0]) circle.attr('ctrl_size') >> ctrl.attr('scaleX') circle.attr('ctrl_size') >> ctrl.attr('scaleY') circle.attr('ctrl_size') >> ctrl.attr('scaleZ') pm.parentConstraint(mixJointList[i], ctrlAxis) pm.parentConstraint(ctrl, ofstJoint) pm.parent(ctrlAxis, ctrlGrp) # Pour weights to simJointList temporarily for skcl in skclList: if selJointList[i] in skcl.getInfluence(): skcl.addInfluence(wgtJointList[i], wt=0) inflList = skcl.getInfluence() isMaintainMax = skcl.attr('maintainMaxInfluences').get() maxInfl = skcl.attr('maxInfluences').get() isFullInfl = False if isMaintainMax and maxInfl == len(inflList): isFullInfl = True skcl.attr('maintainMaxInfluences').set(False) for infl in inflList: if infl == selJointList[i] or infl == wgtJointList[i]: infl.attr('lockInfluenceWeights').set(False) else: infl.attr('lockInfluenceWeights').set(True) for geo in skcl.getGeometry(): pm.skinPercent(skcl, geo.verts, nrm=True, tv=[selJointList[i], 0]) skcl.removeInfluence(selJointList[i]) if isFullInfl: skcl.attr('maintainMaxInfluences').set(True) crv1d = pm.curve(d=1, p=pntMatrix) crv = pm.fitBspline(crv1d, ch=1, tol=0.001) follicle, hcrv, hairSystem = self.assignHair(crv, hairSystem) follicleGrp = follicle.getParent() curveGrp = hcrv.getParent() ikhandle = pm.ikHandle(sj=simJointList[0], ee=simJointList[num - 1], c=hcrv, createCurve=0, solver='ikSplineSolver')[0] # Pour back for i in xrange(num): for skcl in skclList: if wgtJointList[i] in skcl.getInfluence(): skcl.addInfluence(selJointList[i], wt=0) inflList = skcl.getInfluence() isMaintainMax = skcl.attr('maintainMaxInfluences').get() maxInfl = skcl.attr('maxInfluences').get() isFullInfl = False if isMaintainMax and maxInfl == len(inflList): isFullInfl = True skcl.attr('maintainMaxInfluences').set(False) for infl in inflList: if infl == selJointList[i] or infl == wgtJointList[i]: infl.attr('lockInfluenceWeights').set(False) else: infl.attr('lockInfluenceWeights').set(True) for geo in skcl.getGeometry(): pm.skinPercent(skcl, geo.verts, nrm=True, tv=[wgtJointList[i], 0]) for infl in inflList: infl.attr('lockInfluenceWeights').set(False) attrList = [ wgtJointList[i].attr('message'), wgtJointList[i].attr('bindPose') ] for attr in attrList: for dst in pm.connectionInfo(attr, dfs=True): dst = pm.Attribute(dst) if dst.node().type() == 'dagPose': attr // dst if isFullInfl: skcl.attr('maintainMaxInfluences').set(True) pm.delete(wgtJointList) simGrp = pm.group(simJointList[0], follicle, n='sim_joints#') xformer = pm.group(simGrp, mixJointList[0], selJointList[0], n='%s_transformer#' % sel.nodeName()) hcrv.attr('scalePivot').set( selJointList[0].getTranslation(space='world')) hcrv.attr('rotatePivot').set( selJointList[0].getTranslation(space='world')) ctrlGrp.attr('scalePivot').set( selJointList[0].getTranslation(space='world')) ctrlGrp.attr('rotatePivot').set( selJointList[0].getTranslation(space='world')) simGrp.attr('scalePivot').set( selJointList[0].getTranslation(space='world')) simGrp.attr('rotatePivot').set( selJointList[0].getTranslation(space='world')) mixJointList[0].attr('template').set(1) hcrv.attr('template').set(1) hairSystem.attr('iterations').set(20) xformer.attr('scalePivot').set(axis.getTranslation()) xformer.attr('rotatePivot').set(axis.getTranslation()) wcnst = pm.parentConstraint(circle, hcrv, mo=True) lcnst = pm.parentConstraint(circle, xformer, mo=True) rev = pm.shadingNode('reverse', asUtility=True) circle.attr('space') >> wcnst.attr('%sW0' % wcnst.getTargetList()[0]) circle.attr('space') >> rev.attr('inputX') rev.attr('outputX') >> lcnst.attr('%sW0' % lcnst.getTargetList()[0]) pm.delete(follicleGrp, curveGrp, crv1d) pm.hide(simGrp) crvGrp = self.makeGroupIfNotExist('hairSystemOutputCurves', 0) ikGrp = self.makeGroupIfNotExist('hairSystemIKHandles', 1) nodesGrp = self.makeGroupIfNotExist('hairSystemNodes', 1) pm.parent(hcrv, crvGrp) pm.parent(ikhandle, ikGrp) if hairSystem.getParent() != nodesGrp: pm.parent(hairSystem, nodesGrp) if not pm.objExists(self.topName): topGrp = pm.group(n=self.topName, em=1) pm.parent(nodesGrp, ikGrp, crvGrp, xformer, axis, ctrlGrp, topGrp) else: pm.parent(xformer, axis, ctrlGrp, self.topName) topNode = pm.PyNode(self.topName) self.lockXformAttrs(topNode, False) self.lockXformAttrs(ctrlGrp, False) self.lockXformAttrs(crvGrp, False) self.lockXformAttrs(ikGrp, False) self.lockXformAttrs(nodesGrp, False) pm.select(topNode, r=1) self.selList.pop(0) windowName = 'hairSystem_Window' if pm.window(windowName, ex=1): pm.deleteUI(windowName) if self.selList: self.dialog(self.selList[0]) pm.displayInfo('"Make Joint Hair" has been successfully done.') return True
def mirror_pose( self, mirrorMode='behavior', *args ): try: selectedItem = pm.radioCollection( self.mirrorModeRC, q=True, select=True ) mirrorModeInUI = (pm.radioButton( selectedItem, q=True, label=True )).lower() except: pass objs = pm.ls( sl=True ) for obj in objs: name = self.findMirror( obj ) # find mirrored object's name if not name: continue mirrorMode = mirrorModeInUI mirrorModeAttrExists = pm.attributeQuery( 'mirrorMode', node=obj, exists=True ) if mirrorModeAttrExists: mirrorMode = obj.mirrorMode.get() # get object's attributes allAttrs = pm.listAttr( obj, keyable=True, unlocked=True ) userAttrs = pm.listAttr(obj, ud=True, unlocked=True) for attr in allAttrs: if pm.connectionInfo( pm.PyNode(name).attr(attr), isDestination=True ): pass if attr not in userAttrs:# match main attributes try: value = obj.attr(attr).get() if attr == 'visibility': # no need to mirror visibility pass elif attr=='translateX': # translate x is always reversed if mirrorMode=='behavior': pm.PyNode(name).attr(attr).set( -value ) elif mirrorMode=='orientation': pm.PyNode(name).attr(attr).set( -value ) elif mirrorMode=='hybrid': pm.PyNode(name).attr(attr).set( -value ) elif attr=='translateY': # translate x is always reversed if mirrorMode=='behavior': pm.PyNode(name).attr(attr).set( -value ) elif mirrorMode=='orientation': pm.PyNode(name).attr(attr).set( value ) elif mirrorMode=='hybrid': pm.PyNode(name).attr(attr).set( -value ) elif attr=='translateZ': # translate x is always reversed if mirrorMode=='behavior': pm.PyNode(name).attr(attr).set( -value ) elif mirrorMode=='orientation': pm.PyNode(name).attr(attr).set( value ) elif mirrorMode=='hybrid': pm.PyNode(name).attr(attr).set( -value ) elif attr=='rotateX': if mirrorMode=='behavior': pm.PyNode(name).attr(attr).set( value ) elif mirrorMode=='orientation': pm.PyNode(name).attr(attr).set( value ) elif mirrorMode=='hybrid': pm.PyNode(name).attr(attr).set( -value ) elif attr=='rotateY': if mirrorMode=='behavior': pm.PyNode(name).attr(attr).set( value ) elif mirrorMode=='orientation': pm.PyNode(name).attr(attr).set( -value ) elif mirrorMode=='hybrid': pm.PyNode(name).attr(attr).set( value ) elif attr=='rotateZ': if mirrorMode=='behavior': pm.PyNode(name).attr(attr).set( value ) elif mirrorMode=='orientation': pm.PyNode(name).attr(attr).set( -value ) elif mirrorMode=='hybrid': pm.PyNode(name).attr(attr).set( -value ) else: pm.PyNode(name).attr(attr).set( value ) except: pm.error('ehm_tools...mirrorPose: Mirror failed on main attributes!') for userAttr in userAttrs:# find and match user defined attributes try: value = obj.attr(userAttr).get() pm.PyNode(name).attr(userAttr).set( value ) except: pm.error('ehm_tools...mirrorPose: Mirror failed on user defined attributes!')
def flip_pose( self, mirrorMode=True, *args ): try: selectedItem = pm.radioCollection( self.mirrorModeRC, q=True, select=True ) mirrorModeInUI = (pm.radioButton( selectedItem, q=True, label=True )).lower() except: pass objs = pm.ls( sl=True ) flippedObjs = [] # list of objects already flipped for obj in objs: mirrorMode = mirrorModeInUI mirrorModeAttrExists = pm.attributeQuery( 'mirrorMode', node=obj, exists=True ) if mirrorModeAttrExists: mirrorMode = obj.mirrorMode.get() name = self.findMirror( obj ) # find mirrored object's name if name in flippedObjs: # prevent object to get flipped twice continue flippedObjs.append( obj ) # get object's attributes allAttrs = pm.listAttr( obj, keyable=True, unlocked=True ) userAttrs = pm.listAttr(obj, ud=True, unlocked=True) if not name: # if mirror not found go to next object # 1. create 3 locators representing Position, aimVector and upVector pos = self.createChildLoc( obj ) aim = self.createChildLoc( obj ) upv = self.createChildLoc( obj ) # 2. get the flip plane from our control object, default is YZ. place aim and up vectors accordingly try: flipPlane = obj.mirrorPlane.get() except: flipPlane = 'YZ' if flipPlane == 'YZ': aim.translateZ.set(1) upv.translateY.set(1) elif flipPlane == 'XZ': aim.translateX.set(1) upv.translateZ.set(1) elif flipPlane == 'XY': aim.translateX.set(1) upv.translateY.set(1) # 3. parent locators under control's parent. They should be in the same group as our control object we want to flip try: controlParent = obj.getParent() except: controlParent = None if controlParent: pm.parent( pos, controlParent ) pm.parent( aim, controlParent ) pm.parent( upv, controlParent ) # 4. group all locators and scale the group according to our flip plane grp = pm.group( pos, aim, upv ) pm.xform( grp, os=True, piv=(0,0,0) ) if flipPlane == 'YZ': grp.scaleX.set(-1) elif flipPlane == 'XZ': grp.scaleY.set(-1) elif flipPlane == 'XY': grp.scaleZ.set(-1) # 5. create point and aim constraints to achieve the pose on a null object and apply the values to our control result = pm.group( empty=True ) result.rotateOrder.set( obj.rotateOrder.get() ) if controlParent: pm.parent( result, controlParent ) pm.pointConstraint( pos, result ) if flipPlane == 'YZ': pm.aimConstraint( aim, result, aimVector=[0,0,1], upVector=[0,1,0], worldUpType="object", worldUpObject=upv ) elif flipPlane == 'XZ': pm.aimConstraint( aim, result, aimVector=[1,0,0], upVector=[0,0,1], worldUpType="object", worldUpObject=upv ) elif flipPlane == 'XY': pm.aimConstraint( aim, result, aimVector=[1,0,0], upVector=[0,1,0], worldUpType="object", worldUpObject=upv ) result.scale.set( obj.scale.get() ) # get object's attributes allAttrs = pm.listAttr( obj, keyable=True, unlocked=True ) userAttrs = pm.listAttr(obj, ud=True, unlocked=True) for attr in allAttrs: try: obj.attr(attr).set( result.attr(attr).get() ) except: continue # 6. delete extra nodes pm.delete( grp, result ) continue for attr in allAttrs: if pm.connectionInfo( pm.PyNode(name).attr(attr), isDestination=True ): pass if attr not in userAttrs:# match main attributes try: otherValue = pm.PyNode(name).attr(attr).get() value = obj.attr(attr).get() if attr == 'visibility': # no need to mirror visibility pass elif attr=='translateX': # translate x is always reversed if mirrorMode=='behavior': pm.PyNode(name).attr(attr).set( -value ) obj.attr(attr).set( -otherValue ) elif mirrorMode=='orientation': pm.PyNode(name).attr(attr).set( -value ) obj.attr(attr).set( -otherValue ) elif mirrorMode=='hybrid': pm.PyNode(name).attr(attr).set( -value ) obj.attr(attr).set( -otherValue ) elif attr=='translateY': # translate x is always reversed if mirrorMode=='behavior': pm.PyNode(name).attr(attr).set( -value ) obj.attr(attr).set( -otherValue ) elif mirrorMode=='orientation': pm.PyNode(name).attr(attr).set( value ) obj.attr(attr).set( otherValue ) elif mirrorMode=='hybrid': pm.PyNode(name).attr(attr).set( -value ) obj.attr(attr).set( -otherValue ) elif attr=='translateZ': # translate x is always reversed if mirrorMode=='behavior': pm.PyNode(name).attr(attr).set( -value ) obj.attr(attr).set( -otherValue ) elif mirrorMode=='orientation': pm.PyNode(name).attr(attr).set( value ) obj.attr(attr).set( otherValue ) elif mirrorMode=='hybrid': pm.PyNode(name).attr(attr).set( -value ) obj.attr(attr).set( -otherValue ) elif attr=='rotateX': if mirrorMode=='behavior': pm.PyNode(name).attr(attr).set( value ) obj.attr(attr).set( otherValue ) elif mirrorMode=='orientation': pm.PyNode(name).attr(attr).set( value ) obj.attr(attr).set( otherValue ) elif mirrorMode=='hybrid': pm.PyNode(name).attr(attr).set( -value ) obj.attr(attr).set( -otherValue ) elif attr=='rotateY': if mirrorMode=='behavior': pm.PyNode(name).attr(attr).set( value ) obj.attr(attr).set( otherValue ) elif mirrorMode=='orientation': pm.PyNode(name).attr(attr).set( -value ) obj.attr(attr).set( -otherValue ) elif mirrorMode=='hybrid': pm.PyNode(name).attr(attr).set( value ) obj.attr(attr).set( otherValue ) elif attr=='rotateZ': if mirrorMode=='behavior': pm.PyNode(name).attr(attr).set( value ) obj.attr(attr).set( otherValue ) elif mirrorMode=='orientation': pm.PyNode(name).attr(attr).set( -value ) obj.attr(attr).set( -otherValue ) elif mirrorMode=='hybrid': pm.PyNode(name).attr(attr).set( -value ) obj.attr(attr).set( -otherValue ) else: pm.PyNode(name).attr(attr).set( value ) obj.attr(attr).set( otherValue ) except: pm.error('ehm_tools...mirrorPose: Flip failed on main attributes!') else:# match user defined attributes try: otherValue = pm.PyNode(name).attr(attr).get() value = obj.attr(attr).get() pm.PyNode(name).attr(attr).set( value ) obj.attr(attr).set( otherValue ) except: pm.error('ehm_tools...mirrorPose: Flip failed on user defined attributes!') pm.select( objs )
def mixTwoShaders(shadingMixNode, alSurfaceMixed, folder_to_save): buf = 0 blendToReturn = [] if pm.connectionInfo(shadingMixNode.name() + '.mix', id = True): connectedMix = 1 maskToMix = pm.listConnections(shadingMixNode.name() + '.mix', p=True)[0] else: connectedMix = 0 toMixNum = pm.getAttr(shadingMixNode.name() + '.mix') for shaderToMix in alSurfaceMixed: print shaderToMix # add .txt file with information of parametrs in shader fileName = os.path.join(folder_to_save, shaderToMix.name() + '.txt') preferencesFile = open(fileName, 'w+') for i in pm.listAttr(shaderToMix): value = pm.getAttr(shaderToMix.name() + '.' + i) try: preferencesFile.write(i) preferencesFile.write(" " + str(value)) except: pass preferencesFile.write("\n") preferencesFile.close() listConnected = pm.listConnections(shaderToMix, p=True, d=False) for plug in listConnected: if buf == 0: AOV_name = plug.outputs(p=True)[0].name().split('.')[1] if AOV_name == 'diffuseColor': AOV_name = 'baseColor' AOV_name = ''.join(i for i in AOV_name if not i.isdigit()) if plug.type() == 'float3': name = 'blendColors_' + AOV_name + '_' + shadingMixNode.name() +'_AOVS' nodeBlend = pm.createNode( 'blendColors' , n=name) nodeBlendAttr = nodeBlend.name() + '.color2' nodeBlendAttrOut = nodeBlend.name() + '.output' pm.connectAttr(plug, nodeBlendAttr) else: aiUserData = pm.createNode( 'aiUserDataColor') R = aiUserData.name() + '.defaultValueR' G = aiUserData.name() + '.defaultValueG' B = aiUserData.name() + '.defaultValueB' pm.connectAttr(plug, R) pm.connectAttr(plug, G) pm.connectAttr(plug, B) plugUserData = aiUserData.name() + '.outColor' name = 'blendColors_' + AOV_name + '_' + shadingMixNode.name() +'_AOVS' nodeBlend = pm.createNode( 'blendColors' , n=name) nodeBlendAttr = nodeBlend.name() + '.color2' nodeBlendAttrOut = nodeBlend.name() + '.output' pm.connectAttr(plugUserData, nodeBlendAttr) if pm.getAttr(shadingMixNode.name() + '.mix') == 0: if (not connectedMix): pm.setAttr(nodeBlend + '.blender', toMixNum) else: pm.connectAttr(maskToMix.name(), nodeBlend + '.blender') blendToReturn.append(nodeBlend) elif (buf == 1): AOV_name = plug.outputs(p=True)[0].name().split('.')[1] if AOV_name == 'diffuseColor': AOV_name = 'baseColor' AOV_name = ''.join(i for i in AOV_name if not i.isdigit()) if not (pm.objExists('blendColors_' + AOV_name + '_' + shadingMixNode.name() +'_AOVS')): pass # ADD LATER else: if plug.type() == 'float3': nodeBlendAttr = 'blendColors_' + AOV_name + '_' + shadingMixNode.name() +'_AOVS' + '.color1' pm.connectAttr(plug, nodeBlendAttr) else: aiUserData = pm.createNode( 'aiUserDataColor') R = aiUserData.name() + '.defaultValueR' G = aiUserData.name() + '.defaultValueG' B = aiUserData.name() + '.defaultValueB' pm.connectAttr(plug, R) pm.connectAttr(plug, G) pm.connectAttr(plug, B) plugUserData = aiUserData.name() + '.outColor' nodeBlendAttr = 'blendColors_' + AOV_name + '_' + shadingMixNode.name() +'_AOVS' + '.color1' pm.connectAttr(plugUserData, nodeBlendAttr) buf += 1 for blendNode in blendToReturn: nameBlendAttr = blendNode.name() + '.output' pasName = blendNode.name().split('_')[1] AOV_name = pasName nametotest = "aiAOV_" + AOV_name if not (nametotest in listOfAovsEnabled): print 'ERROR TO PASS ' + AOV_name else: pm.setAttr("aiAOV_" + AOV_name + ".enabled", 1) if pm.getAttr(nameBlendAttr, type=True) == 'float3': nameBlendAttr = blendNode.name() + '.color1' print nameBlendAttr, pm.listConnections(nameBlendAttr) if pm.listConnections(nameBlendAttr): pass else: if pasName == 'baseColor': pasName = 'diffuseColor' NpasName = pasName.replace('specular', 'specular1') pasName = NpasName nodeAttr = alSurfaceMixed[1] + '.' + pasName parm = pm.getAttr(nodeAttr) if type(parm).__name__ == 'float': parmN = (parm, parm, parm) parm = parmN nodeConst = pm.createNode( 'colorConstant') nodeConstAttr = nodeConst + '.inColor' pm.setAttr(nodeConstAttr, parm) nodeConstAttr = nodeConst + '.outColor' nodeBlendAttr = blendNode + '.color1' #print nodeBlendAttr pm.connectAttr(nodeConstAttr, nodeBlendAttr) else: pass return blendToReturn
def mixBlendAndShader(listofBlends, shadingMixNode): alSurfaceMixed = [] for i in shadingMixNode.listConnections(): if i.nodeType() == 'alSurface': alSurfaceMixed.append(i) blendToReturn = [] buf = 0 if pm.connectionInfo(shadingMixNode.name() + '.mix', id = True): connectedMix = 1 maskToMix = pm.listConnections(shadingMixNode.name() + '.mix', p=True)[0] else: connectedMix = 0 toMixNum = pm.getAttr(shadingMixNode.name() + '.mix') for blendToMix in listofBlends: AOV_name = blendToMix.name().split('_')[1] outputBlend = blendToMix.name() + '.output' if pm.getAttr(outputBlend, typ = True) == "float3": # VECTOR name = 'blendColors_' + AOV_name + '_' + shadingMixNode.name() +'_AOVS' nodeBlend = pm.createNode( 'blendColors' , n=name) nodeBlendAttr = nodeBlend.name() + '.color1' nodeBlendAttrOut = nodeBlend.name() + '.output' else: # FLOAT name = 'blendTwoAttr_' + AOV_name + '_' + shadingMixNode.name() +'_AOVS' nodeBlend = pm.createNode( 'blendTwoAttr' , n=name) nodeBlendAttr = nodeBlend.name() + '.input[0]' nodeBlendAttrOut = nodeBlend.name() + '.output' pm.connectAttr(outputBlend, nodeBlendAttr) if pm.getAttr(shadingMixNode.name() + '.mix') == 0: if (not connectedMix): if pm.getAttr(outputBlend, typ = True) == "float3": pm.setAttr(nodeBlend + '.blender', toMixNum) else: pm.setAttr(nodeBlend + '.attributesBlender', toMixNum) else: if pm.getAttr(outputBlend, typ = True) == "float3": pm.connectAttr(maskToMix.name(), nodeBlend + '.blender') else: pm.connectAttr(maskToMix.name(), nodeBlend + '.attributesBlender') blendToReturn.append(nodeBlend) for i in blendToReturn: pasName = i.name().split('_')[1] if pasName == 'baseColor': pasName = 'diffuseColor' NpasName = pasName.replace('specular', 'specular1') pasName = NpasName nodeAttr = alSurfaceMixed[0] + '.' + pasName if pm.listConnections(nodeAttr): plug = pm.listConnections(nodeAttr, p=True)[0] if plug.type() == 'float3': nodeBlendAttr = i + '.color2' else: nodeBlendAttr = i + '.input[1]' pm.connectAttr(plug, nodeBlendAttr) else: parm = pm.getAttr(nodeAttr) if type(parm).__name__ == 'float': nodeConst = pm.createNode( 'floatConstant') nodeConstAttr = nodeConst + '.inFloat' pm.setAttr(nodeConstAttr, parm) nodeConstAttr = nodeConst + '.outFloat' nodeBlendAttr = i + '.input[1]' pm.connectAttr(nodeConstAttr, nodeBlendAttr) else: nodeConst = pm.createNode( 'colorConstant') nodeConstAttr = nodeConst + '.inColor' pm.setAttr(nodeConstAttr, parm) nodeConstAttr = nodeConst + '.outColor' nodeBlendAttr = i + '.color2' pm.connectAttr(nodeConstAttr, nodeBlendAttr) return blendToReturn
def is_exact_destination(pymel_attribute): result = pm.connectionInfo(pymel_attribute, isExactDestination=True) return result
def buildConnections(self): #reveice info from incoming package if pm.objExists(self.metaMain) == 1: print '' print 'Package from (' + self.metaMain + ') has been received' pm.select(self.metaMain) headQuarter = pm.selected()[0] mainDestinations = [] moduleGrp = pm.connectionInfo(headQuarter.moduleGrp, destinationFromSource=True) for tempDestination in moduleGrp: destination = tempDestination.split('.') mainDestinations.append(destination[0]) #to the main hierachy for grp in mainDestinations: destnation = grp.split('_') if destnation[1] == 'CC': CC = grp elif destnation[1] == 'SKL': SKL = grp elif destnation[1] == 'IK': IK = grp elif destnation[1] == 'LOC': LOC = grp elif destnation[1] == 'XTR': XTR = grp elif destnation[1] == 'GUD': GUD = grp elif destnation[1] == 'GEO': GEO = grp elif destnation[1] == 'ALL': ALL = grp elif destnation[1] == 'XTR': XTR = grp elif destnation[1] == 'TRS': TRS = grp elif destnation[1] == 'PP': PP = grp self.bodyCtrl.controlGrp.setParent(CC) self.guideGrp.setParent(GUD) self.spineIkGrp.setParent(IK) self.spineIkGrp.inheritsTransform.set(0) print '' print 'Info from (' + self.meta + ') has been integrate, ready for next Module' print '' else: OpenMaya.MGlobal.displayError('Target :' + self.metaMain + ' is NOT exist') #create package send for next part #template: #metaUtils.addToMeta(self.meta,'attr', objs) metaUtils.addToMeta(self.meta,'controls',[self.bodyCtrl.control] + [spineCc for spineCc in self.spineCc]) metaUtils.addToMeta(self.meta,'transGrp',[self.chestGrp]) metaUtils.addToMeta(self.meta,'skinJoints',[joint for joint in self.ikJj])
def miaMaterialX_to_VRayMtl( miaX ): ''' # 하다 말았음 나중에 손볼것! # # mia_material_x --> VRayMtl # for miax in pm.ls( type=['mia_material_x', 'mia_material_x_passes'] ): # mia_material_x --> VRayMtl vray = miaMaterialX_To_VRayMtl( miax ) # 오브젝트에 연결 assignMaterialToObject( material=vray, objects=getObjects_fromMaterial( miax ) ) ''' # 재질이 mia_material_x 나 mie_material_x_passes 인지 확인 if not (pm.nodeType(miaX) == "mia_material_x_passes") or (pm.nodeType(miaX) == "mia_material_x"): return # 비교에 사용할 attribute 목록 작성, # miaX attribute 앞, VRay attribute 뒤 attrList = [ ("diffuse", "color"), ("diffuse_weight", "diffuseColorAmount"), ("diffuse_roughness", "roughnessAmount"), ("refl_color", "reflectionColor"), ("reflectivity", "reflectionColorAmount"), ("refl_gloss", "reflectionGlossiness"), ("refl_gloss_samples", "reflectionSubdivs"), ("refl_falloff_on", "reflectionDimDistanceOn"), ("refl_falloff_dist", "reflectionDimDistance"), ("refl_depth", "reflectionsMaxDepth"), ("refr_ior", "refractionIOR"), ("refr_color", "refractionColor"), ("transparency", "refractionColorAmount"), ("refr_gloss", "refractionGlossiness"), ("refr_gloss_samples", "refractionSubdivs"), ("thin_walled", "refractionIOR") ] # VRayMtl 생성 vRayMtl = createVRayMtl()[0] # 맵이 연결되어 있으면 연결, # 그렇지 않으면 값을 조정 (value/color) for miaAttr, vrayAttr in attrList: if pm.connectionInfo( miaX +"."+ miaAttr, id=True): outAttr = pm.listConnections( miaX+"."+miaAttr, p=True)[0] inAttr = vRayMtl + "." + vrayAttr pm.connectAttr( outAttr, inAttr ) else: outAttr = pm.getAttr( miaX + "." + miaAttr ) inAttr = vRayMtl + "." + vrayAttr pm.setAttr(inAttr, outAttr) if pm.getAttr(miaX + ".thin_walled") == 1: pm.setAttr(vRayMtl + ".refractionIOR", 1) # 범프가 존재하면 # 연결하고 multiplier를 조정 if pm.connectionInfo(miaX + ".standard_bump", id=True): # 연결 outAttr = pm.listConnections(miaX + ".standard_bump")[0] outValue = pm.listConnections(outAttr + ".bumpValue", p=True)[0] inValue = vRayMtl + "." + 'bumpMap' pm.connectAttr(outValue, inValue+"R") pm.connectAttr(outValue, inValue+"G") pm.connectAttr(outValue, inValue+"B") # 값 적용 outDepth = pm.getAttr(outAttr + ".bumpDepth") inDepth = vRayMtl + "." + 'bumpMult' pm.setAttr(inDepth, outDepth) return (vRayMtl)
def mip_move_image_plane(imagePlane = '', *args, **kwargs): if imagePlane: connections = pm.connectionInfo(imagePlane+'.message', destinationFromSource=True) cam = 'none' for item in connections: if item.split('Shape.')[0] == 'front': cam = 'front' if item.split('Shape.')[0] == 'side': cam = 'side' if item.split('Shape.')[0] == 'top': cam = 'top' if cam != 'none': curve = pm.curve(per=True, d=1, p=[(0.5,0,0.5), (0.5,0,-0.5), (-0.5,0,-0.5), (-0.5,0,0.5), (0.5,0,0.5)], k=[0,1,2,3,4]) if cam == 'front': curve.setRotation((90,0,0)) if cam == 'top': curve.setRotation((0,0,0)) if cam == 'side': curve.setRotation((90,90,0)) pm.setAttr(curve+'.rx', lock=True, keyable=False, channelBox=False) pm.setAttr(curve+'.ry', lock=True, keyable=False, channelBox=False) pm.setAttr(curve+'.rz', lock=True, keyable=False, channelBox=False) pm.setAttr(curve+'.sy', lock=True, keyable=False, channelBox=False) filename = pm.getAttr(imagePlane+'.imageName').split('/')[-1].split('.')[0] pm.rename(curve, 'Mover_'+filename) pm.expression(name=imagePlane+'_expression', s='{0}.displayMode = {1}.visibility * 3'.format(imagePlane, curve)) ratio = 1.0 coverageX = float(pm.getAttr(imagePlane+'.coverageX')) coverageY = float(pm.getAttr(imagePlane+'.coverageY')) size = 1.0 sizeW = float(pm.getAttr(imagePlane+'.width')) sizeH = float(pm.getAttr(imagePlane+'.height')) if sizeW>sizeH: size = sizeW else: size = sizeH if coverageX > coverageY: ratio = coverageX/coverageY x = size z = size/ratio curve.setScale((x,1,z)) pm.select(curve.cv[0:3]) pm.scale(1.2,1+(.2/ratio),1) else: ratio = coverageY/coverageX x = size/ratio z = size curve.setScale((x,1,z)) pm.select(curve.cv[0:3]) pm.scale(1+(.2/ratio),1.2,1) if pm.mel.getApplicationVersionAsFloat() > 2012: pm.connectAttr(curve.translate, imagePlane+'.imageCenter') else: pm.connectAttr(curve.translate, imagePlane+'.center') pm.connectAttr(curve.scaleX, imagePlane+'.width') pm.connectAttr(curve.scaleZ, imagePlane+'.height') pm.select(curve, replace=True) else: pm.warning('not using the front, side or top camera !!!')
pm.select(hi=True) nurbsSurf = pm.ls(sl=1, type='nurbsSurface')[0] #edit surface precision pm.setAttr(nurbsSurf + '.curvePrecision', 14) #if auto mode is On look for the biggest len with scale values if auto == True: scaleX = nurbsSurf.getParent().scaleX.get() scaleZ = nurbsSurf.getParent().scaleZ.get() if scaleX > scaleZ: UVvalue = 'U' if scaleX < scaleZ: UVvalue = 'V' #check if you can use the script to use the history on the orig shape create = pm.connectionInfo(nurbsSurf + '.create', sfd=True) if create == '' or create == []: history = False elif pm.objectType(create) == 'makeNurbPlane': create = create.split('.')[0] create = pm.PyNode(create) else: history = False #if history set the attribute of the nurbs with script if history == True: if UVvalue == 'U': pm.setAttr(create + '.patchesU', numP) pm.setAttr(create + '.patchesV', 1) if UVvalue == 'V': pm.setAttr(create + '.patchesV', numP)
def ar_ikFootRollReOrient(ctl, ctlOffGrp, orientSample, rotateAxis='.rz', reverseConnections=False): """ @ reorient ik roll controllers using re parenting. Args: ctl (str): controller. ctlOffGrp (str): controller offset group. orientSample (str): orient sample. rotateAxis (str): rotate axis with "." in prefix. reverseConnections (bool): bool. Returns: bool. """ ctl = pm.PyNode(ctl) ctlOffGrp = pm.PyNode(ctlOffGrp) orientSample = pm.PyNode(orientSample) # offsetGroup changes. pm.select(cl=True) jt = pm.joint(n=ctlOffGrp[:-2] + 'Extra' + ctlOffGrp[-2:]) pm.select(cl=True) jtTemp = pm.joint(n=ctlOffGrp + 'ConnTemp') pm.delete(pm.parentConstraint(orientSample, jt)) parentGrp = ctlOffGrp.getParent() pm.parent(jt, parentGrp) pm.makeIdentity(jt, apply=True, t=1, r=1, s=1, n=0, pn=1) # query connection. connections = pm.connectionInfo(ctlOffGrp.rx, sfd=True) # attach connection. pm.connectAttr(connections, jtTemp + rotateAxis) pm.disconnectAttr(connections, ctlOffGrp.rx) # parent. children = ctlOffGrp.getChildren() pm.parent(children, jt) jtNewName = str(ctlOffGrp) pm.delete(ctlOffGrp) jt.rename(jtNewName) if reverseConnections: mdn = pm.createNode('multiplyDivide', n='multiplyDivideReverse' + jt) mdn.input2X.set(-1) pm.connectAttr(connections, mdn.input1X) mdn.outputX.connect(jt + rotateAxis) connName = pm.PyNode(connections.split('.')[0]) if type(connName) == pm.nodetypes.UnitConversion: connName.conversionFactor.set(1) else: pm.connectAttr(connections, jt + rotateAxis) # delete tempJoint. pm.delete(jtTemp) # rotate controller group. children = ctl.getChildren() filtChildren = [] for each in children: print each if type(each) == pm.nodetypes.NurbsCurve: pass elif each.rx.isConnected() or each.ry.isConnected() or each.rz.isConnected(): pm.select(cl=True) newGroup = pm.createNode('transform', n=each + '_Freezed', ss=True) pm.delete(pm.parentConstraint(each, newGroup)) pm.parent(newGroup, ctl) pm.parent(each, newGroup) filtChildren.append(newGroup) else: filtChildren.append(each) pm.parent(filtChildren, w=True) offChild = jt.getChildren() for each in offChild: each.r.set([0, 0, 0]) pm.parent(filtChildren, ctl) return True
def getIntermediateObj(obj): geos = obj.getShapes() for geo in geos: if geo.isIntermediate() and pm.connectionInfo(geo + '.worldMesh[0]', isSource=True): return geo
def mip_move_image_plane(imagePlane='', *args, **kwargs): if imagePlane: connections = pm.connectionInfo(imagePlane + '.message', destinationFromSource=True) cam = 'none' for item in connections: if item.split('Shape.')[0] == 'front': cam = 'front' if item.split('Shape.')[0] == 'side': cam = 'side' if item.split('Shape.')[0] == 'top': cam = 'top' if cam != 'none': curve = pm.curve(per=True, d=1, p=[(0.5, 0, 0.5), (0.5, 0, -0.5), (-0.5, 0, -0.5), (-0.5, 0, 0.5), (0.5, 0, 0.5)], k=[0, 1, 2, 3, 4]) if cam == 'front': curve.setRotation((90, 0, 0)) if cam == 'top': curve.setRotation((0, 0, 0)) if cam == 'side': curve.setRotation((90, 90, 0)) pm.setAttr(curve + '.rx', lock=True, keyable=False, channelBox=False) pm.setAttr(curve + '.ry', lock=True, keyable=False, channelBox=False) pm.setAttr(curve + '.rz', lock=True, keyable=False, channelBox=False) pm.setAttr(curve + '.sy', lock=True, keyable=False, channelBox=False) filename = pm.getAttr(imagePlane + '.imageName').split('/')[-1].split('.')[0] pm.rename(curve, 'Mover_' + filename) pm.expression(name=imagePlane + '_expression', s='{0}.displayMode = {1}.visibility * 3'.format( imagePlane, curve)) ratio = 1.0 coverageX = float(pm.getAttr(imagePlane + '.coverageX')) coverageY = float(pm.getAttr(imagePlane + '.coverageY')) size = 1.0 sizeW = float(pm.getAttr(imagePlane + '.width')) sizeH = float(pm.getAttr(imagePlane + '.height')) if sizeW > sizeH: size = sizeW else: size = sizeH if coverageX > coverageY: ratio = coverageX / coverageY x = size z = size / ratio curve.setScale((x, 1, z)) pm.select(curve.cv[0:3]) pm.scale(1.2, 1 + (.2 / ratio), 1) else: ratio = coverageY / coverageX x = size / ratio z = size curve.setScale((x, 1, z)) pm.select(curve.cv[0:3]) pm.scale(1 + (.2 / ratio), 1.2, 1) if pm.mel.getApplicationVersionAsFloat() > 2012: pm.connectAttr(curve.translate, imagePlane + '.imageCenter') else: pm.connectAttr(curve.translate, imagePlane + '.center') pm.connectAttr(curve.scaleX, imagePlane + '.width') pm.connectAttr(curve.scaleZ, imagePlane + '.height') pm.select(curve, replace=True) else: pm.warning('not using the front, side or top camera !!!')