def matchIkToFk(ikControl, ikPole, offset=100.0, msgAttr='fkjoints', autoKey=True):
    """
    Matches ikControl and ikPole Vector control to match the current pose of underlying
    fk duplicate joint chains
    Finds the fk joints using a previously created message connection to the attribute msgAttr
    """

    fkJoints = pmc.listConnections('{0}.{1}'.format(ikControl, msgAttr),
                                   destination=False, source=True)

    attr = pmc.listConnections('{0}.ikfk'.format(ikControl), destination=False,
                               source=True, plugs=True, scn=True)[0]
    switchControl = attr.node()
    switchAttr = attr.name(includeNode=False)

    frameBeforeCurrent = pmc.currentTime(q=True) - 1
    if autoKey:
        pmc.setKeyframe(switchControl, attribute=switchAttr, time=frameBeforeCurrent,
                        value=1, outTangentType='step')
        pmc.setKeyframe([ikControl, ikPole], time=frameBeforeCurrent, outTangentType='step')

        pmc.setKeyframe(switchControl, attribute=switchAttr, value=0, outTangentType='step')

    alignObjects(ikControl, fkJoints[-1])
    loc = getPoleVectorPosition(fkJoints, offset, curveGuide=False)
    alignObjects(ikPole, loc, position=True, rotation=False)
    pmc.delete(loc)

    if autoKey:
        pmc.setKeyframe([ikControl, ikPole], time=frameBeforeCurrent)

    pmc.headsUpMessage('BAMF!')
Пример #2
0
 def build_twist_deform(self, *args):
     """ builds a curve with 3 cv's controled by clusters
     Args:
         None
     Returns (None)
     """
     surf_wireShp_name = self.flexiPlaneNameField.getText() + '_flexiPlane_wire_bShp_SURF'
     wireNode_name = self.flexiPlaneNameField.getText() + '_flexiPlane_bShp_wireNode_SURF'
     twistNode_name = self.flexiPlaneNameField.getText() + '_flexiPlane_bShp_twistNode_SURF'
     twistHandle_name = self.flexiPlaneNameField.getText() + '_flexiPlane_twist_Handle'
     surf_bShpGRP_name = self.flexiPlaneNameField.getText() + '_flexiPlane_bShp_GRP'
     
     pm.select( surf_wireShp_name, r = True )
     twist_deformer = mel.eval("nonLinear -type twist -lowBound -1 -highBound 1 -startAngle 0 -endAngle 0;")[0]
     
     twistSurf_inputList = pm.listConnections( surf_wireShp_name + 'Shape' )
     pm.rename( twistSurf_inputList [-3] , twistNode_name )
     
     twistNode_inputList = pm.listConnections( twistNode_name )
     pm.rename( twistNode_inputList [-1] , twistHandle_name )
     pm.setAttr( twistHandle_name + '.rotateZ', 90 )
     pm.reorderDeformers( wireNode_name, twistNode_name, surf_wireShp_name )
     pm.parent( twistHandle_name, surf_bShpGRP_name )
     
     pm.select( cl = True )
Пример #3
0
    def bdBuildSplineSolverScale(self,condition):
        
        print 'asdas'
        self.splineCurve = pm.listConnections(self.ikSpline, type = 'nurbsCurve')[0]

        effector = pm.listConnections(self.ikSpline ,source=True, type='ikEffector')[0]
        endJoint = pm.listConnections(effector,source=True, type='joint')[0]
        startJointChild = pm.listRelatives(self.startJoint,c=True, type='joint')[0]
        self.jointChain = []
        self.jointChain.append(self.startJoint)
        self.jointChain.append(startJointChild)
        while startJointChild.name() != endJoint.name():
            startJointChild = pm.listRelatives(startJointChild,c=True, type='joint')[0]
            self.jointChain.append(startJointChild)
        
        self.splineCurveScl = pm.duplicate(self.splineCurve,name = self.splineCurve.name().replace('crv','crv_scl'))
        strArclenSCL = pm.arclen(self.splineCurveScl,ch=True)
        strArclenCRV = pm.arclen(self.splineCurve,ch=True)
        arclenSCL = pm.ls( strArclenSCL ) [0]
        arclenCRV = pm.ls( strArclenCRV ) [0]
        arclenSCL.rename(self.splineCurveScl[0].name() + '_length')
        arclenCRV.rename(self.splineCurve.name() + '_length')
        
        mdScaleFactor = pm.createNode('multiplyDivide', name = self.splineCurve.name().replace('crv','crv_scaleFactor_md'))
        arclenCRV.arcLength.connect(mdScaleFactor.input1X)
        arclenSCL.arcLength.connect(mdScaleFactor.input2X)
        mdScaleFactor.operation.set(2)

        for jnt in self.jointChain:
            mdScaleFactor.outputX.connect(jnt.scaleX) 
Пример #4
0
    def assignToSelected(self, layerIndex, channelIndex):
        for obj in pm.selected():
            materialChannelList = [".diffuse", ".diffuse_weight", ".transparency", ".reflectivity", ".refl_gloss",
                                   ".cutout_opacity", ".bump", ".normal"]
            shapeNode = pm.listRelatives(obj, c=True, s=True)
            shadingGrp = pm.listConnections(shapeNode, type="shadingEngine")[0]
            mat = list(set(
                pm.listConnections(shadingGrp, type=['mia_material_x', 'mia_material_x_passes', 'lambert', 'phong'])))[
                0]
            try:
                currentItem = self.layeredTextureTreeModel.itemFromIndex(layerIndex[0]).node
            except:
                pm.cmds.warning("Please select a texture from the list.")
            try:
                if channelIndex < 6:
                    outAttr = ".outColor"
                    if channelIndex != 0:
                        outAttr = ".outAlpha"

                    currentItemOutColor = currentItem + outAttr
                    materialInput = mat + materialChannelList[channelIndex]
                    pm.connectAttr(currentItemOutColor, materialInput, f=True)
                elif channelIndex == 6:
                    createBump(currentItem, mat)
                else:
                    createBump(currentItem, mat, normal=True)
            except:
                pm.cmds.warning("Could not connect materials to " + obj)
Пример #5
0
def getShader():
    # get shapes of selection:
    shapesInSel = py.ls(dag=1,o=1,s=1,sl=1)
    # get shading groups from shapes:
    shadingGrps = py.listConnections(shapesInSel,type='shadingEngine')
    # get the shaders:
    shader = py.ls(py.listConnections(shadingGrps),materials=1)
    return shader[0] 
	def illumDefaultCommand(self, *args):
		connections = pm.listConnections('defaultLightSet', d=False, s=True)
		if self.illDefault_box.getValue() == 0 and self.lightTransform in connections:
			defaultSet = pm.listConnections(self.lightTransform, d=True, s=False, plugs=True)[0]
			pm.disconnectAttr(self.lightTransform+'.instObjGroups[0]', defaultSet)

		elif self.illDefault_box.getValue() == 1:
			pm.connectAttr(self.lightTransform+'.instObjGroups',  'defaultLightSet.dagSetMembers', nextAvailable=True)
Пример #7
0
 def shader_getShader(self, arg):
     # get shapes of selection:
     shape = pm.ls(arg, dag=1,o=1,s=1)
     # get shading groups from shapes:
     shadingGrp = pm.listConnections(shape,type='shadingEngine')
     # get the shaders:
     shader = pm.ls(pm.listConnections(shadingGrp),materials=1) 
     return shader
Пример #8
0
    def bdBuildRPSolverScale(self,condition):
        print 'RP Solver'
        
        #self.splineCurve = pm.listConnections(self.ikSpline, type = 'nurbsCurve')[0]
        pm.select(cl=True)
        ikGrp = pm.group(n=self.ikSpline.name() + '_GRP')
        ikParent = self.ikSpline.getParent()
        ikPos = self.ikSpline.getTranslation(space= 'world')
        ikGrp.setTranslation(ikPos)
        pm.parent(ikGrp,ikParent)
        pm.parent(self.ikSpline,ikGrp)
        

        sclJnt = pm.duplicate(self.startJoint, parentOnly = True , name = self.startJoint.name().replace('JNT','SCL'))[0]
        effector = pm.listConnections(self.ikSpline ,source=True, type='ikEffector')[0]
        endJoint = pm.listConnections(effector,source=True, type='joint')[0]
        startJointChild = pm.listRelatives(self.startJoint,c=True, type='joint')[0]
        self.jointChain = []
        self.jointChain.append(self.startJoint)
        self.jointChain.append(startJointChild)
        while startJointChild.name() != endJoint.name():
            startJointChild = pm.listRelatives(startJointChild,c=True, type='joint')[0]
            self.jointChain.append(startJointChild)
        
        jntPos = []
        for jnt in self.jointChain:
            pos = jnt.getTranslation(space= 'world')
            jntPos.append(pos)
        
        self.splineCurveScl = pm.curve(p=jntPos, degree =1, n = self.startJoint.name().replace('01_JNT','CRV_SCL'))
        self.splineCurveScl.setPivots(jntPos[0])
        pm.parent(self.splineCurveScl, sclJnt)
        
        strArclenSCL = pm.arclen(self.splineCurveScl,ch=True)
        arclenSCL = pm.ls( strArclenSCL ) [0]
        arclenSCL.rename(self.splineCurveScl.name() + '_length')
        distanceNode = pm.createNode('distanceBetween',name = self.startJoint.name().replace('_01_JNT','distance'))
        
        sclJnt.rotatePivotTranslate.connect(distanceNode.point1)
        ikGrp.rotatePivotTranslate.connect(distanceNode.point2)
        sclJnt.worldMatrix.connect(distanceNode.inMatrix1)
        ikGrp.worldMatrix.connect(distanceNode.inMatrix2)
     
        mdScaleFactor = pm.createNode('multiplyDivide', name = self.splineCurveScl.name().replace('CRV_SCL','CRV_scaleFactor_MD'))
        distanceNode.distance.connect(mdScaleFactor.input1X)
        arclenSCL.arcLength.connect(mdScaleFactor.input2X)
        mdScaleFactor.operation.set(2)

        cndScaleFactor = pm.createNode('condition', name = self.splineCurveScl.name().replace('CRV_SCL','CRV_scaleFactor_CND'))
        distanceNode.distance.connect(cndScaleFactor.firstTerm)
        arclenSCL.arcLength.connect(cndScaleFactor.secondTerm)
        mdScaleFactor.outputX.connect(cndScaleFactor.colorIfTrueR)
        
        cndScaleFactor.operation.set(2)
        
        
        for jnt in self.jointChain:
            cndScaleFactor.outColorR.connect(jnt.scaleX)                 
Пример #9
0
    def createCgfxShader(self):
        # get the materials starting from the shaders and looking for connections
        shadersList = [sh.name() for sh in pm.ls(type="shadingEngine")]
        # maya's default shaders, we remove them
        mayaShaders = ["initialParticleSE", "initialShadingGroup"]

        shadersList = set(shadersList) - set(mayaShaders)
        materialList = []

        for sh in shadersList:

            mat = pm.listConnections("%s.surfaceShader" % sh)[0]
            materialList.append(mat)

        for mat in materialList:
            try:
                diffuseFile = pm.listConnections("%s.color" % mat)[0]
            except:
                pm.warning("No diffuse file found")
            try:
                specFile = pm.listConnections("%s.specularColor" % mat)[0]
            except:
                pm.warning("No spec file found")
            try:
                normFile = pm.listConnections("%s.normalCamera" % mat)[0]
            except:
                pm.warning("No norm file found")

            # create a cgfx material
            cgfxShader = pm.shadingNode("cgfxShader", asShader=1)
            cgfxShader.rename(mat + "_cgfx")
            cmd = 'cgfxShader -e -fx "'

            cmd += CHARACTERS_PATH.replace("scenes/characters", "renderData/shaders") + 'zoobeCharacterShader2.cgfx"'
            cmd += cgfxShader.name()
            # assign the zoobe cgfx shader file
            pm.mel.eval(cmd)

            self.saveChar(self.name)
            """
            if diffuseFile:
                #diffuseFile.outColor.connect(cgfxShader.diffuseMapSampler)
                pm.connectAttr('%s.outColor'%diffuseFile.name(),'%s.diffuseMapSampler'%cgfxShader.name())
            
            if specFile:
                specFile.outColor.connect(cgfxShader.specularMapSampler)
            if normFile:
                normFile.outNormal.connect(cgfxShader.normalMapSampler)
            """
            # get the shaders for the materials
            shader = pm.listConnections("%s.outColor" % mat)[0]
            print shader

            # connect the cgfx material to the mesh shader
            shader.surfaceShader.disconnect()
            cgfxShader.outColor.connect(shader.surfaceShader)
Пример #10
0
def getSourcePlug(plugname, index):
    conns = []
    if index < 0:
        conns = pm.listConnections(plugname, p=1, s=1, d=0)
    else:
        conns = pm.listConnections('%s[%s]'%(plugname, index), p=1, s=1, d=0)
    if conns:
        if len(conns) == 1:
            return conns[0]
        else:
            return ""
Пример #11
0
def bdSetUpLamberts():
	cgfxShaders = pm.ls(type='cgfxShader')
	for cgfx in cgfxShaders:
		diffuseFile = pm.listConnections('%s.diffuseMapSampler'%cgfx)[0]
		shaderNode = pm.listConnections('%s.outColor'%cgfx)[0]
		#transparancyFile = pm.listConnections('%s.specularMapSampler'%cgfx)[0]
		lambertNode = pm.shadingNode('lambert',asShader=1,n=cgfx.name() + '_LMB' )
		diffuseFile.outColor.connect(lambertNode.color)
		
		cgfx.outColor.disconnect()
		lambertNode.outColor.connect(shaderNode.surfaceShader)
Пример #12
0
def createDistanceTool(objA=None, objB=None):
    """ A better version of Maya's Distance Tool """
    if objA == None and objB == None:
        objA, objB = getSelection(2)
    elif objA == None or objB == None:
        raise SelectionError("Incorrect Selection!")
    spPos = getPosition(objA)
    epPos = getPosition(objB)
    distanceNode = pm.distanceDimension(sp=spPos, ep=epPos)
    locSp = pm.listConnections(str(distanceNode) + ".startPoint")[0]
    locEp = pm.listConnections(str(distanceNode) + ".endPoint")[0]
    return [locSp, locEp]
def multi_illDefault(*args):
	sel_lights = pm.ls(sl=True, lights=True, dag=True)
	connections = pm.listConnections('defaultLightSet', d=False, s=True)

	for each in sel_lights:
		trans = pm.listRelatives(each, parent=True, fullPath=True)[0]
		if multi_illDefault_box.getValue() == 0 and trans in connections:
			defaultSet = pm.listConnections(trans, d=True, s=True, plugs=True)[0]
			pm.disconnectAttr(trans+'.instObjGroups[0]', defaultSet)

		elif multi_illDefault_box.getValue() == 1:
			pm.connectAttr(trans+'.instObjGroups',  'defaultLightSet.dagSetMembers', nextAvailable=True)
Пример #14
0
def bdBuildSplineSolverScale():
    selection = pm.ls(sl=1,type='transform')
    startJoint = ''
    if selection:
        startJoint = selection[0]
    else:
        return
    
    print startJoint
    
    ikSpline  = pm.listConnections(startJoint,type='ikHandle')[0]
    print ikSpline  
    solver = ikSpline.ikSolver.inputs()[0]
    
    if 'ikSplineSolver' in solver.name():
        sclChain = pm.duplicate(startJoint,name = startJoint.name() + '_SCL')[0]
        sclChainAll = sclChain.listRelatives(f=True, ad=True,type='joint')
        
        print sclChainAll  
        
        for sclJnt in sclChainAll:
            pm.rename(sclJnt,sclJnt+'_SCL')
        
        splineCurve = pm.listConnections(ikSpline, type = 'nurbsCurve')[0]
    
        effector = pm.listConnections(ikSpline ,source=True, type='ikEffector')[0]
        endJoint = pm.listConnections(effector,source=True, type='joint')[0]
        jointChain = startJoint.listRelatives(f=True, ad=True,type='joint')
        jointChain  = jointChain + [startJoint]
        jointChain.reverse()
        print jointChain
        
        splineCurveScl = pm.duplicate(splineCurve,name = splineCurve.name().replace('crv','crv_scl'))
        strArclenSCL = pm.arclen(splineCurveScl,ch=True)
        strArclenCRV = pm.arclen(splineCurve,ch=True)
        arclenSCL = pm.ls( strArclenSCL ) [0]
        arclenCRV = pm.ls( strArclenCRV ) [0]
        arclenSCL.rename(splineCurveScl[0].name() + '_length')
        arclenCRV.rename(splineCurve.name() + '_length')
        
        mdScaleFactor = pm.createNode('multiplyDivide', name = splineCurve.name().replace('crv','crv_scaleFactor_md'))
        arclenCRV.arcLength.connect(mdScaleFactor.input1X)
        arclenSCL.arcLength.connect(mdScaleFactor.input2X)
        mdScaleFactor.operation.set(2)
    
        for jnt in jointChain[1:]:
            mdJntTr = pm.createNode('multiplyDivide', name = jnt + '_trX_MD')
            #mdJntTr.operation.set(2)
            
            sclJnt = pm.ls(jnt + '_SCL')[0]
            mdScaleFactor.outputX.connect(mdJntTr.input2X)
            sclJnt.translateX.connect(mdJntTr.input1X)
            mdJntTr.outputX.connect(jnt.translateX)
	def connectToAlembicCache(self, namespace = ''):
		
		#get SelectionList
		selectionList = pm.ls(sl = True, fl = True, type = 'transform')
		pm.select(cl = True)
		
		#check if objects are selected
		if not(selectionList):
			if(self.verbose): print('No objects selected, please select at least one object.')
			return None
			
		#Check if namespace is valid
		if not(namespace in self.getNamespaces()):
			if(self.verbose): print('Picked namespace does not exists anymore. Please refresh namespace list')
			return None
		
		
		
		
		#Connect to alembic node
		
		
		#Iterate through selectionList and connect same object plus namespace to alembic cache node if possible
		for masterTrans in selectionList:
			
			#getShape
			masterShape = masterTrans.getShape()
			
			#check if masterShape inMesh Attr connected to Alembic
			if not(pm.nodeType(pm.listConnections(masterShape.inMesh, s = True)[0]) == 'AlembicNode'):
				if(self.verbose): print(masterTrans.name() +' inMesh Attribute not connected to Alembic node. Continuing...')
				continue
				
			#Check if namespace + masterTrans object exists
			if not(pm.objExists(namespace +':' +masterTrans.name().split(':')[-1])):
				if(self.verbose): print(namespace +':' +masterTrans.name().split(':')[-1] +' does not exist. Continuing...')
				continue
				
			
			#Connect Object to Alembic Node
			connectioSourceAttr = pm.listConnections(masterShape.inMesh, s = True, p = True)[0]
			connectionDestinationAttr = namespace +':'  +masterShape.name().split(':')[-1] +'.inMesh'
			pm.connectAttr(connectioSourceAttr, connectionDestinationAttr,f = True)
		
		
		
		#Success Msg
		if(self.verbose): print('Successfully connected PaintFx Hair Geo to Alembic Cache')
Пример #16
0
	def exportAnim(self, *args):
		objs = pm.ls( sl=True )
		successState = True
		
		filePath = pm.fileDialog2( caption='Save Animation', startingDirectory=uad , fileFilter="Anim Files (*.anim)" )
		
		if not filePath:
			sys.stdout.write('Save animation cancelled.')
			return None
		
		
		animInfos = {} # dictionary containing dictionaries of every object's animations
		for obj in objs:
			
			if not ( self.hasUniqueName( obj ) ): # if object'n name is not unique, doesn't save animation for it
				successState = False
				pm.warning( "Object %s's name is not unique. skipped"%obj.name() )  
				continue
			
			nameSpace = self.getNameSpace( obj )
			if nameSpace:
				objName = obj.name().split(':')[1]
			else:
				objName = obj.name()
			
			# find all anim curves on the object
			curves = pm.findKeyframe( obj , curve=True )
			
			
			if not curves: # jump to next object if no anim curve found
				continue
				
			animInfo = {} # dictionary containing one object's animations
			
			for curve in curves: # for each curve, find where it's connected to, keys' times, values and tangents
				attr = pm.listConnections( '%s.output'%curve, plugs=True )[0]
				if nameSpace:
					attrName = attr.name().split(':')[1]
				else:
					attrName = attr.name()
				times = pm.keyframe( attr, q=True, timeChange=True )
				values = pm.keyframe( attr, q=True, valueChange=True )
				outWeights = pm.keyTangent( attr, q=True, outWeight=True )
				outAngles = pm.keyTangent( attr, q=True, outAngle=True )
				inWeights = pm.keyTangent( attr, q=True, inWeight=True )
				inAngles = pm.keyTangent( attr, q=True, inAngle=True )
				animInfo[ attrName ] = { 'times':times, 'values':values, 'outWeights':outWeights, 'outAngles':outAngles, 'inWeights':inWeights, 'inAngles':inAngles }
			
			animInfos[ objName ] = animInfo
		
		# write anim info to file
		filePath = filePath[0]
		logfile = open( filePath , 'w')
		logfile.write( str(animInfos) )
		logfile.close()
		
		if successState:
			sys.stdout.write( 'Animation was successfully exported.' )
		else:
			pm.warning( 'Some objects animtions were not saved due to multiple object with the same name, check script editor for more info.' )
Пример #17
0
def __cleanPrevisouConnection__(previousNode):
    # source part meaning decoMat
    for i in range(0, len(previousNode[0])):
        tmp=pmc.listConnections(previousNode[0][i], source=False, destination=True, connections=False, plugs=False)
        if len(tmp)==0:
            if(previousNode[0][i]):
                pmc.delete(previousNode[0][i], hierarchy='none', all=False)
Пример #18
0
def assign_material(mtl_or_sg, *nodes):
    '''Assign a material to a bunch of nodes

    :param mtl_or_sg: The material or shadingEngine to assign
    :param nodes: The nodes to be assigned to
    '''

    class_ = mtl_or_sg.classification()

    if 'shadingEngine' in class_:
        sg = mtl_or_sg
    elif 'shader/surface' in class_:
        sgs = pmc.listConnections(mtl_or_sg, type='shadingEngine')
        if sgs:
            sg = sgs[0]
        else:
            sg = pmc.sets(
                empty=True,
                renderable=True,
                name=str(mtl_or_sg) + 'SG'
                )
            mtl_or_sg.outColor.connect(sg.surfaceShader)
    else:
        raise TypeError('{} not a shader or shadingEngine'.format(mtl_or_sg))

    for node in nodes:
        pmc.sets(sg, forceElement=node)
Пример #19
0
def findMultiMat():
    meshes = pm.ls(type = 'shape')
    # 
    for m in meshes:
        shader = pm.listConnections(m, type = 'shadingEngine')
        if len(shader)>2:
            print(m)
Пример #20
0
def createFKChainHierarchy(jointList, radius = 1, theSuffix = "_FK_ctrl", axis = [1,0,0] ):
#     jointList = pm.ls(sl = True)[0]
    fkCtrlsGrp = []
    fkCtrls = []

    # find all descendants
#     jointList = collectAllChild(jointList)
    
    for s in jointList:
        # find parent selection
        parentTmp = s.getParent()

        # create ctrl
        helpRoot, help = helpers.createOneHelper(type = "circle", sel = s, suf = theSuffix, axis = axis, freezeGrp= True, hierarchyParent = None, constraintTo = s)
        fkCtrlsGrp.append(helpRoot)
        fkCtrls.append(help)
        
        # if parent ctrl: parent root helper to parent ctrl
        if parentTmp:
            # find parent ctrl
            const = pm.listRelatives(parentTmp, type = "parentConstraint")
            if len(const)>0:
                parentCtrl = pm.listConnections(const[0].target[0].targetTranslate)
                pprint(parentCtrl)
                # attach new ctrl to parent
                helpRoot.setParent(parentCtrl)
        
    
    return fkCtrlsGrp, fkCtrls
Пример #21
0
def AddNodeToContainer(_containerName, _nodesIn, _includeHierarchyBelow = False, _includeShapes = False, _force = False):
    
    import types
    
    nodes = []
    
    # create a new list of current list object
    if type(_nodesIn) is types.ListType:
        nodes = list(_nodesIn)
    
    # store current object as a list
    else:
        nodes = [_nodesIn]
    
    # Put maya unit conversion nodes in a list
    conversionNodes = []
    
    for node in nodes:
        node_conversionNodes = pm.listConnections(node, source = True, destination = True)
        node_conversionNodes = pm.ls(node_conversionNodes, typ = 'unitConversion')
        
        conversionNodes.extend(node_conversionNodes)

    
    # Store everything in a single list
    nodes.extend(conversionNodes)
    pm.container(_containerName, edit = True, addNode = nodes, includeHierarchyBelow = _includeHierarchyBelow, includeShapes = _includeShapes, force = _force)
Пример #22
0
def DistGlobalScale ( dist=None, mainCtrl=None ) :
	
	if dist==None or mainCtrl==None :
		dist, mainCtrl = pm.ls (sl=True)
	else:
		dist = pm.ls( dist )[0]
		mainCtrl = pm.ls( mainCtrl )[0]
	
	if dist and mainCtrl:
		
		if dist.type() == 'multiplyDivide':
			outAttr = 'outputX'
			distShape = dist
		else:
			outAttr = 'distance'
			if dist.type() == 'transform': # if transform node of distance node is selected, then select it's shape
				distShape = dist.getShape()
			else:
				distShape = dist
		
		distShapeOuts = pm.listConnections (distShape ,s=False, p =True)
		
		if len (distShapeOuts) != 0 :
		
			globalScale_mdn = pm.createNode ("multiplyDivide" , n = "globalScale_mdn" )
			
			distShape.attr( outAttr ) >> globalScale_mdn.input1X
			
			mainCtrl.scaleY >> globalScale_mdn.input2X
			
			globalScale_mdn.operation.set ( 2 )
			
			for out in distShapeOuts:
				
				globalScale_mdn.outputX >> out
Пример #23
0
def isKeyAble(name):
    keyable = 0
    
    if (pm.getAttr(name,l = 1) == False) and (len(pm.listConnections(name,s = 1,d = 0)) == 0):
        keyable = 1

    return keyable
Пример #24
0
 def findSG(self,shapeNode):
     '''
     Function: Find the shading group node of a polymesh
     '''
     shadingGroups=pm.listConnections(shapeNode, type='shadingEngine')
     #Shading groups are of node type shadingEngine
     return shadingGroups
Пример #25
0
def copy_correctiveToBlend(base, corrective):
    '''Bakes a static mesh that can be used as a corrective to what you've posed
    Args:
        base (pm.PyNode): base object with bad shape from skinCluster or blendShapes
        corrective (pm.PyNode): sculpted fixed shape
    Returns:
        [pm.PyNode]: new corrected shape
    Usage:
        copy_correctiveToBlend(pm.ls(sl=True)[0], pm.ls(sl=True)[1])
    '''
    #Duplicate your deformed mesh twice, calling one positive and one negative. Move them a little away from your model
    positive = corrective
    negative = pm.duplicate(base, n=corrective.name()+"_negative")[0]
    inputs = pm.listConnections(base.getShape(), type=['skinCluster','blendShape'])
    for input in inputs:
        input.attr('envelope').set(0)
    corrected = pm.duplicate(base, n=corrective.name()+"_corrective")[0]
    #Make a new blend-shape node on your character containing the two duplicate meshes. This blend shape must use the parallel blending mode.
    blend = pm.blendShape(corrected, n='corrector_BS')[0]
    pm.blendShape(blend, e=True, t=(corrected, 0, positive, 1.0))
    pm.blendShape(blend, e=True, t=(corrected, 1, negative, 1.0))
    set=1
    for alias in blend.listAliases():
        alias[1].set(set)
        set=-1
    #Move your character back to bind-pose and in the parallel blend-node, set the positive mesh to 1 and the negative to -1. This should blend your mesh so that you only have the deformations you made to the positive mesh, but now in a neutral pose.
    #bindPose
    
    #Duplicate this new mesh and call it something with the letters BS is the name because this is infinitely funny. This mesh can now be used as a corrective blend-shape
    #Delete the parallel blend-node and repeat these steps for all your shapes. Yes, really.
    #pm.delete(p_bs)
    #pm.delete(base)
    for input in inputs:
        input.attr('envelope').set(1)
    return corrected
Пример #26
0
def cns_del():
    #Takes current objects selected and puts them in a list.
    for obj in obj_sel:
        #creating a variable to hold the listed connections of constraints using the for loops that passes through each object.
        obj_cns = set(pm.listConnections(type = "constraint", destination = False))
        #deleting the constraint as it filters through each object within the list.
        pm.delete(obj_cns)
 def trackDag(self,inCon,nodeType):
     """
     uses the inCon as a source to track down the dag network to find 
     and return all nodes that are driven by the output attr on it
     """
     
     retValue=[]
     if pm.attributeQuery("output",n=inCon,ex=True):
         outs=pm.listConnections("{0}.output".format(inCon),s=0,d=1,p=1) 
         for out in outs:
             outNode=pm.PyNode(str(out).split(".")[0])
             attr=str(out).split(".")[1]
             if isinstance(nodeType, list):
                 for x in nodeType:
                     tempValue=None
                     if isinstance(outNode,x):
                         tempValue=(outNode,attr)
                     else:
                         tempValue=(self.trackDag(outNode,nodeType))
                 
                     if tempValue:
                         retValue.append(tempValue)
                         break        
             else:
                 if isinstance(outNode,nodeType):
                     retValue.append((outNode,attr))
                 else:
                     retValue.append(self.trackDag(outNode,nodeType))
         if len(retValue)>1:
             return retValue
         else:
             return retValue[0]
     else:
         return None
Пример #28
0
def DistGlobalScale ( dist=None, mainCtrl=None ) :
	
	if dist==None or mainCtrl==None :
		dist, mainCtrl = pm.ls (sl=True)
	else:
		dist = pm.ls( dist )[0]
		mainCtrl = pm.ls( mainCtrl )[0]
	if dist and mainCtrl:
		distShape = dist.getShape()

		distShapeOuts = pm.listConnections (distShape ,s=False, p =True)
		
		if len (distShapeOuts) != 0 :
		
			globalScale_mdn = pm.createNode ("multiplyDivide" , n = "globalScale_mdn" )
			
			distShape.distance >> globalScale_mdn.input1X
			
			mainCtrl.scaleY >> globalScale_mdn.input2X
			
			globalScale_mdn.operation.set ( 2 )
			
			for out in distShapeOuts:
				
				globalScale_mdn.outputX >> out
Пример #29
0
def get_connected_attr(con_node, obj):
    """
    Get a list of node connections to key.

    :param con_node: Constraint PyNode.
    :param obj: Constrained object to check connections.
    :return: Attributes connected to the constraint.
    :rtype: List of Attribute() objects.
    """
    node_connections = set(pmc.listConnections(con_node, source=False, destination=True))
    for node in node_connections:
        if node == obj:
            attr_list = pmc.listConnections(con_node, source=False, destination=True, plugs=True)
        elif isinstance(node, pmc.nodetypes.PairBlend):
            attr_list = pmc.listConnections(node, source=False, destination=True, plugs=True)
    return attr_list
Пример #30
0
def collectShaderInfoInLayer():
    sel = pm.ls(sl=True, dag=True, type='mesh')        
       
    shader_info_all_layers = []
    
    for renderlayer in pm.ls(type='renderLayer'):
        pm.editRenderLayerGlobals( currentRenderLayer=renderlayer )
        
        #// shader_info_layer stores the info for each seleted objs in CURRENT layer
        #// flush content of shader_info_layer 
        shader_info_layer = []
        for mesh in sel:
            SG_list = pm.listConnections(mesh, t='shadingEngine')
            #print SG_list
            
            if( SG_list == None ):
                continue
             
            if( len(SG_list) < 1 ):
                SG_list.append('initialShadingGroup')
            
            #// store mesh & material in CURRENT layer
            shader_info_layer.append( ( mesh, SG_list[0] ) )
            
        shader_info_all_layers.append( ( renderlayer, shader_info_layer ) )
        
    pm.editRenderLayerGlobals( currentRenderLayer='defaultRenderLayer' )          
    return shader_info_all_layers
Пример #31
0
 def make_tree(self, root):
     roots = core.listConnections(root,
                                  plugs=True,
                                  connections=True,
                                  source=True,
                                  destination=False,
                                  sourceFirst=True)
     return TreePager.make_tree(self, roots)
Пример #32
0
def mirrorNodes(anim_root, side):
    children = pm.listRelatives(anim_root, type='joint', ad=1)
    children.reverse()
    if len(children):
        chain = [anim_root] + children
        for jnt in chain:
            connections = pm.listConnections(jnt, c=1, scn=1, d=0, s=1)
            plugs = pm.listConnections(jnt, p=1, scn=1, d=0, s=1)
            i = 0
            for dest, src in connections:
                if side == 'l':
                    if src.type() == 'remapValue' or src.type(
                    ) == 'multDoubleLinear':
                        mirrored_rig_node = pm.duplicate(
                            src, name=src.name().replace('l_', 'r_'))[0]
                        src_attr = plugs[i].split('.')[1]
                        dest, dest_attr = dest.split('.')
                        mirrored_dest = pm.ls(dest.replace('l_', 'r_'))[0]
                        mirrored_rig_node.attr(src_attr) >> mirrored_dest.attr(
                            dest_attr)
                        # print mirrored_rig_node
                        # print src.type() + '  -------  ' + dest
                        # print plugs[i]
                        # print src_attr
                        rig_node_connections = pm.listConnections(src,
                                                                  c=1,
                                                                  scn=1,
                                                                  d=0,
                                                                  s=1)
                        rig_node_plugs = pm.listConnections(src,
                                                            p=1,
                                                            scn=1,
                                                            d=0,
                                                            s=1)
                        j = 0
                        for rig_node_dest, rig_node_src in rig_node_connections:
                            print rig_node_dest + ' ------------ ' + rig_node_src
                            print rig_node_plugs[j]
                            mirror_rig_node_src = pm.ls(
                                rig_node_src.name().replace('l_', 'r_'))[0]
                            src_attr = rig_node_plugs[j].split('.')[1]
                            dest_attr = rig_node_dest.split('.')[1]
                            mirror_rig_node_src.attr(
                                src_attr) >> mirrored_rig_node.attr(dest_attr)
                            j += 1
                    i += 1
Пример #33
0
    def get_asigned_material(self, object):
        """ get_asigned_material es auxiliar de guardar_material_antiguo_y_asignar_nuevo
        devuelve esl material y shading group que tiene un objeto asignado
        Returns
        -------
        shd, shdSG contienen el material y shading groups asignados

        Parameters
        ----------
        object objeto del que se extrae el material
        """
        shd=None
        shdSG = pm.listConnections(object, type='shadingEngine')
        if shdSG:
            shd = pm.listConnections(shdSG[0] + '.surfaceShader')
            #print 'OBJECT: ' + object + ' | ' + 'MAYA SHADER: ' + shd[0] + ' | ' + 'MAYA SG: ' + shdSG[0]
        return shd, shdSG
Пример #34
0
    def fix_attachments(self, attachment_joint_list):
        '''
        Looks for remaining constraints on the attachment joint list and if found fills in constraints to the same target
        Should only be called after removal of the component
        '''
        performed_fix = False
        for skeleton_joint in attachment_joint_list:
            has_point_constraint = list(
                set(
                    pm.listConnections(skeleton_joint,
                                       type='pointConstraint',
                                       s=True,
                                       d=False)))
            has_orient_constraint = list(
                set(
                    pm.listConnections(skeleton_joint,
                                       type='orientConstraint',
                                       s=True,
                                       d=False)))

            if has_point_constraint and not has_orient_constraint:
                const_influence_list = list(
                    set(
                        pm.listConnections(has_point_constraint,
                                           type='joint',
                                           s=True,
                                           d=False)))
                target = [
                    x for x in const_influence_list if x != skeleton_joint
                ]
                pm.orientConstraint(target, skeleton_joint, mo=False)
                performed_fix = True
            elif has_orient_constraint and not has_point_constraint:
                const_influence_list = list(
                    set(
                        pm.listConnections(has_orient_constraint,
                                           type='joint',
                                           s=True,
                                           d=False)))
                target = [
                    x for x in const_influence_list if x != skeleton_joint
                ]
                pm.pointConstraint(target, skeleton_joint, mo=False)
                performed_fix = True

        return performed_fix
Пример #35
0
 def matteIdSelect_PB_hit(self):
     attr_name, matteIdColor, attr_node = self.checkMatteIdData()
     node_list = pm.listConnections(attr_node.defaultFloat3, s=False, d=True)
     sel_list = []
     for node in node_list:
         if node.type() != 'renderLayer':
             sel_list.append(node)
     pm.select(sel_list, replace=True)
Пример #36
0
 def ikHandle(self):
     self._MODEL.ikHandle = [
         x for x in pm.listConnections(
             str(pm.PyNode(self.startJnt)) + '.message',
             s=1,
         ) if x != 'MayaNodeEditorSavedTabsInfo'
     ][0]
     return (self._MODEL.ikHandle)
Пример #37
0
    def is_default_shader(self):
        self.result_message = ''
        result_objects = []
        geometry = pm.ls(geometry=True)

        for it in geometry:
            shading_engine = pm.listConnections(it, type='shadingEngine')
            for se in shading_engine:
                materials = pm.listConnections(se, type='lambert')
                for mat in materials:
                    if str(mat) == 'lambert1':
                        result_objects.append(it)

        for it in result_objects:
            self.result_message += it + '\n'
        pm.select(result_objects)
        return self.result_message
Пример #38
0
def listCon(plug, fallback):
    ''' Wrap listConnections returing the first connection or None
    '''
    cons = listConnections(plug)
    if cons:
        return cons[0]
    else:
        return fallback
Пример #39
0
def addSurfToDeformer(surfs, deformer):
    '''
    '''
    membershipSet = pm.listConnections(deformer, type='objectSet')[0]
    #pm.sets(surfs, add=membershipSet)
    surfs = [str(s) for s in surfs]
    memSet = str(membershipSet)
    mc.sets(surfs, add=memSet)
Пример #40
0
def bdGetJntFromMesh():
    import pymel.core as pm
    sel = pm.ls(sl=True)[0].getShape()
    skinCls = pm.listConnections('%s.inMesh' % sel)
    print skinCls
    jnts = pm.skinCluster(skinCls, q=True, influence=True)
    names = [str(jnt.name()) for jnt in jnts]
    pm.select([names])
Пример #41
0
def getPickerPlug(ctrl):
    ''' Return the picker plug this control is connected to.
    
    Example return: 'network27.fkLinker[1].fkController'
    '''
    for plug in listConnections(ctrl + '.message', p=True, s=False, d=True):
        if 'kLinker[' in str(plug):
            return plug
Пример #42
0
def prune_DK_nodes(white_list=[]):
    """
    Finds all the driven key nodes that have no
    input or output connected and removes them.
    Nodes with the word profile in are excluded
    so that no guide components are broken.

    Arguments:
        white_list (list / optional): List of nodes to ignore

    Returns:
        list (All the names of the deleted nodes)
    """
    # Getting all the anim nodes in scene
    all_anim_nodes = pm.ls(type=SDK_ANIMCURVES_TYPE)

    # If a node has no connections, store it.
    problem_nodes = []
    for anim_node in all_anim_nodes:
        if not pm.listConnections(anim_node.input):
            if anim_node not in problem_nodes:
                if anim_node not in white_list:
                    if "profile" not in anim_node.nodeName():
                        problem_nodes.append(anim_node)
        if not pm.listConnections(anim_node.output):
            if anim_node not in problem_nodes:
                if anim_node not in white_list:
                    if "profile" not in anim_node.nodeName():
                        problem_nodes.append(anim_node)

    # Deleting the problem nodes
    for node in problem_nodes:
        pm.delete(node)

    # node names
    deleted_nodes = [x.nodeName() for x in problem_nodes]

    if deleted_nodes:
        print("Deleted Nodes:")
        for deleted_node in deleted_nodes:
            print(deleted_node)
    else:
        print("No Nodes found to delete")

    return deleted_nodes
Пример #43
0
def remove_bindPoses(joints):
    for j in joints:
        con = pm.listConnections(j, d=1, type='dagPose')
        for c in con:
            try:
                pm.delete(c)
            except:
                # bind node already deleted
                pass
Пример #44
0
def _vertsFromShader(shader=None):
    currentSel = pm.ls(sl=1)
    faces = pm.listConnections(shader,
                               type='shadingEngine')[0].members(flatten=1)
    pm.select(faces, r=1)
    pm.mel.eval('ConvertSelectionToVertices;')
    verts = pm.ls(sl=1)
    pm.select(currentSel, r=1)
    return verts
Пример #45
0
    def createMotionPath(self, object, curve, uValue, fractionMode=False):

        motionPath = pm.pathAnimation(object, curve, follow=1)
        PyMotionPath = pm.PyNode(motionPath)
        animNode = pm.listConnections(motionPath, t='animCurve')
        pm.delete(animNode)
        PyMotionPath.fractionMode.set(fractionMode)
        PyMotionPath.uValue.set(uValue)
        return PyMotionPath
Пример #46
0
def connectCns(cnxDict, nsRig=None, nsSkin=None):
    for i, jnt in enumerate(cnxDict["joints"]):
        if nsSkin:
            oJnt = pm.PyNode(nsSkin + ":" + jnt)
        else:
            oJnt = pm.PyNode(jnt)

        if cnxDict["attrs"][i][0]:
            if nsRig:
                oAttr = pm.PyNode(nsRig + ":" + cnxDict["attrs"][i][0])
            else:
                oAttr = pm.PyNode(cnxDict["attrs"][i][0])

            oNode = oAttr.node()
            oTrans = pm.listConnections(
                pm.listConnections(oNode.inputMatrix)[0].matrixIn[0])
            pm.parentConstraint(oTrans, oJnt, mo=True)
            pm.scaleConstraint(oTrans, oJnt, mo=True)
Пример #47
0
def get_color_texture(mesh):
    try:
        sg_node = mesh.outputs(type='shadingEngine')[0]
        shader = pm.listConnections(sg_node.surfaceShader,
                                    source=1,
                                    destination=0)[0]
        diffuse_attr = pm.listConnections(shader.color,
                                          source=1,
                                          destination=0)[0]
        if diffuse_attr.type() == 'file':
            return diffuse_attr.fileTextureName.get()
        else:
            for i in pm.listHistory(diffuse_attr):
                if i.type() == 'file':
                    if 'CLR' or 'DIFF' in i.fileTextureName.get():
                        return i.fileTextureName.get()
    except:
        return None
Пример #48
0
def connectNewBs():
    selection = pm.ls(sl=1)
    for s in selection:
        shape = s.getShape()
        shape_new = pm.ls('new_' + shape.name())[0]
        con = pm.listConnections(shape.name(), plugs=1, type='blendShape')[0]

        shape.attr('worldMesh[0]') // con
        shape_new.attr('worldMesh[0]') >> con
Пример #49
0
def isDecomposed(node):
    # check to see if a decompose matrix is already connected to node
    conns = pmc.listConnections(node.worldMatrix[0], s=0, d=1, t='decomposeMatrix')
    d = None
    if conns:
        d = conns[0]
    else:
        d = decomposeWorldMatrix(node)
    return d
Пример #50
0
 def root(self):
     '''
     Transform node that is the scene group object for this node
     '''
     return_root = get_first_or_default(
         pm.listConnections(self.node.root_joint, type=pm.nt.Joint))
     return_root = return_root if return_root else self.get_root(
         self.get_first_connection())
     return return_root
Пример #51
0
def bdAttrMoveUp(attr):
    print 'Moving %s attr up' % attr
    attrList = bdGetAttrList()
    attrIndex = 0
    for a in attrList:
        if attr in a.name():
            attrIndex = attrList.index(a)

    attrReconstruct = attrList[(attrIndex - 1):]
    attrReconstructConnections = []
    attrReconstructValues = []
    attrReconstructType = []
    attrReconstructRange = []

    for attr in attrReconstruct:
        attrConnections = pm.listConnections('%s' % attr, plugs=1)
        attrReconstructConnections.append(attrConnections)

        attrValue = bdGetValue(attr)
        attrReconstructValues.append(attrValue)

        attrType = attr.type()
        attrReconstructType.append(attrType)

        attrRange = attr.getRange()
        attrReconstructRange.append(attrRange)

    shiftItem = attrReconstruct.pop(1)
    attrReconstruct.insert(0, shiftItem)

    shiftItem = attrReconstructConnections.pop(1)
    attrReconstructConnections.insert(0, shiftItem)

    shiftItem = attrReconstructValues.pop(1)
    attrReconstructValues.insert(0, shiftItem)

    shiftItem = attrReconstructType.pop(1)
    attrReconstructType.insert(0, shiftItem)

    shiftItem = attrReconstructRange.pop(1)
    attrReconstructRange.insert(0, shiftItem)
    '''
    i = 0
    for attr in attrReconstruct:
        print attr.name()
        print attrReconstructConnections[i]
        print attrReconstructValues[i]
        print attrReconstructType[i]
        print attrReconstructRange[i]
        i += 1

    '''
    for attr in attrReconstruct:
        try:
            pm.deleteAttr(attr)
        except:
            pm.warning('Fail to delete %s' % attr.name())
Пример #52
0
 def make_tree(self, root):
     import pymel.core as pm
     roots = pm.listConnections(root,
                                plugs=True,
                                connections=True,
                                source=True,
                                destination=False,
                                sourceFirst=True)
     return TreePager.make_tree(self, roots)
def get_switch_inputs(slot_material, coat, size, progress_bar):
    #get selected number
    switch_number = slot_material.materialsSwitch.get()
    #get corresponding material and process
    chosen_material = pm.listConnections(slot_material + ".material_" +
                                         str(int(switch_number)))
    if (chosen_material):
        print(chosen_material + ":")
        get_color_or_inputs(chosen_material[0], coat, size, progress_bar)
Пример #54
0
    def addShadowPlane(self):
        print 'Creating the shadow plane'
        shadowPlane = pm.polyPlane(n='shadowPlane',
                                   w=10,
                                   h=10,
                                   sx=1,
                                   sy=1,
                                   ax=(0, 1, 0),
                                   cuv=2,
                                   ch=0)
        shadowJoint = pm.joint(n='shadowJoint')
        pm.skinCluster(shadowJoint, shadowPlane)

        root = pm.ls("Root", type='joint')[0]
        pm.parent(shadowJoint, root)

        # rig the plane
        hips = pm.ls("Hips", type='joint')[0]
        leftFoot = pm.ls("LeftFoot", type='joint')[0]
        rightFoot = pm.ls("RightFoot", type='joint')[0]

        pm.pointConstraint(hips, shadowJoint, mo=0, skip='y')
        pm.pointConstraint(leftFoot, shadowJoint, mo=0, skip='y')
        pm.pointConstraint(rightFoot, shadowJoint, mo=0, skip='y')

        # default T pose Y value for the hips will be stored as reference
        # pm.addAttr(hips, ln = 'startY',t = 'double')
        hipsY = hips.getTranslation(space='world').y
        # pm.setAttr(hips.name() + '.startY',hipsY)

        shadowPlaneRV = pm.createNode('remapValue', n='shadowPlane_RV')
        shadowPlaneRV.imx.set(hipsY * 2.0)
        shadowPlaneRV.outputMin.set(2.0)
        shadowPlaneRV.outputMax.set(0)

        hips.translateY.connect(shadowPlaneRV.inputValue)
        shadowPlaneRV.outValue.connect(shadowJoint.scaleX)
        shadowPlaneRV.outValue.connect(shadowJoint.scaleY)
        shadowPlaneRV.outValue.connect(shadowJoint.scaleZ)

        shadowPlaneCgfx = self.importCgfxShader()
        shadowPlaneCgfx.rename('shadowPlane_cgfx')
        shadowPlaneSg = pm.listConnections('%s.outColor' % shadowPlaneCgfx)[0]
        shadowPlaneSg.rename('shadowPlane_cgfxSG')

        shadowPlaneTxt = pm.shadingNode('file',
                                        asTexture=1,
                                        name='shadowPlane_file')

        shadowPlaneTxt.fileTextureName.set(
            'sourceimages\\groundshadow_diffusecolor.tga')
        shadowPlaneTxt.outColor.connect(shadowPlaneCgfx.diffuseMapSampler)

        pm.select(shadowPlane)
        pm.mel.eval('sets -e -forceElement ' + shadowPlaneSg)

        print 'Shadow plane created!!'
Пример #55
0
def get_displacement_attr_of_sg(sg_node):
    displacement_attr = pm.listConnections(sg_node.displacementShader,
                                           source=1,
                                           destination=0,
                                           plugs=1)
    if displacement_attr:
        return displacement_attr[0]
    else:
        return None
Пример #56
0
 def get_transforms(self):
     curve = self.node
     result = []
     for transform_attr in curve.input:
         conn = pm.listConnections(transform_attr, p=True, s=True, d=False)
         if not conn:
             continue
         result.append(conn[0])
     return result
Пример #57
0
    def get_related_nodes(self, node):
        """
        Return nodes that should also be observed for the given node.

        For example, if blendShape is being monitored, this can return connected blendShape
        targets, and the changed callback will be called if any of those nodes are renamed.
        """
        # By default, all directly connected nodes are related.
        return list(set(pm.listConnections(node)))
Пример #58
0
def listBindJoints(sels):
    window = QtWidgets.QWidget(qt.getMayaWindow())
    window.setWindowFlags(QtCore.Qt.Window)
    window.resize(650, 300)
    layout = QtWidgets.QVBoxLayout(window)

    widget = QtWidgets.QPlainTextEdit(window)

    for sel in sels:
        shape = pm.listRelatives(sel, c=True)
        if shape[0].nodeType() == 'mesh':
            skinCluster = pm.listConnections(shape[0] + '.inMesh',
                                             d=False,
                                             s=True)
            if skinCluster[0].nodeType() == 'skinCluster':
                bindList = pm.listConnections(skinCluster[0] + '.matrix',
                                              d=False,
                                              s=True)
                widget.insertPlainText(ar.obj(sel) + 'Bind = [\n')
                for jntList in bindList:
                    widget.insertPlainText("\t'" + jntList + "',\n")
                widget.insertPlainText('\t]\n')
                skcName = sel.replace(ar.node(sel), 'skc')
                cswName = sel.replace(ar.node(sel), 'csw')
                widget.insertPlainText("pm.skinCluster('" + sel + "', " +
                                       ar.obj(sel) + "Bind, n = '" + skcName +
                                       "', tsb = True)\n")
                widget.insertPlainText("pm.copySkinWeights(ss = '" +
                                       str(skinCluster[0]) + "', ds = '" +
                                       skcName + "', noMirror = True)\n")

            else:
                pm.error('Unbound or SkinCluster is not connected')
        else:
            pm.error('The selected object is not geometry')

    layout.addWidget(widget)

    button = QtWidgets.QPushButton('print', window)
    layout.addWidget(button)

    button.clicked.connect(main)

    window.show()
Пример #59
0
    def addObjMorphs(self):
        morphPath = os.path.join(
            os.path.split(self.fbxFile)[0], 'blendshapes/')
        morphFiles = [
            f for f in os.listdir(morphPath)
            if f.endswith('.obj') and 'default' not in f
        ]
        meshesVtxCount = {}
        meshes = pm.ls(type='mesh')
        for m in meshes:
            if 'Orig' not in m.name() and 'rg' not in m.name():
                meshesVtxCount[m.name()] = pm.polyEvaluate(m, v=1)
        print meshesVtxCount

        if morphFiles:
            self.hasMorphs = 1
            bsNode = ''
            bsCreated = 0
            bsEntry = 0

            for obj in morphFiles:
                speakName = obj.split('.')[0]
                speakName = 'speak_' + speakName
                pm.importFile(morphPath + obj, namespace='morph')
                morph = pm.ls('morph:*', type='mesh')[0]
                morph.rename(speakName)
                morphVtxCount = pm.polyEvaluate(morph, v=1)

                for mesh, count in meshesVtxCount.iteritems():
                    print mesh, count
                    if count == morphVtxCount:
                        rigMesh = [pm.ls(mesh, type='mesh')[0].getParent()]
                        skinCls = pm.listConnections('%s.inMesh' %
                                                     rigMesh[0].getShape())[0]

                        if not bsCreated:
                            print 'creating blendshape'
                            bsNode = pm.blendShape(rigMesh,
                                                   name='speak_BS')[0].name()
                            pm.reorderDeformers(skinCls.name(), bsNode,
                                                rigMesh[0].name())
                            pm.blendShape(bsNode,
                                          e=1,
                                          t=(rigMesh[0].name(), bsEntry,
                                             morph.name(), 1))
                            bsCreated = 1
                        else:
                            print 'adding blendshape'
                            pm.blendShape(bsNode,
                                          e=1,
                                          t=(rigMesh[0].name(), bsEntry,
                                             morph.name(), 1))
                pm.delete(morph)
                bsEntry += 1

                removeNamespace()
Пример #60
0
def get_connected_attributes_in_node_tree(node_or_nodes, node_types=None):
    """ gets all attributes, its type, the node_type and data_type

    Args:
        node_or_nodes: all connected attributes belonging to the node or nodes
        node_types: if unspecified it will only add the node of the given node_types

    Returns: dict {attribute: {"node_type": "some_node_type",
                               "data_type": "some_data_type",
                               "type": "some_attribute_type"
                               }
                  }
    """
    # find all nodes connected in tree and remove doubled
    tree_nodes = list(set(pmc.listHistory(node_or_nodes, f=True, ac=True) + pmc.listHistory(node_or_nodes, ac=True)))
    all_connected_attributes = []

    # checks if the attribute is a relevant attribute by checking
    # the node types of the nodes connected to it
    def _check_node_type(attribute):
        if node_types:
            is_relevant = False
            if attribute.nodeType() in node_types:
                dependencies = attribute.connections(p=True)
                if dependencies:
                    for dependency in dependencies:
                        if not is_relevant and dependency.nodeType() in node_types:
                            is_relevant = True
            if is_relevant:
                all_connected_attributes.append(attribute)
        else:
            all_connected_attributes.append(attribute)

    # based on all nodes in tree get all related attributes
    # do the filtering and check if the attribute is relevant
    for connection in pmc.listConnections(tree_nodes, c=True, p=True):
        source, destination = connection
        if source not in all_connected_attributes:
            _check_node_type(source)
        if destination not in all_connected_attributes:
            _check_node_type(destination)

    # subdict skeleton every keys value in attribute should have
    subdict = {"node_type": None,
               "data_type": None,
               "type": None}

    attribute_dict = {}
    for attribute in all_connected_attributes:
        _ = subdict.copy()
        _["node_type"] = attribute.nodeType()
        _["data_type"] = attribute.type()
        _["type"] = get_used_attribute_type(attribute)
        attribute_dict[attribute.name()] = _

    return attribute_dict