def getInfluenceAndWeightList( mesh, vertices = [] ):

    skinClusters = sgBFunction_dag.getNodeFromHistory( mesh, 'skinCluster' )
    if not skinClusters: return None
    
    skinCluster = skinClusters[0]
    
    fnSkinCluster = om.MFnDependencyNode( sgBFunction_dag.getMObject( skinCluster ) )
    plugWeightList = fnSkinCluster.findPlug( 'weightList' )
    
    if not vertices: vertices = [ i for i in range( plugWeightList.numElements() ) ]
    influenceAndWeightList = [ [] for i in range( len( vertices ) ) ]
    phygicalMap = [ 0 for i in range( plugWeightList.numElements() ) ]
    
    for i in range( len( vertices ) ):
        logicalIndex = vertices[i]
        plugWeights = plugWeightList[ logicalIndex ].child( 0 )
        influenceNums = []
        values = []
        for j in range( plugWeights.numElements() ):
            influenceNum = plugWeights[j].logicalIndex()
            value = plugWeights[j].asFloat()
            influenceNums.append( influenceNum )
            values.append( value )
        
        influenceAndWeightList[i] = [ influenceNums, values ]
        phygicalMap[ logicalIndex ] = i
        
    return influenceAndWeightList, phygicalMap
Esempio n. 2
0
 def __init__(self, skinCluster ):
     
     self.maxJointIndices = om.MIntArray()
     self.maxJointDagPath = om.MDagPathArray()
     
     fnSkinCluster = om.MFnDependencyNode( sgBFunction_dag.getMObject( skinCluster ) )
     self.plugMatrix = fnSkinCluster.findPlug( 'matrix' )
     plugWeightList = fnSkinCluster.findPlug( 'weightList' )
     
     self.existConnectJoints = []
     logicalIndexMax = self.plugMatrix[ self.plugMatrix.numElements()-1 ].logicalIndex()
     
     self.jointLogicalIndexMap = [ -1 for i in range( logicalIndexMax+1 ) ]
     
     for i in range( self.plugMatrix.numElements() ):
         connection = om.MPlugArray()
         self.plugMatrix[i].connectedTo( connection, True, False )
         if connection.length():
             self.existConnectJoints.append( connection[0].node() )
             self.jointLogicalIndexMap[ self.plugMatrix[i].logicalIndex() ] = i
     
     self.maxJointIndices = om.MIntArray()
     self.maxJointIndices.setLength( plugWeightList.numElements() )
     for i in range( plugWeightList.numElements() ):
         plugWeights = plugWeightList[i].child( 0 )
 
         maxWeight = plugWeights[0].asFloat()
         mwJointIndex = plugWeights[0].logicalIndex()
         for j in range( 1, plugWeights.numElements() ):
             jointIndex = plugWeights[j].logicalIndex()
             cuWeight = plugWeights[j].asFloat()
             if cuWeight > maxWeight:
                 maxWeight = cuWeight
                 mwJointIndex = jointIndex
         self.maxJointIndices.set( mwJointIndex, i )
def getInfluenceAndWeightList(mesh, vertices=[]):

    skinClusters = sgBFunction_dag.getNodeFromHistory(mesh, 'skinCluster')
    if not skinClusters: return None

    skinCluster = skinClusters[0]

    fnSkinCluster = om.MFnDependencyNode(
        sgBFunction_dag.getMObject(skinCluster))
    plugWeightList = fnSkinCluster.findPlug('weightList')

    if not vertices:
        vertices = [i for i in range(plugWeightList.numElements())]
    influenceAndWeightList = [[] for i in range(len(vertices))]
    phygicalMap = [0 for i in range(plugWeightList.numElements())]

    for i in range(len(vertices)):
        logicalIndex = vertices[i]
        plugWeights = plugWeightList[logicalIndex].child(0)
        influenceNums = []
        values = []
        for j in range(plugWeights.numElements()):
            influenceNum = plugWeights[j].logicalIndex()
            value = plugWeights[j].asFloat()
            influenceNums.append(influenceNum)
            values.append(value)

        influenceAndWeightList[i] = [influenceNums, values]
        phygicalMap[logicalIndex] = i

    return influenceAndWeightList, phygicalMap
Esempio n. 4
0
def pickOutJoint( targets ):
    
    import sgBFunction_dag
    
    for target in targets:
        targetH = sgBFunction_dag.getParents( target )
        targetH.append( target )
        children = cmds.listRelatives( target, c=1, ad=1 )
        children.reverse()
        targetH += children
        
        oTargetH = []
        oTarget = om.MObject()
        for h in targetH:
            oTargetH.append( sgBFunction_dag.getMObject( h ) )
            if h == target: oTarget = oTargetH[-1]
        
        for i in range( len( oTargetH ) ):
            if oTarget == oTargetH[i]:
                fnChild = None
                fnParent = None
                fnTarget = om.MFnDagNode( oTargetH[i] )
                if not i == 0:
                    fnParent = om.MFnDagNode( oTargetH[i-1] )
                if not i == len( oTargetH ):
                    fnChild = om.MFnDagNode( oTargetH[i+1] )
                
                if fnChild:
                    if fnParent:
                        cmds.parent( fnChild.fullPathName(), fnParent.fullPathName() )
                    else:
                        cmds.parent( fnChild.fullPathName(), w=1 )
                
                cmds.delete( fnTarget.fullPathName() )
Esempio n. 5
0
def setKeyCurve(keyCurve, targetCurve, objBaseMatrix=None):

    import sgBFunction_dag
    import sgBFunction_base

    sgBFunction_base.autoLoadPlugin('sgHair')

    nodes = sgBFunction_dag.getNodeFromHistory(targetCurve, 'sgHair_keyCurve')
    if not nodes:
        node = cmds.deformer(targetCurve, type='sgHair_keyCurve')[0]
        cmds.connectAttr('time1.outTime', node + '.time')
        if objBaseMatrix:
            mm = cmds.createNode('multMatrix')
            cmds.connectAttr(objBaseMatrix + '.wm', mm + '.i[0]')
            cmds.connectAttr(targetCurve + '.wim', mm + '.i[1]')
            cmds.connectAttr(mm + '.o', node + '.baseLocalMatrix')
    else:
        node = nodes[0]

    fnNode = om.MFnDependencyNode(sgBFunction_dag.getMObject(node))

    cuTime = cmds.currentTime(q=1)
    plugKeys = fnNode.findPlug('keys')

    targetIndex = 0
    for i in range(plugKeys.numElements()):
        plugKey = plugKeys[i]

        plugFrame = plugKey.child(0)
        timeValue = plugFrame.asMTime().value()

        if cuTime == timeValue:
            targetIndex = plugKey.logicalIndex()
            break

        if plugKey.logicalIndex() >= targetIndex:
            targetIndex = plugKey.logicalIndex() + 1

    if objBaseMatrix:
        import sgBFunction_convert
        mtxObj = cmds.getAttr(objBaseMatrix + '.wm')
        mtxInvCurve = cmds.getAttr(keyCurve + '.wim')

        mMtxObj = sgBFunction_convert.convertMatrixToMMatrix(mtxObj)
        mMtxInvCurve = sgBFunction_convert.convertMatrixToMMatrix(mtxInvCurve)

        mMtxLocal = mMtxObj * mMtxInvCurve
        mtxLocal = sgBFunction_convert.convertMMatrixToMatrix(mMtxLocal)
        cmds.setAttr(node + '.keys[%d].baseMatrix' % targetIndex,
                     mtxLocal,
                     type='matrix')
    cmds.setAttr(node + '.keys[%d].keyframe' % targetIndex, cuTime)
    keyCurveShape = sgBFunction_dag.getShape(keyCurve)
    if not cmds.isConnected(keyCurveShape + '.local',
                            node + '.keys[%d].inputCurve' % targetIndex):
        cmds.connectAttr(keyCurveShape + '.local',
                         node + '.keys[%d].inputCurve' % targetIndex,
                         f=1)
    '''
def getPlugMatrix( mesh ):
    
    skinCluster = getSkinClusterFromMesh( mesh )
    if not skinCluster: return None
    skinCluster = skinCluster[0]
    fnSkinCluster = om.MFnDependencyNode( sgBFunction_dag.getMObject( skinCluster ) )
    
    return fnSkinCluster.findPlug( 'matrix' )
def getPlugBindPre(mesh):

    skinCluster = getSkinClusterFromMesh(mesh)
    if not skinCluster: return None
    skinCluster = skinCluster[0]
    fnSkinCluster = om.MFnDependencyNode(
        sgBFunction_dag.getMObject(skinCluster))

    return fnSkinCluster.findPlug('bindPreMatrix')
Esempio n. 8
0
 def buildMesh2( self ):
     
     numVertices, numPolygons, verticesPoints, verticesCounts, verticesIndices = self.getBuildMeshInfo2()
     
     tr = cmds.createNode( 'transform' )
     trObj = sgBFunction_dag.getMObject( tr )
     
     fnMesh = om.MFnMesh()
     fnMesh.create( numVertices, numPolygons, verticesPoints, verticesCounts, verticesIndices, trObj )
     return tr
Esempio n. 9
0
 def setJointNum( self, topJoint, endJoint, num, equally ):
     
     import sgBFunction_dag
     import maya.OpenMaya as om
     
     jntFnH = [ None for i in self.jntH ]
     
     sels = cmds.ls( sl=1 )
     
     originLength = len( jntFnH )
     for i in range( originLength ):
         jntFnH[i] = om.MFnDagNode( sgBFunction_dag.getMObject( self.jntH[i] ) )
     
     diff = num - originLength
     if diff < 0:
         for jntFn in jntFnH[diff-1:-1]:
             jntChildren = cmds.listRelatives( jntFn.fullPathName(), c=1, f=1 )
             for child in jntChildren:
                 cmds.parent( child, w=1 )
             cmds.delete( jntFn.fullPathName() )
         jntFnH = jntFnH[:diff-1]+[jntFnH[-1]]
         cmds.parent( jntFnH[-1].fullPathName(), jntFnH[-2].fullPathName() )
     elif diff > 0:
         cmds.select( jntFnH[-2].fullPathName() )
         rad = cmds.getAttr( jntFnH[-2].fullPathName()+'.radius' )
         for i in range( diff ):
             jntFnH.insert( -1, om.MFnDagNode(sgBFunction_dag.getMObject( cmds.joint( rad=rad ) )) )
         cmds.parent( jntFnH[-1].fullPathName(), jntFnH[-2].fullPathName() )
     
     positions = self.getPositionFromCurve( num, equally )
     
     for i in range( 1, len( jntFnH )-1 ):
         cmds.move( positions[i].x, positions[i].y, positions[i].z, jntFnH[i].fullPathName(), ws=1, pcp=1 )
     
     self.setEditMode( topJoint, endJoint )
     self.setGlobalValue( self.getGlobalValue() )
     
     if sels:
         existObjs = []
         for sel in sels:
             if cmds.objExists( sel ):
                 existObjs.append( sel )
         cmds.select( existObjs )
Esempio n. 10
0
def setKeyCurve( keyCurve, targetCurve, objBaseMatrix = None ):
    
    import sgBFunction_dag
    import sgBFunction_base
    
    sgBFunction_base.autoLoadPlugin( 'sgHair' )
    
    nodes = sgBFunction_dag.getNodeFromHistory( targetCurve, 'sgHair_keyCurve' )
    if not nodes:
        node = cmds.deformer( targetCurve, type= 'sgHair_keyCurve' )[0]
        cmds.connectAttr( 'time1.outTime', node+'.time' )
        if objBaseMatrix:
            mm = cmds.createNode( 'multMatrix' )
            cmds.connectAttr( objBaseMatrix+'.wm', mm+'.i[0]' )
            cmds.connectAttr( targetCurve+'.wim', mm+'.i[1]' )
            cmds.connectAttr( mm+'.o', node+'.baseLocalMatrix' )
    else:
        node = nodes[0]
    
    fnNode = om.MFnDependencyNode( sgBFunction_dag.getMObject( node ) )
    
    cuTime   = cmds.currentTime( q=1 )
    plugKeys = fnNode.findPlug( 'keys' )
    
    targetIndex = 0
    for i in range( plugKeys.numElements() ):
        plugKey = plugKeys[i]
        
        plugFrame = plugKey.child( 0 )
        timeValue = plugFrame.asMTime().value()
        
        if cuTime == timeValue:
            targetIndex = plugKey.logicalIndex()
            break
        
        if plugKey.logicalIndex() >= targetIndex:
            targetIndex = plugKey.logicalIndex() + 1
    
    if objBaseMatrix:
        import sgBFunction_convert
        mtxObj = cmds.getAttr( objBaseMatrix+'.wm' )
        mtxInvCurve = cmds.getAttr( keyCurve+'.wim' )
        
        mMtxObj = sgBFunction_convert.convertMatrixToMMatrix( mtxObj )
        mMtxInvCurve = sgBFunction_convert.convertMatrixToMMatrix( mtxInvCurve )
        
        mMtxLocal = mMtxObj * mMtxInvCurve
        mtxLocal = sgBFunction_convert.convertMMatrixToMatrix( mMtxLocal )
        cmds.setAttr( node+'.keys[%d].baseMatrix' % targetIndex, mtxLocal, type='matrix' )
    cmds.setAttr( node+'.keys[%d].keyframe' % targetIndex, cuTime )
    keyCurveShape = sgBFunction_dag.getShape( keyCurve )
    if not cmds.isConnected( keyCurveShape+'.local', node+'.keys[%d].inputCurve' % targetIndex ):
        cmds.connectAttr( keyCurveShape+'.local', node+'.keys[%d].inputCurve' % targetIndex, f=1 )
    
    '''
Esempio n. 11
0
def getKnots( target ):
    
    import sgBFunction_dag
    target = sgBFunction_dag.getShape( target )
    
    fnCurve = om.MFnNurbsCurve( sgBFunction_dag.getMObject( target ) )
    
    dArr = om.MDoubleArray()
    fnCurve.getKnots( dArr )
    
    return dArr
Esempio n. 12
0
def getKnots(target):

    import sgBFunction_dag
    target = sgBFunction_dag.getShape(target)

    fnCurve = om.MFnNurbsCurve(sgBFunction_dag.getMObject(target))

    dArr = om.MDoubleArray()
    fnCurve.getKnots(dArr)

    return dArr
 def replace(self, *args ):
     
     import sgBFunction_dag
     
     sourceName = cmds.textField( WinA_Global.fld_source, q=1, tx=1 )
     targetName = cmds.textField( WinA_Global.fld_target, q=1, tx=1 )
     isNamespace = cmds.checkBox( WinA_Global.chk_isNamespace, q=1, v=1 )
     
     if not sourceName: return None
     
     if isNamespace:
         targets = cmds.ls()
         fnTargets = []
         for target in targets:
             if target[:len(sourceName)] != sourceName: continue
             if cmds.attributeQuery( 'wm', node=target, ex=1 ):
                 fnTarget = om.MFnDagNode( sgBFunction_dag.getMDagPath( target ) )
             else:
                 fnTarget = om.MFnDependencyNode( sgBFunction_dag.getMObject( target ) )
             fnTargets.append( fnTarget )
         for fnTarget in fnTargets:
             if type( fnTarget ) == type( om.MFnDagNode() ):
                 cmds.rename( fnTarget.fullPathName(), targetName + fnTarget.name()[len(sourceName):] )
             else:
                 cmds.rename( fnTarget.name(), targetName + fnTarget.name()[len(sourceName):] )
         
     else:
         targets = cmds.ls()
         fnTargets = []
         for target in targets:
             if target.find( sourceName ) == -1: continue
             if cmds.attributeQuery( 'wm', node=target, ex=1 ):
                 fnTarget = om.MFnDagNode( sgBFunction_dag.getMDagPath( target ) )
             else:
                 fnTarget = om.MFnDependencyNode( sgBFunction_dag.getMObject( target ) )
             fnTargets.append( fnTarget )
         for fnTarget in fnTargets:
             if type( fnTarget ) == type( om.MFnDagNode() ):
                 cmds.rename( fnTarget.fullPathName(), fnTarget.name().replace( sourceName, targetName ) )
             else:
                 cmds.rename( fnTarget.name(), fnTarget.name().replace( sourceName, targetName ) )
def copyFollicleAttribute( *args ):
    
    sels = cmds.ls( sl=1 )
    
    others = sels[:-1]
    first = sels[-1]
    
    import sgBModel_attribute
    import sgBFunction_dag
    import sgBFunction_attribute
    
    first = sgBFunction_dag.getShape( first )
    if cmds.nodeType( first ) == 'nurbsCurve':
        first = sgBFunction_dag.getFollicleFromCurve( first )

    for i in range( len( others ) ):
        other = sgBFunction_dag.getShape( others[i] )
        if cmds.nodeType( other ) == 'nurbsCurve':
            other = sgBFunction_dag.getFollicleFromCurve( other )
        others[i] = other
    
    follicleRampAttrList = sgBModel_attribute.follicleRampAttrList

    follicleNormalAttrList = sgBModel_attribute.follicleNormalAttrList
    
    fnNode = om.MFnDependencyNode( sgBFunction_dag.getMObject( first ) )
    
    rampAttrNames = []
    rampValues    = []
    
    for rampAttr in follicleRampAttrList:
        print "node name : ", fnNode.name()
        plugAttr = fnNode.findPlug( rampAttr )
        print rampAttr
        
        for other in others:
            sgBFunction_attribute.removeMultiInstances( other, rampAttr )
         
        for j in range( plugAttr.numElements() ):
            rampAttrNames.append( plugAttr[j].name().split( '.' )[-1] )
            rampValues.append( cmds.getAttr( plugAttr[j].name() )[0] )
    
    for other in others:
        for i in range( len( rampAttrNames ) ):
            cmds.setAttr( other+'.'+rampAttrNames[i], *rampValues[i] )
    
    for normalAttr in follicleNormalAttrList:
        attrValue = cmds.getAttr( first+'.'+normalAttr )
        for other in others:
            try:cmds.setAttr( other+'.'+normalAttr, attrValue )
            except:pass
Esempio n. 15
0
 def setJointNum( self, topJoint, endJoint, num, equally=True ):
     
     import sgBFunction_dag
     
     self.editCurveByJoints()
     
     jntFnH = [ None for i in self.jntH ]
     
     originLength = len( jntFnH )
     for i in range( originLength ):
         jntFnH[i] = om.MFnDagNode( sgBFunction_dag.getMObject( self.jntH[i] ) )
     
     diff = num - originLength
     if diff < 0:
         for jntFn in jntFnH[diff-1:-1]:
             jntChildren = cmds.listRelatives( jntFn.fullPathName(), c=1, f=1 )
             if not jntChildren: continue
             for child in jntChildren:
                 cmds.parent( child, w=1 )
             cmds.delete( jntFn.fullPathName() )
         jntFnH = jntFnH[:diff-1]+[jntFnH[-1]]
         cmds.parent( jntFnH[-1].fullPathName(), jntFnH[-2].fullPathName() )
     elif diff > 0:
         cmds.select( jntFnH[-2].fullPathName() )
         rad = cmds.getAttr( jntFnH[-2].fullPathName()+'.radius' )
         for i in range( diff ):
             jntFnH.insert( -1, om.MFnDagNode(sgBFunction_dag.getMObject( cmds.joint( rad=rad ) )) )
         cmds.parent( jntFnH[-1].fullPathName(), jntFnH[-2].fullPathName() )
     
     positions = self.getPositionFromCurve( num, equally )
     
     for i in range( 1, len( jntFnH )-1 ):
         cmds.move( positions[i].x, positions[i].y, positions[i].z, jntFnH[i].fullPathName(), ws=1, pcp=1 )
     
     self.updateJointH( topJoint )
     
     return topJoint
Esempio n. 16
0
def replaceRivetMesh( source, target ):
    
    sourceShape = cmds.listRelatives( source, s=1, f=1 )[0]
    targetShape = cmds.listRelatives( target, s=1, f=1 )[0]
    
    nodes = list( set( cmds.listConnections( sourceShape, d=1, s=0, type='sgMatrixFromVertices' ) ) )
    
    import sgBFunction_dag
    
    fnSourceMesh  = om.MFnMesh( sgBFunction_dag.getMDagPath( sourceShape ) )
    fnTargetMesh = om.MFnMesh( sgBFunction_dag.getMDagPath( targetShape ) )
    
    sourceMeshPoints = om.MPointArray()
    targetMeshPoints = om.MPointArray()
    fnSourceMesh.getPoints( sourceMeshPoints )
    fnTargetMesh.getPoints( targetMeshPoints )
    
    intersector = om.MMeshIntersector()
    intersector.create( fnTargetMesh.object() )
    
    for node in nodes:
        fnNode = om.MFnDependencyNode( sgBFunction_dag.getMObject( node ) )
        plugVerticeId = fnNode.findPlug( 'verticeId' )
        
        pointOnMesh = om.MPointOnMesh()
        for i in range( plugVerticeId.numElements() ):
            logicalIndex = plugVerticeId[i].logicalIndex()
            pointSource = sourceMeshPoints[ logicalIndex ]
            
            intersector.getClosestPoint( pointSource, pointOnMesh )
            
            faceIndex = pointOnMesh.faceIndex()
            indicesVertices = om.MIntArray()
            fnTargetMesh.getPolygonVertices( faceIndex, indicesVertices )
            
            minDist = 100000.0
            closeIndex = indicesVertices[0]
            for j in range( indicesVertices.length() ):
                pointTarget = targetMeshPoints[ indicesVertices[j] ]
                dist = pointTarget.distanceTo( pointSource )
                if dist < minDist:
                    minDist = dist
                    closeIndex = indicesVertices[j]
            
            print plugVerticeId[i].name(), closeIndex
            cmds.setAttr( plugVerticeId[i].name(), closeIndex )

        cmds.connectAttr( targetShape+'.outMesh', node+'.inputMesh', f=1 )
        cmds.connectAttr( targetShape+'.worldMatrix[0]', node+'.inputMeshMatrix', f=1 )
Esempio n. 17
0
    def buildMesh( self ):
        
        newVerticeCounts = om.MIntArray()
        newVerticesIndices = om.MIntArray()

        self.indicesCheckedPolygon.sort()
        self.indicesCheckedVertices.sort()
        
        newPoints = om.MPointArray()
        newPoints.setLength( len( self.indicesCheckedVertices ) )
        
        origPoints = om.MPointArray()
        self.fnMesh.getPoints( origPoints )
        
        for i in range( newPoints.length() ):
            checkedIndex = self.indicesCheckedVertices[i]
            checkedPoint = origPoints[ checkedIndex ] * self.meshMatrix
            newPoints.set( checkedPoint, i )
        
        indicesCheckedVerticesMap = [ -1 for i in range( self.fnMesh.numVertices() ) ]
        for i in range( len( self.indicesCheckedVertices ) ):
            checkedVtxIndex = self.indicesCheckedVertices[i]
            indicesCheckedVerticesMap[ checkedVtxIndex ] = i

        for i in range( len( self.indicesCheckedPolygon ) ):
            polygonIndex = self.indicesCheckedPolygon[i]
            indices = om.MIntArray()
            self.fnMesh.getPolygonVertices( polygonIndex, indices )
            for j in range( indices.length() ):
                checkedVtxIndex = indices[j]
                vtxIndex = indicesCheckedVerticesMap[ checkedVtxIndex ]
                newVerticesIndices.append( vtxIndex )
            newVerticeCounts.append( indices.length() )
        
        fnMesh = om.MFnMesh()
        
        tr = cmds.createNode( 'transform' )
        trObj = sgBFunction_dag.getMObject( tr )
        
        fnMesh.create( len(self.indicesCheckedVertices), len(self.indicesCheckedPolygon), newPoints, newVerticeCounts, newVerticesIndices, trObj )
        
        return tr
Esempio n. 18
0
def createShadingEngine( name ):
    
    linker = 'lightLinker1'
    partition = 'renderPartition'
    
    import maya.OpenMaya as om
    
    fnLinker = om.MFnDependencyNode( sgBFunction_dag.getMObject( linker ) )
    
    plugLink = fnLinker.findPlug( 'link' )
    
    linkIndex = plugLink.numElements()
    
    shadingEngine = cmds.shadingNode( 'shadingEngine', n=name, asUtility=1 )
    
    cmds.connectAttr( shadingEngine+'.message', linker+'.link[%d].object' % linkIndex, f=1 )
    cmds.connectAttr( shadingEngine+'.message', linker+'.shadowLink[%d].shadowObject' % linkIndex, f=1 )
    cmds.connectAttr( shadingEngine+'.partition', partition+'.sets[%d]' % linkIndex, f=1 )
    
    return shadingEngine
Esempio n. 19
0
def getAttrSourceConnection(attr):

    cons = cmds.listConnections(attr, s=1, d=0, p=1, c=1)
    if cons: return cons

    import sgBFunction_dag
    node, attr = attr.split('.')

    fnNode = om.MFnDependencyNode(sgBFunction_dag.getMObject(node))
    plugAttr = fnNode.findPlug(attr)

    try:
        numChildren = plugAttr.numChildren()
    except:
        return []

    cons = []
    for i in range(numChildren):
        cPlugAttr = plugAttr.child(i)
        attrName = om.MFnAttribute(cPlugAttr.attribute()).name()
        cons += getAttrSourceConnection(node + '.' + attrName)
    return cons
Esempio n. 20
0
def getAttrSourceConnection( attr ):
    
    cons = cmds.listConnections( attr, s=1, d=0, p=1, c=1 )
    if cons: return cons
    
    import sgBFunction_dag
    node, attr = attr.split( '.' )
    
    fnNode = om.MFnDependencyNode( sgBFunction_dag.getMObject( node ) )
    plugAttr = fnNode.findPlug( attr )
    
    try:
        numChildren = plugAttr.numChildren()
    except:
        return []
    
    cons = []
    for i in range( numChildren ):
        cPlugAttr = plugAttr.child( i )
        attrName = om.MFnAttribute( cPlugAttr.attribute() ).name()
        cons += getAttrSourceConnection( node+'.'+attrName )
    return cons
Esempio n. 21
0
    def getMeshAndIndices(targetCurve):
        curveShape = sgBFunction_dag.getShape(targetCurve)

        inputNode = curveShape
        crvToPointNode = None
        mtxFromVtxNode = None
        num = 0
        while True:
            num += 1
            if num >= 100: break
            cons = cmds.listConnections(inputNode, s=1, d=0, p=1, c=1)
            if not cons: return None
            outputCon = cons[1]
            node = outputCon.split('.')[0]
            targetNodeType = cmds.nodeType(node)
            if targetNodeType == 'sgCurveFromPoints':
                crvToPointNode = node
                inputNode = node
                continue
            if targetNodeType == 'sgMatrixFromVertices':
                mtxFromVtxNode = node
                break
            inputNode = node

        mesh = cmds.listConnections(mtxFromVtxNode + '.inputMesh', s=1, d=0)[0]

        print "crvToPointNode : ", crvToPointNode
        fnNode = om.MFnDependencyNode(
            sgBFunction_dag.getMObject(crvToPointNode))
        plugInputs = fnNode.findPlug('input')

        indices = []
        for i in range(plugInputs.numElements()):
            connections = om.MPlugArray()
            plugInputPoint = plugInputs[i].child(1)
            plugInputPoint.connectedTo(connections, True, False)
            indices.append(connections[0].logicalIndex())

        return mesh, indices
Esempio n. 22
0
    def getMeshAndIndices( targetCurve ):
        curveShape = sgBFunction_dag.getShape( targetCurve )
        
        inputNode = curveShape
        crvToPointNode = None
        mtxFromVtxNode = None
        num = 0
        while True:
            num += 1
            if num >= 100: break
            cons = cmds.listConnections( inputNode, s=1, d=0, p=1, c=1 )
            if not cons: return None
            outputCon = cons[1]
            node = outputCon.split( '.' )[0]
            targetNodeType = cmds.nodeType( node )
            if targetNodeType == 'sgCurveFromPoints':
                crvToPointNode = node
                inputNode = node
                continue
            if targetNodeType == 'sgMatrixFromVertices':
                mtxFromVtxNode = node
                break
            inputNode = node

        mesh = cmds.listConnections( mtxFromVtxNode+'.inputMesh', s=1, d=0 )[0]
        
        print "crvToPointNode : ", crvToPointNode
        fnNode = om.MFnDependencyNode( sgBFunction_dag.getMObject( crvToPointNode ) )
        plugInputs = fnNode.findPlug( 'input' )
        
        indices = []
        for i in range( plugInputs.numElements() ):
            connections = om.MPlugArray()
            plugInputPoint = plugInputs[i].child( 1 )
            plugInputPoint.connectedTo( connections, True, False )
            indices.append( connections[0].logicalIndex() )
        
        return mesh, indices
Esempio n. 23
0
def combineSkinCluster(skinedObjs):

    import sgBFunction_dag

    numVertices = None
    for skinedObj in skinedObjs:
        objShape = sgBFunction_dag.getShape(skinedObj)
        fnMesh = om.MFnMesh(sgBFunction_dag.getMDagPath(objShape))
        if not numVertices:
            numVertices = fnMesh.numVertices()
        else:
            if numVertices != fnMesh.numVertices():
                cmds.error("Selected meshs not same objects")

    skinJoints = []
    weightList = [[] for i in range(numVertices)]
    for skinedObj in skinedObjs:

        skinCluster = sgBFunction_dag.getNodeFromHistory(
            skinedObj, 'skinCluster')
        if not skinCluster: continue

        skinCluster = skinCluster[0]

        fnNode = om.MFnDependencyNode(sgBFunction_dag.getMObject(skinCluster))

        plugMatrix = fnNode.findPlug('matrix')

        plugMatrixMaxLogicalIndex = 0
        for i in range(plugMatrix.numElements()):
            logicalIndex = plugMatrix[i].logicalIndex()
            if logicalIndex > plugMatrixMaxLogicalIndex:
                plugMatrixMaxLogicalIndex = logicalIndex

        connections = om.MPlugArray()
        skinedJointIndices = []
        origSkinedJointIndicesMap = [
            -1 for i in range(plugMatrixMaxLogicalIndex + 1)
        ]
        for i in range(plugMatrix.numElements()):

            plugMatrix[i].connectedTo(connections, True, False)
            if not connections.length():
                continue

            skinJointName = om.MFnDagNode(connections[0].node()).fullPathName()

            if not skinJointName in skinJoints:
                skinJoints.append(skinJointName)

            jntIndex = skinJoints.index(skinJointName)
            origSkinedJointIndicesMap[plugMatrix[i].logicalIndex()] = jntIndex
            skinedJointIndices.append(jntIndex)

        plugWeightList = fnNode.findPlug('weightList')

        for i in range(plugWeightList.numElements()):

            plugWeights = plugWeightList[i].child(0)
            for j in range(plugWeights.numElements()):

                logicalIndex = plugWeights[j].logicalIndex()
                weightValue = plugWeights[j].asFloat()
                jntIndex = origSkinedJointIndicesMap[logicalIndex]

                weightList[i].append([jntIndex, weightValue])

    newMesh = cmds.createNode('mesh')
    srcShape = sgBFunction_dag.getShape(skinedObjs[0])
    newMeshObj = sgBFunction_dag.getParent(newMesh)
    cmds.connectAttr(srcShape + '.outMesh', newMesh + '.inMesh')
    cmds.refresh()
    cmds.disconnectAttr(srcShape + '.outMesh', newMesh + '.inMesh')
    node = cmds.deformer(newMeshObj, type='skinCluster')[0]

    for i in range(len(skinJoints)):
        cmds.connectAttr(skinJoints[i] + '.wm', node + '.matrix[%d]' % i)
        bindPreMatrix = cmds.getAttr(skinJoints[i] + '.wim')
        cmds.setAttr(node + '.bindPreMatrix[%d]' % i,
                     bindPreMatrix,
                     type='matrix')

    for i in range(len(weightList)):
        for logicalIndex, value in weightList[i]:
            cmds.setAttr(
                node + '.weightList[%d].weights[%d]' % (i, logicalIndex),
                value)

    cmds.skinPercent(node, normalize=True)
Esempio n. 24
0
def weightHammerCurve( targets ):
    import maya.OpenMaya as om
    import sgBFunction_dag
    import sgCFnc_dag
    import sgModelDg
    
    def getWeights( plug ):
        childPlug = plug.child(0)
        numElements = childPlug.numElements()
        indicesAndValues = []
        for i in range( numElements ):
            logicalIndex = childPlug[i].logicalIndex()
            value        = childPlug[i].asFloat()
            indicesAndValues.append( [ logicalIndex, value ] )
        return indicesAndValues
    
    def getMixWeights( first, second, rate ):
        
        invRate = 1.0-rate
        
        print first
        print second
        
        firstMaxIndex = first[-1][0]
        secondMaxIndex = second[-1][0]
        maxIndex = firstMaxIndex+1
        
        if firstMaxIndex < secondMaxIndex:
            maxIndex = secondMaxIndex+1
        
        firstLogicalMap  = [ False for i in range( maxIndex ) ]
        secondLogicalMap = [ False for i in range( maxIndex ) ]
        
        for index, value in first:
            firstLogicalMap[ index ] = True
            
        for index, value in second:
            secondLogicalMap[ index ] = True
        
        returnTargets = []
        
        for index, value in first:
            returnTargets.append( [index, invRate * value] )
        for index, value in second:
            if firstLogicalMap[ index ]:
                for i in range( len( returnTargets ) ):
                    wIndex = returnTargets[i][0]
                    if wIndex == index:
                        returnTargets[i][1] += rate * value
                        break
            else:
                returnTargets.append( [index, rate * value] )
        return returnTargets
    
    def clearArray( targetPlug ):
        plugChild = targetPlug.child( 0 )
        targetInstances = []
        for i in range( plugChild.numElements() ):
            targetInstances.append( plugChild[i].name() )
        targetInstances.reverse()
        for i in range( len( targetInstances ) ):
            cmds.removeMultiInstance( targetInstances[i] )
        
    
    node = targets[0].split( '.' )[0]
    
    skinClusterNodes = sgBFunction_dag.getNodeFromHistory( node, 'skinCluster' )
    if not skinClusterNodes: return None
    
    fnSkinCluster = om.MFnDependencyNode( sgBFunction_dag.getMObject( skinClusterNodes[0] ) )
    plugWeightList = fnSkinCluster.findPlug( 'weightList' )
    
    cmds.select( targets )
    for dagPath, uArr, vArr, wArr in sgCFnc_dag.getMDagPathAndComponent():
        
        fnCurve = om.MFnNurbsCurve( dagPath )
        startNum = 0
        lastNum = fnCurve.numCVs()-1
        
        if uArr[-1] == lastNum:
            pass
        elif uArr[0] == startNum:
            pass
        elif uArr[0] == startNum and uArr[-1] == lastNum:
            pass
        else:
            weightStart = getWeights( plugWeightList[ uArr[0]-1 ] )
            weightEnd   = getWeights( plugWeightList[ uArr[-1]+1 ] )
            
            length = uArr.length()
            for i in range( uArr.length() ):
                clearArray( plugWeightList[ uArr[i] ] )
                plugWeightListEmelent = plugWeightList.elementByLogicalIndex( uArr[i] )
                
                rate = float( i+1 ) / (length+2)
                weights = getMixWeights( weightStart, weightEnd, rate )
                for index, value in weights:
                    targetPlug = plugWeightListEmelent.child(0).elementByLogicalIndex( index )
                    cmds.setAttr( targetPlug.name(), value )
        cmds.skinPercent( skinClusterNodes[0], normalize=1 )
Esempio n. 25
0
def combineSkinCluster( skinedObjs ):
    
    import sgBFunction_dag
    
    numVertices = None
    for skinedObj in skinedObjs:
        objShape = sgBFunction_dag.getShape( skinedObj )
        fnMesh = om.MFnMesh( sgBFunction_dag.getMDagPath( objShape ) )
        if not numVertices:
            numVertices = fnMesh.numVertices()
        else:
            if numVertices != fnMesh.numVertices():
                cmds.error( "Selected meshs not same objects" )
    
    skinJoints = []
    weightList = [ [] for i in range( numVertices ) ]
    for skinedObj in skinedObjs:
        
        skinCluster = sgBFunction_dag.getNodeFromHistory( skinedObj, 'skinCluster' )
        if not skinCluster: continue
        
        skinCluster = skinCluster[0]
        
        fnNode = om.MFnDependencyNode( sgBFunction_dag.getMObject( skinCluster ) )
        
        plugMatrix = fnNode.findPlug( 'matrix' )
        
        plugMatrixMaxLogicalIndex = 0
        for i in range( plugMatrix.numElements() ):
            logicalIndex = plugMatrix[i].logicalIndex()
            if logicalIndex > plugMatrixMaxLogicalIndex:
                plugMatrixMaxLogicalIndex = logicalIndex 
        
        connections = om.MPlugArray()
        skinedJointIndices = []
        origSkinedJointIndicesMap = [ -1 for i in range( plugMatrixMaxLogicalIndex+1 ) ]
        for i in range( plugMatrix.numElements() ):
            
            plugMatrix[i].connectedTo( connections, True, False )
            if not connections.length():
                continue
            
            skinJointName = om.MFnDagNode( connections[0].node() ).fullPathName()
            
            if not skinJointName in skinJoints:
                skinJoints.append( skinJointName )
            
            jntIndex = skinJoints.index( skinJointName )
            origSkinedJointIndicesMap[ plugMatrix[i].logicalIndex() ] = jntIndex
            skinedJointIndices.append( jntIndex )
    
        plugWeightList = fnNode.findPlug( 'weightList' )
        
        for i in range( plugWeightList.numElements() ):
            
            plugWeights = plugWeightList[i].child( 0 )
            for j in range( plugWeights.numElements() ):
                
                logicalIndex = plugWeights[j].logicalIndex()
                weightValue = plugWeights[j].asFloat()
                jntIndex = origSkinedJointIndicesMap[ logicalIndex ]
                
                weightList[i].append( [jntIndex, weightValue] )
    
    newMesh = cmds.createNode( 'mesh' )
    srcShape = sgBFunction_dag.getShape( skinedObjs[0] )
    newMeshObj = sgBFunction_dag.getParent( newMesh )
    cmds.connectAttr( srcShape+'.outMesh', newMesh+'.inMesh' )
    cmds.refresh()
    cmds.disconnectAttr( srcShape+'.outMesh', newMesh+'.inMesh' )
    node = cmds.deformer( newMeshObj, type='skinCluster' )[0]
    
    for i in range( len( skinJoints ) ):
        cmds.connectAttr( skinJoints[i]+'.wm', node+'.matrix[%d]' % i )
        bindPreMatrix = cmds.getAttr( skinJoints[i]+'.wim' )
        cmds.setAttr( node+'.bindPreMatrix[%d]' % i, bindPreMatrix, type='matrix' )
    
    for i in range( len( weightList ) ):
        for logicalIndex, value in weightList[i]:
            cmds.setAttr( node+'.weightList[%d].weights[%d]' %( i, logicalIndex ), value )
    
    cmds.skinPercent( node, normalize=True )
Esempio n. 26
0
def setWeightInnerPointsToTargetJoint( baseMesh, baseJoint, targetMeshs ):
    
    import sgBFunction_dag
    
    baseMeshShape = sgBFunction_dag.getShape( baseMesh )
    dagPathBaseMesh = sgBFunction_dag.getMDagPath( baseMeshShape )
    mtxBaseMesh = dagPathBaseMesh.inclusiveMatrix()
    headIntersector = om.MMeshIntersector()
    headIntersector.create( dagPathBaseMesh.node() )
    
    targetMeshs = cmds.ls( sl=1 )
    
    for targetMesh in targetMeshs:
    
        skinNodes = sgBFunction_dag.getNodeFromHistory( targetMesh ,'skinCluster')
        if not skinNodes: continue
        
        skinNode = skinNodes[0]
        fnSkinNode = om.MFnDependencyNode( sgBFunction_dag.getMObject( skinNode ) )
        
        joints = cmds.listConnections( skinNode+'.matrix', s=1, d=0 )
        if not baseJoint in joints: continue
        indexInfluence = joints.index( baseJoint )
        
        plugWeightList = fnSkinNode.findPlug( 'weightList' )
        
        targetMeshShape = sgBFunction_dag.getShape( targetMesh )
        dagPathTargetMesh = sgBFunction_dag.getMDagPath( targetMeshShape )
        fnTargetMesh = om.MFnMesh( dagPathTargetMesh )
        
        mtxTarget = dagPathTargetMesh.inclusiveMatrix()
        mtxToBase = mtxTarget * mtxBaseMesh.inverse()
        
        numVertices = fnTargetMesh.numVertices()
        pointsTarget = om.MPointArray()
        fnTargetMesh.getPoints( pointsTarget )
        
        pointOnMesh = om.MPointOnMesh()
        
        targetVertices = []
        
        for i in range( numVertices ):
            pointLocal = pointsTarget[i] * mtxToBase
            headIntersector.getClosestPoint( pointLocal, pointOnMesh )
            
            point = pointOnMesh.getPoint()
            normal = om.MVector( pointOnMesh.getNormal() )
            
            vDir = om.MVector( pointLocal ) - om.MVector( point )
            
            if vDir * normal > 0: continue
            
            plugWeights = plugWeightList[i].child( 0 )
            for j in range( plugWeights.numElements() ):
                cmds.setAttr( plugWeights.name() + "[%d]" % j, 0 )
            
            cmds.setAttr( plugWeights.name() + "[%d]" % indexInfluence, 1 )
            targetVertices.append( targetMesh+'.vtx[%d]' % i )

        cmds.select( targetVertices )
            
Esempio n. 27
0
def weightHammerCurve(targets):
    import maya.OpenMaya as om
    import sgBFunction_dag
    import sgCFnc_dag
    import sgModelDg

    def getWeights(plug):
        childPlug = plug.child(0)
        numElements = childPlug.numElements()
        indicesAndValues = []
        for i in range(numElements):
            logicalIndex = childPlug[i].logicalIndex()
            value = childPlug[i].asFloat()
            indicesAndValues.append([logicalIndex, value])
        return indicesAndValues

    def getMixWeights(first, second, rate):

        invRate = 1.0 - rate

        print first
        print second

        firstMaxIndex = first[-1][0]
        secondMaxIndex = second[-1][0]
        maxIndex = firstMaxIndex + 1

        if firstMaxIndex < secondMaxIndex:
            maxIndex = secondMaxIndex + 1

        firstLogicalMap = [False for i in range(maxIndex)]
        secondLogicalMap = [False for i in range(maxIndex)]

        for index, value in first:
            firstLogicalMap[index] = True

        for index, value in second:
            secondLogicalMap[index] = True

        returnTargets = []

        for index, value in first:
            returnTargets.append([index, invRate * value])
        for index, value in second:
            if firstLogicalMap[index]:
                for i in range(len(returnTargets)):
                    wIndex = returnTargets[i][0]
                    if wIndex == index:
                        returnTargets[i][1] += rate * value
                        break
            else:
                returnTargets.append([index, rate * value])
        return returnTargets

    def clearArray(targetPlug):
        plugChild = targetPlug.child(0)
        targetInstances = []
        for i in range(plugChild.numElements()):
            targetInstances.append(plugChild[i].name())
        targetInstances.reverse()
        for i in range(len(targetInstances)):
            cmds.removeMultiInstance(targetInstances[i])

    node = targets[0].split('.')[0]

    skinClusterNodes = sgBFunction_dag.getNodeFromHistory(node, 'skinCluster')
    if not skinClusterNodes: return None

    fnSkinCluster = om.MFnDependencyNode(
        sgBFunction_dag.getMObject(skinClusterNodes[0]))
    plugWeightList = fnSkinCluster.findPlug('weightList')

    cmds.select(targets)
    for dagPath, uArr, vArr, wArr in sgCFnc_dag.getMDagPathAndComponent():

        fnCurve = om.MFnNurbsCurve(dagPath)
        startNum = 0
        lastNum = fnCurve.numCVs() - 1

        if uArr[-1] == lastNum:
            pass
        elif uArr[0] == startNum:
            pass
        elif uArr[0] == startNum and uArr[-1] == lastNum:
            pass
        else:
            weightStart = getWeights(plugWeightList[uArr[0] - 1])
            weightEnd = getWeights(plugWeightList[uArr[-1] + 1])

            length = uArr.length()
            for i in range(uArr.length()):
                clearArray(plugWeightList[uArr[i]])
                plugWeightListEmelent = plugWeightList.elementByLogicalIndex(
                    uArr[i])

                rate = float(i + 1) / (length + 2)
                weights = getMixWeights(weightStart, weightEnd, rate)
                for index, value in weights:
                    targetPlug = plugWeightListEmelent.child(
                        0).elementByLogicalIndex(index)
                    cmds.setAttr(targetPlug.name(), value)
        cmds.skinPercent(skinClusterNodes[0], normalize=1)
 def create( *args ):
     
     import sgBFunction_dag
     
     reload( sgBFunction_mesh )
     
     sels = cmds.ls( sl=1 )
     
     baseMesh = cmds.textField( Window_Global.fld_baseMesh, q=1, tx=1 )
     detail   = cmds.intField( Window_Global.fld_detail, q=1, v=1 )
     
     base    = sgBFunction_dag.getShape( baseMesh ) 
     dagPathBase = sgBFunction_dag.getMDagPath( baseMesh )
     oBase = sgBFunction_dag.getMObject( base )
     
     baseMtx = dagPathBase.inclusiveMatrix()
     
     fnBase = om.MFnMesh()
     fnBase.setObject( dagPathBase )
     
     origPointsBase = om.MPointArray()
     multedPointsBase = om.MPointArray()
     fnBase.getPoints( origPointsBase )
     
     multedPointsBase.setLength( origPointsBase.length() )
     for i in range( multedPointsBase.length() ):
         multedPointsBase.set( origPointsBase[i]*baseMtx, i )
     fnBase.setPoints( multedPointsBase )
     
     intersector = om.MMeshIntersector()
     intersector.create( oBase )
     
     topJnts = []
     for sel in sels:
         target  = sgBFunction_dag.getShape( sel )
         
         dagPathMesh = sgBFunction_dag.getMDagPath( target )
         fnMeshTarget = om.MFnMesh( dagPathMesh )
         origPointsTarget = om.MPointArray()
         multedPointsTarget = om.MPointArray()
         fnMeshTarget.getPoints( origPointsTarget )
         
         targetMtx = dagPathMesh.inclusiveMatrix()
         multedPointsTarget.setLength( origPointsTarget.length() )
         for i in range( multedPointsTarget.length() ):
             multedPointsTarget.set( origPointsTarget[i] * targetMtx , i )
         
         minDistIndex = 0
         minDist = 100000.0
         pointOnMesh = om.MPointOnMesh()
         for i in range( multedPointsTarget.length() ):
             intersector.getClosestPoint( multedPointsTarget[i], pointOnMesh )
             pointClose = om.MPoint( pointOnMesh.getPoint() )
             dist = multedPointsTarget[i].distanceTo( pointClose )
             if dist < minDist:
                 minDist = dist
                 minDistIndex = i
                 
         maxDistIndex = 0
         maxDist = 0.0
         for i in range( multedPointsTarget.length() ):
             dist = multedPointsTarget[minDistIndex].distanceTo( multedPointsTarget[i] )
             if maxDist < dist:
                 maxDist = dist
                 maxDistIndex = i
         
         startCenter = om.MPoint( *cmds.xform( target+'.vtx[%d]' % minDistIndex, q=1, ws=1, t=1 ) )
         endCenter = om.MPoint( *cmds.xform( target+'.vtx[%d]' % maxDistIndex, q=1, ws=1, t=1 ) )
             
         jnts = sgBFunction_mesh.createJointLineFromMeshApi( dagPathMesh, startCenter, endCenter, detail )
         topJnts.append( jnts[0] )
     
     fnBase.setPoints( origPointsBase )
     
     cmds.select( topJnts )