def rotateOnXToMatchZ( self, obj, target ):
        assert isinstance(obj, pymel.core.nodetypes.Transform)
    
        helperZ = pm.createNode('transform')
        helperX = pm.createNode('transform')

        ## get helperZ,
        ## parent helperZ to target
        pm.parent( helperZ, target)    
        ##  zero helperZ, except +tz
        helperZ.translate.set( [0,0,16] )
        ######################### pm.duplicate( helperZ )  ## just to visualize debug
        ## parent helperZ to obj
        pm.parent( helperZ, obj )
        ## zero helperZ tx
        helperZ.tx.set( 0 )    
        ## make another helperX
        ## parent helperX to obj
        pm.parent( helperX, obj )
        ## move helperX only +tz, zero all else
        helperX.translate.set( [1,0,0] )
        ## unparent helper and helperX
        pm.parent( helperX, world=True )
        pm.parent( helperZ, world=True )
        ## should probably zero everything out that we can here
        obj.jointOrient.set( 0,0,0 )
        obj.rotateAxis.set( 0,0,0 )
        con = pm.aimConstraint( helperX, obj,
            worldUpType='object',
            worldUpObject=helperZ,
            aimVector=[1,0,0],
            upVector=[0,0,1],
        )
        pm.delete( con )   
        pm.delete( [helperX, helperZ] )
예제 #2
0
def importYeti(path):
    msg = ''
    try:
        yetiInfo = getYetiInfo()
        if yetiInfo:
            for yetiNode, shader in yetiInfo.items():
                if pm.objExists(yetiNode):
                    pm.delete(yetiNode)
                if pm.objExists(shader):
                    pm.delete(shader)

        if pm.objExists('yetiInfoNode'):
            yetiInfoNode = pm.PyNode('yetiInfoNode')
            yetiInfoNode.unlock()
            pm.delete(yetiInfoNode)

        cmds.file(path,
                  pr=1,
                  ignoreVersion=1,
                  i=1,
                  type="mayaBinary",
                  mergeNamespacesOnClash=False,
                  options="v=0;")
        #pm.importFile(path)
        if not pm.objExists('yetiInfoNode'):
            msg += u'"yetiInfoNode"가 존재 하지 않습니다.'
    except:
        return msg

    if not pm.objExists('time1'):
        timeNode = pm.createNode('time', n='time1')

    timeNode = pm.PyNode('time1')

    yetiInfoNode = pm.PyNode('yetiInfoNode')
    yetiInfo = json.loads(yetiInfoNode.yetiInfo.get())

    for yetiNodeName, shaderName in yetiInfo.items():
        try:
            yetiNode = pm.createNode('pgYetiMaya', n=yetiNodeName + 'Shape')
            yetiParent = yetiNode.getParent()
            yetiParent.rename(yetiNodeName)
            yetiNode.renderDensity.set(1)
            yetiNode.aiOpaque.set(0)
            timeNode.outTime.connect(yetiNode.currentTime)

            pm.select(yetiParent)
            surfaceShader = pm.PyNode(shaderName)
            pm.hyperShade(assign=surfaceShader)
        except:
            msg += u'{}노드와 {}쉐이더를  어싸인 하는데 실패 했습니다'.format(
                yetiNodeName, shaderName)

    return msg
    def autoOrientXKeepZ(self, obj ):
        assert isinstance(obj, pymel.core.nodetypes.Transform)
        
        unrepar = Unreparenter( obj )
        pm.makeIdentity( obj, apply=True, t=1, r=1, s=1, n=0, pn=1 )
        target = pm.createNode('joint')
        cons = [
            pm.pointConstraint( obj, target ),
            pm.orientConstraint( obj, target ),
            pm.scaleConstraint( obj, target )
        ]
        pm.delete( cons )
        
        
        unrepar.reparent()
        pm.joint( obj, edit=True,
            oj='xzy', secondaryAxisOrient='yup',
            zeroScaleOrient=True, children=False
        )
        unrepar.unparent( )
        pm.makeIdentity( obj, apply=True, t=1, r=1, s=1, n=0, pn=1 )
        
        
        self.rotateOnXToMatchZ(obj,target)

        pm.delete( target )
        
        pm.makeIdentity( obj, apply=True, t=1, r=1, s=1, n=0, pn=1 )
        unrepar.reparent(clean=True)
예제 #4
0
def exportYeti(path):
    yeitInfo = getYetiInfo()
    if pm.objExists('yetiInfoNode'):
        yetiInfoNode = pm.PyNode('yetiInfoNode')
        yetiInfoNode.unlock()
        pm.delete(yetiInfoNode)

    attrName = 'yetiInfo'
    yetiInfoNode = pm.createNode('network', n='yetiInfoNode')
    yetiInfoNode.addAttr(attrName, dt='string')
    jsonHandl = json.dumps(yeitInfo)
    yetiInfoNode.attr(attrName).set(jsonHandl)
    yetiInfoNode.attr(attrName).lock()
    yetiInfoNode.lock()

    exportList = [yetiInfoNode]
    for _, shader in yeitInfo.items():
        exportList.append(shader)

    pm.select(exportList)
    try:
        pm.exportSelected(path, pr=1, typ='mayaBinary', force=1, es=1)
        print 'Success Export Shader'
    except:
        print exportList
        print path
    finally:
        yetiInfoNode.unlock()
        pm.delete(yetiInfoNode)
    def connectAttributes(self, sourceAttrName, targetAttrName, multiplier=0.0):

        sourceAttrName = sourceAttrName
        targetAttrName = targetAttrName

        multValue = multiplier
        ##print( help( multValue )   )

        ## Get a list of all selected objects
        objs = pm.ls(selection=True)

        sourceObj = objs.pop(0)
        sourceAttr = getattr(sourceObj, sourceAttrName)

        doMult = False
        if multiplier != 0.0:
            doMult = True

        if doMult:
            m = pm.createNode("multiplyDivide")
            m.input2X.set(multValue)

        ## Loop through all the selected objects, except the first one
        for obj in objs:
            ## This stuff might fail, so put it in a try block
            try:
                targetAttr = getattr(obj, targetAttrName)
                if doMult:
                    sourceAttr >> m.input1X
                    m.outputX >> targetAttr
                else:
                    sourceAttr >> targetAttr

            except:
                print("An error occured on object: " + obj.name() + "\n" + traceback.format_exc() + "\n")
예제 #6
0
 def makeScripterNode(self):
     node = pm.createNode('mmmmScripterNodeV001v')
     originalName = node.name()
     node.rename(originalName + 'Shape')
     t = node.getParent()
     t.rename(originalName)
     node.rename(t.name() + 'Shape')
     c = pm.createNode('transform')
     c.rename('computationEnforcer')
     d = pm.createNode('plusMinusAverage')
     d.rename('dependency__plug_all_dependencies_into_1D_inputs_00')
     d.output1D >> node.dependency
     pm.parent(c, t)
     node.output >> c.translateX
     pm.select(t)
     return [t, node, c]
예제 #7
0
 def makeScripterNode( self ):
     node = pm.createNode('mmmmScripterNodeV001v')
     originalName = node.name()
     node.rename( originalName + 'Shape' )
     t = node.getParent()
     t.rename( originalName )
     node.rename( t.name()+'Shape' )
     c = pm.createNode('transform')
     c.rename( 'computationEnforcer' )
     d = pm.createNode('plusMinusAverage')
     d.rename( 'dependency__plug_all_dependencies_into_1D_inputs_00' )
     d.output1D >> node.dependency
     pm.parent( c, t )
     node.output >> c.translateX
     pm.select(t)
     return [t,node,c]
    def makeCamPlaneForDrawing(self):
        drawPlaneGroup = pm.createNode( "transform" );
    
        size = 1024
        planeList = pm.polyPlane( w=size,h=size, sx=1,sy=1, n="drawPlane", axis=[0,0,1] )  #print( planeList )
        planeXform = planeList[0]

        planeShape = planeXform.getShape()
        planeShape.overrideEnabled.set(1)
        planeShape.overrideShading.set(0)
        
        locatorXform = pm.spaceLocator(n="drawPlaneLocator")
        locatorShape = locatorXform.getShape()
        locatorShape.localScale.set( [128,128,128] )

        camList = pm.camera( name="drawPlaneCam" )  #print( camList )
        camXform = camList[0]
        camXform.tz.set(256)        
        
        pm.parent( planeXform, locatorXform )
        pm.parent( locatorXform, drawPlaneGroup )
        pm.parent( camXform, drawPlaneGroup )
        
        pm.orientConstraint( camXform, planeXform, ) ##aimVector=[0,1,0], upVector=[0,0,1] )
        
        ## Look through cam
        pm.select( camXform )
        panel = pm.getPanel( withFocus=True )        
        pm.mel.eval( "lookThroughSelected 0 " + panel +";")
        
        pm.makeLive( planeXform )
예제 #9
0
def exportShader(path):
    """씬안에 쉐이딩 그룹으로 부터 정보를 모아 shaderInfoNode에 저장 한후 
    입력 받은 경로에 shader를 저장 한다.
    
    :param path: 파일 경로
    :type path: str
    
    """
    sgGrps = getShadingEngine()

    shaderInfos = []
    exportList = []

    for sg in sgGrps:
        shaderInfo = getShaderInfo(sg)
        shaderInfos.append(shaderInfo)
        if shaderInfo['surfaceShader'] != '':
            exportList.append(shaderInfo['surfaceShader'])
        if shaderInfo['displacement'] != '':
            exportList.append(shaderInfo['displacement'])

    numAttr = len(shaderInfos)

    if pm.objExists('shaderInfoNode'):
        shaderInfoNode = pm.PyNode('shaderInfoNode')
        shaderInfoNode.unlock()
        pm.delete(shaderInfoNode)
    shaderInfoNode = pm.createNode('network', n='shaderInfoNode')
    shaderInfoNode.addAttr('shaderInfos', at='compound', nc=numAttr)

    for i in range(numAttr):
        attrName = 'shaderInfos' + str(i)
        shaderInfoNode.addAttr(attrName, dt='string', p='shaderInfos')

    for i, shaderInfo in enumerate(shaderInfos):
        attrName = 'shaderInfos' + str(i)
        jsonHandl = json.dumps(shaderInfo)
        shaderInfoNode.attr(attrName).set(jsonHandl)
        shaderInfoNode.attr(attrName).lock()

    shaderInfoNode.lock()

    exportList.append(shaderInfoNode)
    pm.select(exportList)
    try:
        pm.exportSelected(path, pr=1, typ='mayaBinary', force=1, es=1)
        print 'Success Export Shader'
    except:
        print exportList
        print path

    finally:
        shaderInfoNode.unlock()
        pm.delete(shaderInfoNode)
예제 #10
0
    def updateInfo(self):
        s = self

        self.updateScriptNames()
        candidates = pm.ls(s.scriptFullName + "*")

        if len(candidates) > 1:
            try:
                foundObjs = pm.ls(s.scriptFullName)
                assert (len(foundObjs) == 1)
                candidates[0] = foundObjs[0]
            except:
                print(
                    'Major problem found: you should have exactly one object'
                    'with that script name in your scene. Please double check'
                    ' your naming.')
        elif len(candidates) == 0:
            originalSelection = pm.ls(
                selection=True)  ## store selection to get it back later
            self.node = pm.createNode('transform',
                                      n=s.scriptFullName)  ## type, n=name
            try:
                scriptsParent = pm.ls('scripts*')[0]
            except:
                scriptsParent = pm.createNode('transform', n='scripts')
            pm.parent(self.node, scriptsParent)
            pm.select(originalSelection)  ## restore selection

        else:
            self.node = candidates[0]

        try:
            getattr(self.node, self.attrName)
        except:
            try:
                self.node.addAttr(self.attrName, dt='string')
                print('An attribute named "' + self.attrName +
                      '" was added to ' + self.node.name())
            except:
                print("Couldn't add attribute. Continuing anyway...")
    def fixJointComplexXforms( self, obj ):
        assert isinstance(obj, pymel.core.nodetypes.Transform)
        
        unrepar = Unreparenter( obj )
        
        pm.makeIdentity( obj, apply=True, t=1, r=1, s=1, n=0, pn=1 )
        tmp = pm.createNode('joint')
        cons = [
            pm.pointConstraint( obj, tmp ),
            pm.orientConstraint( obj, tmp ),
            pm.scaleConstraint( obj, tmp )
        ]
        pm.delete( cons )
        
        helperZ = pm.createNode('transform')
        helperX = pm.createNode('transform')
        pm.parent( helperX, tmp )
        pm.parent( helperZ, tmp )
        
        helperX.translate.set( [1,0,0] )    
        helperZ.translate.set( [0,0,1] )    

        obj.jointOrient.set( 0,0,0 )
        obj.rotateAxis.set( 0,0,0 )
        con = pm.aimConstraint( helperX, obj,
            worldUpType='object',
            worldUpObject=helperZ,
            aimVector=[1,0,0],
            upVector=[0,0,1],
        )
        pm.delete( con )   
        pm.delete( [helperX, helperZ] )
        
        pm.delete( tmp )
        
        pm.makeIdentity( obj, apply=True, t=1, r=1, s=1, n=0, pn=1 )
        unrepar.reparent( )
예제 #12
0
    def updateScriptNames(self):
        self.scriptPrefix = self.scriptPrefixTextField.getText()
        self.scriptName = self.scriptNameTextField.getText()
        self.scriptFullName = self.scriptPrefix + self.scriptName
                                
    def updateInfo(self):
        s = self
       
        self.updateScriptNames()
        candidates = pm.ls( s.scriptFullName + "*" )
        
        if len(candidates)>1:
            try:
                foundObjs = pm.ls( s.scriptFullName )
                assert(  len(foundObjs)==1  )
                candidates[0]=foundObjs[0]
            except:
                print( 'Major problem found: you should have exactly one object'
                    'with that script name in your scene. Please double check'
                    ' your naming.'
                )
        elif len(candidates)==0:
            originalSelection = pm.ls(selection=True)  ## store selection to get it back later
            self.node = pm.createNode( 'transform', n=s.scriptFullName )   ## type, n=name
            try:
                scriptsParent = pm.ls( 'scripts*' )[0]
            except:
                scriptsParent = pm.createNode( 'transform', n='scripts' )
            pm.parent( self.node, scriptsParent )
            pm.select( originalSelection)  ## restore selection
            
        else:
            self.node = candidates[0]
            
        try:
            getattr(self.node, self.attrName)
예제 #13
0
def saveRenderGlobal():

    rgArnold   = pm.PyNode('defaultArnoldDriver')
    rgArnoldRO = pm.PyNode('defaultArnoldRenderOptions')
    rgCommon   = pm.PyNode('defaultRenderGlobals')
    rgRes      = pm.PyNode('defaultResolution')
    
    # get
    renderInfo = {}
    
    for attr in rgArnold.listAttr():
        try:
            renderInfo[attr.name()] = cmds.getAttr(attr.name())
        except:
            pass
    
    for attr in rgCommon.listAttr():
        try:
            renderInfo[attr.name()] = cmds.getAttr(attr.name())
        except:
            pass
        
    for attr in rgRes.listAttr():
        try:
            renderInfo[attr.name()] = cmds.getAttr(attr.name())
        except:
            pass
        
    for attr in rgArnoldRO.listAttr():
        try:
            renderInfo[attr.name()] = cmds.getAttr(attr.name())
        except:
            pass
        
    # add data
    if pm.objExists('renderInfoNode'):
        lightInfoNode = pm.PyNode('renderInfoNode')
        lightInfoNode.unlock()
        pm.delete(lightInfoNode)
    lightInfoNode = pm.createNode('network', n='renderInfoNode')
    lightInfoNode.addAttr('renderInfo', dt='string')
    
    jsonHandl = json.dumps(renderInfo)
    lightInfoNode.attr('renderInfo').set(jsonHandl)
    lightInfoNode.attr('renderInfo').lock()
    

    print u'렌더 셋팅을 성공 적으로 저장 했습니다.'
예제 #14
0
    def createMeta(self, name):
        metaNode = pm.createNode('network', n=name + '_RigNode')

        # create system info
        metaNode.addAttr('cameraRigInfo',
                         numberOfChildren=5,
                         attributeType='compound')
        metaNode.addAttr('Class', dt='string', parent='cameraRigInfo')
        metaNode.addAttr('camera', at='message', parent='cameraRigInfo')
        metaNode.addAttr('ctrl', at='message', parent='cameraRigInfo')
        metaNode.addAttr('expression', at='message', parent='cameraRigInfo')
        metaNode.addAttr('ext', m=True, at='message', parent='cameraRigInfo')
        metaNode.Class.set('TumbleCamera')
        metaNode.Class.lock()
        self.metaNode = metaNode
        self.connectMeta(metaNode)
예제 #15
0
def dupXformNoChildren( obj ):
    ## takes only a single object
    assert type(obj) == pymel.core.nodetypes.Transform
    print( obj )
    
    dupShapesFinal = []
    tempDuplicatedXforms = []
    
    for s in obj.getShapes():
    
        s = obj.getShape()

        ## we need a temporary xform to move the shape to
        tempXform = pm.createNode('transform')
        pm.parent( s, tempXform, shape=True, relative=True )

        ## Duplicate the original shape
        ## we'll get a new duplicate of the transform
        ## and our duplicated shape node will be its shape
        dups = pm.duplicate( s )
        tempDuplicatedXform = dups[0]
        tempDuplicatedXforms.append( tempDuplicatedXform )
        
        dupShapesFinal.append( tempDuplicatedXform.getShape() )
    
        ## Now put the original xform back where we got it from!
        pm.parent( s, obj, shape=True, relative=True )
        pm.delete( tempXform )
        
        ## Now we should be back where we started, except with a new
        ## duplicated shape node at the origin, with a indentity
        ## xform node
        
    ## Now that we have duplicates of all the shapes,
    ## we need a duplicated xform node
    dupList = pm.duplicate( obj, parentOnly=True, returnRootsOnly=True )
    dupXform = dupList[0]
    ## Now parent all the duplicated shapes to the duplicated xform
    for s in dupShapesFinal:
        pm.parent( s, dupXform, shape=True, relative=True )
        
        
    ## We have to delete tempInplaceXform later, because we need it for a bit
    pm.delete( tempDuplicatedXforms )
    def connectAttributes(self,
                          sourceAttrName,
                          targetAttrName,
                          multiplier=0.0):

        sourceAttrName = sourceAttrName
        targetAttrName = targetAttrName

        multValue = multiplier
        ##print( help( multValue )   )

        ## Get a list of all selected objects
        objs = pm.ls(selection=True)

        sourceObj = objs.pop(0)
        sourceAttr = getattr(sourceObj, sourceAttrName)

        doMult = False
        if multiplier != 0.0:
            doMult = True

        if doMult:
            m = pm.createNode("multiplyDivide")
            m.input2X.set(multValue)

        ## Loop through all the selected objects, except the first one
        for obj in objs:
            ## This stuff might fail, so put it in a try block
            try:
                targetAttr = getattr(obj, targetAttrName)
                if doMult:
                    sourceAttr >> m.input1X
                    m.outputX >> targetAttr
                else:
                    sourceAttr >> targetAttr

            except:
                print("An error occured on object: " + obj.name() + "\n" +
                      traceback.format_exc() + "\n")
예제 #17
0
def importYeti(path):
    """입력 받은 경로에 shader를 import 한후 쉐이더를 적용 한다.
    
    :param path: 파일 경로
    :type path: str
    
    """
    yetiInfo = getYetiInfo()
    if yetiInfo:
        for yetiNode, shader in yetiInfo.items():
            if pm.objExists(yetiNode):
                pm.delete(yetiNode)
            if pm.objExists(shader):
                pm.delete(shader)

    if pm.objExists('yetiInfoNode'):
        yetiInfoNode = pm.PyNode('yetiInfoNode')
        yetiInfoNode.unlock()
        pm.delete(yetiInfoNode)

    pm.importFile(path)
    if not pm.objExists('yetiInfoNode'):
        pm.error(u'"yetiInfoNode"가 존재 하지 않습니다.')

    yetiInfoNode = pm.PyNode('yetiInfoNode')
    yetiInfo = json.loads(yetiInfoNode.yetiInfo.get())

    for yetiNodeName, shaderName in yetiInfo.items():
        yetiNode = pm.createNode('pgYetiMaya', n=yetiNodeName + 'Shape')
        yetiParent = yetiNode.getParent()
        yetiParent.rename(yetiNodeName)
        yetiNode.renderDensity.set(1)
        yetiNode.aiOpaque.set(0)

        pm.select(yetiParent)
        surfaceShader = pm.PyNode(shaderName)
        pm.hyperShade(assign=surfaceShader)
예제 #18
0
def duplicateShape( shape, selectDup=False ):

        '''
        Duplicates the shape node, does not by default select the result.
        Takes as an argument a single pymel shape node.
        '''

        oSel = pm.ls(selection=True)
        
        ## we need a temporary xform to move the shape to
        originalParent = shape.getParent()
        tempXform = pm.createNode('transform')
        pm.parent( shape, tempXform, shape=True, relative=True )

        ## Duplicate the original shape
        ## we'll get a new duplicate of the transform
        ## and our duplicated shape node will be its shape
        ## it's guaranteed to be a simple one xform
        ## hierarchy because we started from the new xform we created
        dups = pm.duplicate( shape )
        tempDuplicatedXform = dups[0]
        dupShape = tempDuplicatedXform.getShape()
        
    
        ## Now put the original xform back where we got it from!
        ## also parent new duplicated shape back to original xform
        pm.parent( shape, originalParent, shape=True, relative=True )
        pm.parent( dupShape, originalParent, shape=True, relative=True )
        ## Clean up the temporary xforms that were used
        pm.delete( tempXform )
        pm.delete( tempDuplicatedXform )
        
        ## restore selection and return result
        if selectDup==False:
            pm.select( oSel )
        return dupShape
예제 #19
0
    def createRivet(self):
        """
        Create one rivet for each selected vertex
        """
        selObjs = pm.ls(selection=True)
        if not selObjs:
            ## Nothing is selected, so print out warning and raise error        
            print( self.emsgPleaseSelect )
            return
            #raise Exception, self.emsgPleaseSelect
        self.originalSel = selObjs  #### Store this step of of the selection in case we want it again later

        uvs = []
        
                
        uvs.extend( pm.polyListComponentConversion( selObjs, tuv=True )  ) #### Change this to the full version
              
        #uvs.extend( [uv for uv in selObjs if '.uv' in uv] )  #### This is a very good list comprehension, perhaps expand it though
            ## the extend method of a list adds all items from another given list to the list

        uvsFromNurbs = []
        for i in selObjs:
            if pm.objectType( i ) == 'nurbsSurface' :
                uvs.append( i )

        
        ##  select our new, smaller/filtered uvs       
        pm.select( uvs )
        uvs = pm.ls( flatten = True, selection = True )  ## The flatten command returns each component individually in the list, rather than using strings that specify ranges of selections.  It takes more RAM but is often much more suitable to work with.

        ## Create a group so that we can organize the rivets  -  **** Note that this should be improved with the MmmmTools upcoming unique naming system
        if not pm.objExists('_follicle_grp'):    #### This line and the next should eventually be improved to not use a hardcoded name
            group = pm.group( em = True, w=True, n='_follicle_grp' )    #### **** Totally recreate this line, use a variable name or at least a unique one
        else:
            group = pm.PyNode('_follicle_grp')
            
        rivets = []
        
        pm.select( selObjs )

        failCount = 0

        ## Give an error msg if the user didn't use the script on a compatible selection
        if not uvs:
            failCount += 1
            print( self.emsgPleaseSelect )

        ## Everything is good, proceed to investigate and create rivets
        for uv in uvs:
                ## The commented out print line are simple useful for debugging
                print pm.objectType( uv )                
                
                objShapeName, index = tuple( uv.split( '.', 1 )  )
                obj = pm.PyNode( objShapeName )
                loc = pm.createNode( 'locator' )
                tr = getT( loc ) 
                #print( "Transform was: " + tr )
                hair = pm.createNode( 'follicle', parent = tr )
                pm.parent( tr, group )  ####  This line sucks because it's using a f*****g stupid name again
                rivets.append( tr )
                
                ## Poly mesh handler
                if pm.objectType( obj ) == 'mesh':
                    obj.outMesh >> hair.inputMesh
                    uvPos = pm.polyEditUV( uv, query=True )
                ## Nurbs surface handler
                elif pm.objectType( obj ) == 'nurbsSurface':
                    obj.local >> hair.inputSurface
                    ## The index is a messy string, so we need to pull uv data out of it
                    uvTuple = ( index.strip('.uv[]').split('][')  )
                    ## We need to create the tuple as floats, because we got it as strings
                    uvPos = (    float(uvTuple[0]), float(uvTuple[1])     )
                    #uvPos = ( uvTuple[0], uv[1] )#index.strip('.uv[]').split('][')

                    ## Handle conditions where the uvs aren't normalized, this may not be required often
                    maxU = float(  obj.maxValueU.get()     )
                    maxV = float(  obj.maxValueV.get()     )
                    uvPos = (    uvPos[0]/maxU,  uvPos[1]/maxV   )
                ## Handle other cases, where this script can't do anything useful
                else:
                    print( obj + ' with uv: ' + uv + \
                        '   was incompatible, it much be either polygons or Nurbs' )
                    failCount += 1                        
                    continue
                    
                u, v = uvPos                    

                ## Make the hair follow the model, both by parenting, and by keeping its translate and rotate matched
                obj.worldMatrix >> hair.inputWorldMatrix
                hair.outTranslate >> tr.translate
                hair.outRotate >> tr.rotate   ## Note:  The hair has no outScale
                
                ## Set the u and v parameters of the hair so that it sticks to the correct place on the model
                hair.parameterU.set( u )
                hair.parameterV.set( v )
                
                ## Put the rivet into a group so we can select it afterwards
                self.lastRivetsCreated.append( loc )
           
        ## Select all the new rivets we created
        pm.select( self.lastRivetsCreated, replace=True )
        if failCount:
            print( str(failCount) + """ rivets failed to be created. Most likely because the selection was not correct. Try selecting vertices on a nurbs surface or a polygon mesh and running the script again. """)
        else:
            print( self.msgSucess )
        return       
예제 #20
0
    def refreshArsenalPass(self, progressBarUpdate = None):
        allRenderLayers = pm.RenderLayer.listAllRenderLayers()
        for myRenderLayer in allRenderLayers:
            arsenalPassName = myRenderLayer.name() + '_arsenalPass'
            aresenalConnected = myRenderLayer.listConnections(destination=True, source=False, type='arsenalPass')
            ajustements = pm.editRenderLayerAdjustment(myRenderLayer, query=True, layer=True)
            if len(aresenalConnected) == 0:
                if not pm.objExists(arsenalPassName):
                    pm.createNode('arsenalPass', name=arsenalPassName)
                    pm.lockNode(arsenalPassName, lock=True)
                pm.connectAttr(myRenderLayer.name() + '.message', arsenalPassName + '.passName', force=True)
            elif str(aresenalConnected[0]) != arsenalPassName:
                pm.lockNode(aresenalConnected[0], lock=False)
                pm.rename(aresenalConnected[0], arsenalPassName)
                pm.lockNode(arsenalPassName, lock=True)
                self.passName[myRenderLayer].passName = myRenderLayer.name()
            attributesFastArsenal = ['lightSelectAllNormal',
             'lightSelectAllDiffuse',
             'lightSelectAllRaw',
             'lightSelectAllSpecular',
             'vrayLambert',
             'multimatteMaskName',
             'vrayMaterialID',
             'vrayProxyObjectID']
            attributesFastVray = ['giOn',
             'primaryEngine',
             'secondaryEngine',
             'imap_detailEnhancement',
             'aoOn',
             'globopt_mtl_glossy',
             'globopt_mtl_reflectionRefraction',
             'globopt_mtl_doMaps',
             'globopt_light_doShadows',
             'aaFilterOn',
             'globopt_geom_displacement',
             'cam_mbOn',
             'cam_dofOn',
             'cam_overrideEnvtex',
             'sys_distributed_rendering_on']
            attributesConnectionArsenal = ['passMembers',
             'blackHoleMembers',
             'blackHoleMembersReceiveShd',
             'giMembersGenerate',
             'giMembersReceive',
             'primaryMembersOff',
             'reflectionMembersOff',
             'refractionMembersOff',
             'shadowCastsMembersOff',
             'lightSelectNormalMembers',
             'lightSelectDiffuseMembers',
             'lightSelectRawMembers',
             'lightSelectSpecularMembers']
            self.multiMatteAttributes(myRenderLayer=myRenderLayer, attributesConnectionArsenal=attributesConnectionArsenal)
            for (i, attribut,) in enumerate(attributesFastArsenal):
                if progressBarUpdate is not None:
                    progressBarUpdate(numStep=100, value=i, text='Pass ' + myRenderLayer.name() + ' step 2 : init FastArsenal %v of %m ...')
                self.initAttributes(attribut=attribut, renderPass=myRenderLayer)

            for (i, attribut,) in enumerate(attributesFastVray):
                self.initAttributes(attribut=attribut, renderPass=myRenderLayer, fromRenderGlobal=True)
                if progressBarUpdate is not None:
                    progressBarUpdate(numStep=100, value=i, text='Pass ' + myRenderLayer.name() + ' step 3 : init FastVray %v of %m ...')
                if myRenderLayer.name() != 'defaultRenderLayer':
                    if ajustements is None or 'vraySettings.' + attribut not in ajustements:
                        self.overrideAttribute(renderPass=myRenderLayer, node=arsenalPassName, attribute=attribut, always=True)
                    else:
                        self.overrideAttribute(renderPass=myRenderLayer, node=arsenalPassName, attribute=attribut, always=False)

            for (i, attribut,) in enumerate(attributesConnectionArsenal):
                if progressBarUpdate is not None:
                    progressBarUpdate(numStep=100, value=i, text='Pass ' + myRenderLayer.name() + ' step 4 : init FastConnection %v of %m ...')
                self.initAttributes(attribut=attribut, renderPass=myRenderLayer, connection=True)

            if progressBarUpdate is not None:
                progressBarUpdate(numStep=100, value=100, text='Done...')
예제 #21
0
middleC = pm.PyNode("middle_c")

pinkyA = pm.PyNode("pinky_a")
pinkyB = pm.PyNode("pinky_b")
pinkyC = pm.PyNode("pinky_c")


pointerAll = [pointerA, pointerB, pointerC]
middleAll = [middleA, middleB, middleC]
pinkyAll = [pinkyA, pinkyB, pinkyC]
all = pointerAll + middleAll + pinkyAll

adds = {}

for jnt in all:
    addNodeY = pm.createNode("plusMinusAverage")
    addNodeZ = pm.createNode("plusMinusAverage")
    addNodeY.rename(jnt.name() + "_addY")
    addNodeZ.rename(jnt.name() + "_addZ")
    ## the operator >> means "connect" for pymel
    addNodeY.output1D >> jnt.rotateY
    addNodeZ.output1D >> jnt.rotateZ

    adds[jnt.name() + "Y"] = addNodeY
    adds[jnt.name() + "Z"] = addNodeZ

## We can't hard core the name because Maya might change that
## #controlCurve.pointerAllCurl >> pm.PyNode('pointer_a_addZ').input1D
## so we use our adds dictionary to get the right answer
## pointerAllCurl connections
target = adds["pointer_a" + "Z"]
예제 #22
0
def setup_ik_spline(**kwargs):
    curve = kwargs.get("curve", None)
    joint_chain = kwargs.get("joint_chain", None)
    auto_curve = kwargs.get("auto_curve", True)
    use_curve = kwargs.get("use_curve", None)
    spans = kwargs.get("number_of_spans", 4)
    ctrl_jnts = kwargs.get("num_control_joints", 3)
    ik_name = kwargs.get("ik_name", "ikHandle")
    scale_stretch = kwargs.get("scale_stretch", False)
    create_dense_chain = kwargs.get("dense_chain", False)
    dense_division = kwargs.get("dense_chain_divisions", 3)
    auto_simplify = kwargs.get("auto_simplify_curve", False)
    stretch_exp = kwargs.get("stretch_exp", False)
    global_scale_check = kwargs.get("global_scale_check", False)
    global_scale_attr = kwargs.get("global_scale_attr", None)

    pm.select(joint_chain, hierarchy=True)
    joint_chain = pm.ls(selection=True)
    if not isinstance(joint_chain[0], pm.Joint):
        pm.displayInfo("selection should be of type joint")
        return None
    if len(joint_chain) < 2:
        pm.displayInfo("Chain should consist of more than one joint")
        return None

    if (global_scale_check):
        if (global_scale_attr is None):
            pm.displayInfo("Please input global scale attribute")
            return None
        else:
            obj = global_scale_attr.split(".")[0]
            global_attr = global_scale_attr.split(".")[1]
            check_global_attr = pm.attributeQuery(global_attr,
                                                  node=obj,
                                                  exists=True)
            if not check_global_attr:
                pm.displayInfo("Invalid global scale attribute")
                return None

    start_jnt = joint_chain[0]
    end_joint = joint_chain[-1]

    if create_dense_chain:
        rep_chain = pm.duplicate(joint_chain)
        start_jnt = rep_chain[0]
        end_joint = rep_chain[-1]
        dense_chain(joints=rep_chain, joints_inbetween=dense_division)
        rep_chain.append(end_joint)
        for index in range(len(joint_chain)):
            pm.parentConstraint(rep_chain[index],
                                joint_chain[index],
                                maintainOffset=False)
            #pm.scaleConstraint(rep_chain[index], joint_chain[index], maintainOffset=False)
            pm.connectAttr(
                str(rep_chain[index]) + ".scale",
                str(joint_chain[index]) + ".scale")
        pm.select(start_jnt, hierarchy=True)
        new_chain = pm.ls(selection=True)

    crv = ""

    #print "START", start_jnt
    #print "END",end_joint

    if auto_curve:
        ik_handle, eff, crv = pm.ikHandle(startJoint=start_jnt,
                                          createCurve=auto_curve,
                                          solver="ikSplineSolver",
                                          numSpans=spans,
                                          endEffector=end_joint,
                                          simplifyCurve=auto_simplify)

    else:
        crv = pm.PyNode(use_curve)
        ik_handle, eff = pm.ikHandle(startJoint=start_jnt,
                                     curve=use_curve,
                                     solver="ikSplineSolver",
                                     endEffector=end_joint,
                                     createCurve=False)

    crv.inheritsTransform.set(0)

    pm.rename(ik_handle, ik_name + "IK_Handle")
    pm.rename(crv, ik_name + "IK_Curve")

    ik_curve_shp = crv.getShape()
    crv_info_node = pm.createNode("curveInfo")
    pm.connectAttr(ik_curve_shp + ".worldSpace", crv_info_node + ".inputCurve")
    '''
    if stretch_exp:
        if create_dense_chain:
            stretch_expression(joints = new_chain, curve_info_node = crv_info_node, connect_scale = scale_stretch,
                               expression_name = ik_name+"_stretch_expression")
        else:
            stretch_expression(joints = joint_chain, curve_info_node = crv_info_node, connect_scale = scale_stretch,
                               expression_name = ik_name+"_stretch_expression")
    '''

    if ctrl_jnts:
        if ctrl_jnts == 1:
            print "Minimum 2 joints needed as controllers"
            print "skipping control joint creation process"
            pm.displayInfo("Minimum 2 joints needed as controllers")
        else:
            ctrl_jnts = joints_along_curve(number_of_joints=ctrl_jnts,
                                           curve=crv,
                                           bind_curve_to_joint=True)
            pm.select(clear=True)
            ctr_jnt_gp = pm.group(ctrl_jnts, name="control_joints")
            #print "JNT NAME", ctr_jnt_gp

    if stretch_exp:
        pm.addAttr(ctrl_jnts[-1],
                   longName="Stretch",
                   attributeType="enum",
                   enumName="off:on",
                   keyable=True)
        print "ATTRIBUTE TO", str(ctrl_jnts[-1])
        if create_dense_chain:
            stretch_expression(joints=new_chain,
                               curve_info_node=crv_info_node,
                               connect_scale=scale_stretch,
                               expression_name=ik_name + "_stretch_expression",
                               ctrl_attr=str(ctrl_jnts[-1]) + ".Stretch",
                               glbl_scl_stat=global_scale_check,
                               glbl_scl_attr=global_scale_attr)
        else:
            stretch_expression(joints=joint_chain,
                               curve_info_node=crv_info_node,
                               connect_scale=scale_stretch,
                               expression_name=ik_name + "_stretch_expression",
                               ctrl_attr=str(ctrl_jnts[-1]) + ".Stretch",
                               glbl_scl_stat=global_scale_check,
                               glbl_scl_attr=global_scale_attr)

    final_group = pm.group(name=ik_name + "_ik_group", empty=True)
    pm.parent(joint_chain[0], final_group)
    pm.parent(crv, final_group)
    pm.parent(ik_handle, final_group)
    if ctrl_jnts > 1:
        pm.parent(ctr_jnt_gp, final_group)
    if create_dense_chain:
        pm.select(clear=True)
        dense_grp = pm.group(start_jnt, name="dense_chain_group")
        pm.parent(dense_grp, final_group)

    return None