def rename_module(self, new_name):
        """
        renames the entire modules namespace
        """
        if new_name == self.userSpecifiedName:
            return

        # Rename the module name
        new_name = utils.moduleNamespace(new_name)
        pm.lockNode(self.module_container, lock=False, lockUnpublished=False)

        pm.namespace(setNamespace=":")
        pm.namespace(add=new_name)
        pm.namespace(setNamespace=":")

        pm.namespace(moveNamespace=[self.userSpecifiedName, new_name])
        pm.namespace(removeNamespace=self.userSpecifiedName)

        self.userSpecifiedName = new_name
        self.module_container = self.userSpecifiedName + ":module_container"

        # change meta node attribute UserSpecifiedName
        utils.setModuleMetaInfo(self.module_container, "Namespace", self.userSpecifiedName)


        pm.lockNode(self.module_container, lock=True, lockUnpublished=True)

        return
    def _do_maya_pre_publish(self, task, work_template, progress_cb):
        """
        Do Maya primary pre-publish/scene validation
        """
        import maya.cmds as cmds

        progress_cb(0.0, "Validating current scene", task)

        # get the current scene file:
        scene_file = cmds.file(query=True, sn=True)
        if scene_file:
            scene_file = os.path.abspath(scene_file)

        # validate it:
        scene_errors = self._validate_work_file(scene_file, work_template,
                                                task["output"], progress_cb)

        for ref in pm.ls(type='reference'):
            try:
                pm.referenceQuery(ref, filename=True)
            except:
                pm.lockNode(ref, l=False)
                pm.delete(ref)

        progress_cb(100)

        return scene_errors
    def reParentModule(self, new_parentObject):
        '''
        re parents modules
        '''
        old_parentObject = self.findParentModule()

        self.parent_object = pm.PyNode(self.userSpecifiedName + ":unhookTarget_loc")
        # if None is passed, we are unparenting.
        if new_parentObject != None:
            # make sure we are not trying to connect to another part of the same module
            if new_parentObject.namespace() != self.parent_object.namespace():
                self.parent_object = pm.PyNode(new_parentObject)

        # check to see if parent object is the same as old parent object.
        # we do not want to parent to same module.
        if self.parent_object == old_parentObject:
            return

        # Connect four attributes similar to how a pointConstraint works.
        pm.lockNode(self.module_container, lock=False, lockUnpublished=False)
        hook_constraint = pm.PyNode(self.userSpecifiedName + ":targetParent_pointConstraint")

        #self.parent_object.parentMatrix[0].connect(hook_constraint.target[0].targetParentMatrix)

        pm.connectAttr(self.parent_object + ".parentMatrix[0]", hook_constraint + ".target[0].targetParentMatrix", force=True)
        pm.connectAttr(self.parent_object + ".translate", hook_constraint + ".target[0].targetTranslate", force=True)
        pm.connectAttr(self.parent_object + ".rotatePivot", hook_constraint + ".target[0].targetRotatePivot", force=True)
        pm.connectAttr(self.parent_object + ".rotatePivotTranslate", hook_constraint + ".target[0].targetRotateTranslate", force=True)

        utils.setModuleMetaInfo(self.module_container, "ParentObject", self.parent_object)


        pm.lockNode(self.module_container, lock=True, lockUnpublished=True)
Exemple #4
0
def delete_unknow_nodes():
    unknow_list = pm.ls(
        mel.eval('ls -type unknown -type unknownDag -type unknownTransform'))
    while len(unknow_list) > 0:
        for node in unknow_list:
            pm.lockNode(node, lock=False)
            pm.delete(node)
Exemple #5
0
def lock_rig(lock=True):
    pm.hide(pm.ls(type='locator'))
    pm.select(pm.ls(type='locator'), add=True)
    pm.select(pm.ls(type='orientConstraint'), add=True)
    pm.select(pm.ls(type='parentConstraint'), add=True)
    pm.select(pm.ls(type='pointConstraint'), add=True)
    # pm.select(pm.ls(type='skinCluster'),add=True)
    # pm.select(pm.ls(type='blendShape'),add=True)
    pm.select(pm.ls(type='follicle'), add=True)
    pm.select(pm.ls(type='ikHandle'), add=True)
    pm.select(pm.ls('*miscGp'), hi=True, add=True)
    pm.select(pm.ls('*bonGp'), hi=True, add=True)
    pm.select(pm.ls('*genGp'), hi=True, add=True)
    # pm.select(pm.ls('*facialGp'),hi=True,add=True)
    sel = pm.selected()
    for i in sel:
        log.info("{}:lock:{}".format(i, lock))
        pm.lockNode(i, lock=lock)
        if i.nodeType() == 'skinCluster':
            for b in i.getInfluence():
                b.attr('lockInfluenceWeights').set(lock)
        try:
            for atr in i.listAttr():
                if 'vis' not in atr:
                    try:
                        if lock:
                            atr.lock()
                        else:
                            atr.unlock()
                    except:
                        pass
        except:
            pass
Exemple #6
0
def lock_node(node, lock=True, query=False):
    if query:
        result = pm.lockNode(node, q=query)
        log.info(result)
        return result
    pm.lockNode(node, lock=lock)
    return lock
 def _do_maya_pre_publish(self, task, work_template, progress_cb):
     """
     Do Maya primary pre-publish/scene validation
     """
     import maya.cmds as cmds
     
     progress_cb(0.0, "Validating current scene", task)
     
     # get the current scene file:
     scene_file = cmds.file(query=True, sn=True)
     if scene_file:
         scene_file = os.path.abspath(scene_file)
         
     # validate it:
     scene_errors = self._validate_work_file(scene_file, work_template, task["output"], progress_cb)
     
     for ref in pm.ls(type='reference'):  
         try:
             pm.referenceQuery(ref,filename=True)  
         except:  
             pm.lockNode(ref,l=False)
             pm.delete(ref)
     
     progress_cb(100)
       
     return scene_errors
def flushScript( *args ):
    if( script_job_id != -1 ):
        pm.scriptJob( kill=script_job_id, force=True )
        
    pm.lockNode( 'light_probe', lock=False )
    pm.delete('light_probe')
        
    pm.makeLive(none=True)
    def __init__(self):
        selectedObjects = pm.ls(selection = True, transforms = True)
        
        filteredGroups = []
        for obj in selectedObjects:
            if obj.find("Group__") == 0:
                filteredGroups.append(obj)
        
        if len(filteredGroups) == 0:
            return
        
        # Recursively find and store grouped module namespaces in a list
        groupContainer = "Group_container"
        modules = []
        for group in filteredGroups:
            modules.extend(self.FindChildModules(group))
        
        
        
        # Store all the grouped container nodes in a list
        moduleContainers = [groupContainer]
        for module in modules:
            moduleContainer = "%s:module_container" %module
            moduleContainers.append(moduleContainer)
        
        
        # Unlock containers
        for container in moduleContainers:
            pm.lockNode(container, lock = False, lockUnpublished = False)

        # Ungroup
        for group in filteredGroups:
            childCount = len(pm.listRelatives(group, children = True))
            
            if childCount > 1:
                pm.ungroup(group, absolute = True)
            
            for attr in ["t", "r", "globalScale"]:
                pm.container(groupContainer, edit = True, unbindAndUnpublish = "%s.%s" %(group, attr))
            
            parentGroup = pm.listRelatives(group, parent = True)
            
            pm.delete(group)
            
            # Recursively delete empty parent groups
            if len(parentGroup) != 0:
                parentGroup = parentGroup[0]
                children = pm.listRelatives(parentGroup, children = True)
                children = pm.ls(children, transforms = True)
                
                if len(children) == 0:
                    pm.select(parentGroup, replace = True)
                    UngroupSelected()
        
        # Lock module containers after ungrouping is finished
        for container in moduleContainers:
            if pm.objExists(container):
                pm.lockNode(container, lock = True, lockUnpublished = True)
Exemple #10
0
def pre_layer_mel():
    print '++++++++++++++++++pre_layer_mel +++++++++++++++++++++++++++++'
    # if "pgYetiMaya" in plugins and "vrayformaya" in plugins:
    # cmds.loadPlugin( "vrayformaya")
    # cmds.loadPlugin( "pgYetiVRayMaya")
    render_node = pm.PyNode("defaultRenderGlobals")
    render_name = render_node.currentRenderer.get()
    yeti_load = cmds.pluginInfo("pgYetiMaya", query=True, loaded=True)
    print "the yeti load is %s " % yeti_load
    yeti_vray_load = cmds.pluginInfo("pgYetiVRayMaya", query=True, loaded=True)
    print "the yeti_vray_load load is %s " % yeti_vray_load
    shave_load = cmds.pluginInfo("shaveNode", query=True, loaded=True)
    print "the shave_load load is %s " % shave_load
    pm.lockNode('defaultRenderGlobals', lock=False)
    render_node.modifyExtension.set(0)
    render_node.postMel.set(l=0)
    render_node.preRenderLayerMel.set(l=0)
    render_node.postRenderLayerMel.set(l=0)
    render_node.preRenderMel.set(l=0)
    render_node.postRenderMel.set(l=0)

    if render_name == "vray":
        print "++++++++++++++++ the renderer is vray+++++++++++++++++++++"
        if yeti_load and yeti_vray_load and shave_load == False:
            mel.eval('pgYetiVRayPreRender;')
            #render_node.postMel.set("pgYetiVRayPostRende;")
            print render_node.postMel.get()
        if shave_load and yeti_load == False:
            mel.eval('shaveVrayPreRender;')
        if yeti_load and yeti_vray_load and shave_load:
            mel.eval('shaveVrayPreRender;pgYetiVRayPreRender;')
        else:
            render_node.postMel.set("")
            render_node.preRenderLayerMel.set("")
            render_node.postRenderLayerMel.set("")
            render_node.preRenderMel.set("")
            render_node.postRenderMel.set("")

    elif render_name == "mentalRay":
        print "++++++++++++++++ the renderer is mentalRay++++++++++++++++++"
        if shave_load:
            #render_name = render_node.currentRenderer.get()

            render_node.preRenderMel.set("shave_MRFrameStart;")
            render_node.postRenderMel.set("shave_MRFrameEnd;")
            #mel.eval('shave_MRFrameStart')

            #render_node.preRenderLayerMel.set('python \"mel.eval(\\"pgYetiVRayPreRender\\")\"')
        else:
            render_node.preRenderMel.set("")
            render_node.postRenderMel.set("")
    else:
        print "++++++++++++++++ the renderer isnot vray mentalRay+++++++++++++++++++++++++"
        render_node.postMel.set("")
        render_node.preRenderLayerMel.set("")
        render_node.postRenderLayerMel.set("")
        render_node.preRenderMel.set("")
        render_node.postRenderMel.set("")
def nameNode():

    sel = pm.ls('*RN')

    pm.lockNode(sel, lock=False)

    pm.rename(sel, 'Avatar_RigRN')

    pm.lockNode('*RN', lock=True)
Exemple #12
0
    def removeNodeAction(self):

        pm.select("cycleAnimationListNode", r = True)


        a = pm.selected()[0]
        pm.lockNode(a, lock = False)
        pm.delete(a)
        pm.deleteUI("CycleAnimationListUI", wnd = True)       
Exemple #13
0
def setModuleMetaInfo(node, attribute, attrInfo):
    """
    Sets the attribute of the modules meta node.
    If attribute type is message, attribute has to be the same for both meta and node.
    """
    node = pm.PyNode(node)
    # what if node is meta
    meta_node = None
    # find meta node
    if node.hasAttr("MetaNode"):
        meta_node = pm.PyNode(node.MetaNode.get())
    elif node.hasAttr("ModuleNodes"):
        meta_node = pm.PyNode(node)

    if meta_node != None:
        if pm.objectType(node) == "container":
            module_container = node
        else:
            module_container = pm.container(q = True, findContainer = node)

        lock_state = pm.lockNode(module_container, q = True, lock = True)[0]
        pm.lockNode(module_container, lock = False, lockUnpublished = False)

        #  ---------------------------------------------------------------

        # if attribute is a string
        if meta_node.attr(attribute).type() == "string":
            meta_node.attr(attribute).set(lock = False)
            meta_node.attr(attribute).set(attrInfo, lock = True)

        # if attribute is a message
        if meta_node.attr(attribute).type() == "message":
            # meta node and node need to have same attribute
            connected_node = pm.PyNode(attrInfo)
            # find the nodes container
            connectedNode_container = pm.container(q = True, findContainer = connected_node)

            if connectedNode_container != getModuleMetaInfo(node, "ModuleContainer"):
                # need to make sure the input node's container is unlocked
                connectedNode_lockState = pm.lockNode(connectedNode_container, q = True, lock = True)[0]
                pm.lockNode(connectedNode_container, lock = False, lockUnpublished = False)

                # if the input node does not have the same attribute
                if not connected_node.hasAttr(attribute):
                    _logger.warning("{} does not have attribute: {}".format(connected_node, attribute))
                    pm.addAttr(connected_node, longName = attribute, at="message", multi = True)
                try:
                    meta_node.attr(attribute).connect(connected_node.attr(attribute))
                except:
                    _logger.warning("CANNOT CONNECT {} TO {}".format(meta_node.attr(attribute), connected_node.attr(attribute)))

                pm.lockNode(connectedNode_container, lock = connectedNode_lockState, lockUnpublished = lock_state)


        pm.lockNode(module_container, lock = lock_state, lockUnpublished = lock_state)
def cbsTrans(*args, **kwargs):
    
    sculptTrans = kwargs.setdefault('sculptTrans', pm.ls(sl=True)[0])# (string) The mesh to get the tweak edits extracted from
    shape = kwargs.setdefault('shape') # (string) The shape node of the sculptTrans node
    tweak = kwargs.setdefault('tweak') # (string) The tweak node that is going to be cleared
    skin = kwargs.setdefault('skin') # (string) The skinCluster node that drives the base mesh
    base = kwargs.setdefault('base') # (string) The base mesh for the character

    #get some info
    sculptTrans, shape, tweak, skin =  gatherInfo(sculptTrans, shape, tweak, skin)
    if not 'baseTransform' in pm.listAttr(sculptTrans, ud=True):
        pm.error('This model has not been prepared for sculpting. If you accidentally started, simply run Clear Tweaks to extract what has been done')
    if not base:
        base = sculptTrans.baseTransform.get()

    baseRef = sculptTrans.baseReference.get()

    #turn off a couple things that might mess with things
    pm.symmetricModelling(e=True, symmetry= False)
    pm.softSelect(e=True, softSelectEnabled=False)

    #first, let's unlock the guys from the old function
    pm.lockNode(base, l=False)
    pm.lockNode(sculptTrans, l=False)
    pm.setAttr('%s.v'%base, True)

    #extract from the sculpted shape
    newShape = clearTweaks(base=base, tweak=tweak)

    pm.delete(sculptTrans)

    newOrig = pm.duplicate(base, n='%s_editReference'%base)[0]
    pm.connectAttr(('%s.outMesh' %newOrig.getShapes()[1]), ('%s.inMesh' %newOrig.getShape()))

    pm.select(cl=True)
    deviation = False
    for v in range(pm.polyEvaluate(base, v=True)):
        refPos = pm.xform('%s.vtx[%i]'%(baseRef, v), q=True, t=True)
        adjPos = pm.xform('%s.vtx[%i]'%(newOrig, v), q=True, t=True)

        if not refPos == adjPos:
            deviation=True
            pm.move('%s.vtx[%i]' %(newShape, v), (refPos[0]-adjPos[0], refPos[1]-adjPos[1], refPos[2]-adjPos[2]), r=True)
            pm.move('%s.vtx[%i]'%(base, v), (refPos[0]-adjPos[0], refPos[1]-adjPos[1], refPos[2]-adjPos[2]), os=True, r=True)
            pm.select('%s.vtx[%i]' %(base, v), add=True)

    if deviation:
        pm.warning('It appears there were issues extracting from the mesh, steps have been taken to try and remedy, but unexpected results may occur')

    #apply a texture to the new shape.
    pm.select(newShape, r=True)
    pm.sets('initialShadingGroup', e=True, forceElement=True)

    pm.delete(newOrig, baseRef)
    return newShape
Exemple #15
0
 def remove_ref_node(self,ref_nodes):
     for ref_node in ref_nodes:
         try:
             pm.lockNode( ref_node, lock=False )
             file_ref = pm.system.FileReference(ref_node)
             file_ref.remove()
         except:
             self.Log.error( 'can not remove %s' % ref_node.name() )
             self.Log.error( traceback.format_exc() )
         else:
             self.Log.debug( 'remove %s success' % ref_node.name() )
Exemple #16
0
def unknown(delete=False):
    unknowns = []
    for node in pm.ls(type=('unknown', 'unknownDag', 'unknownTransform')):
        unknowns.append(node.name())
        if not node.objExists():
            continue
        pm.lockNode(node, lock=False)
        if delete:
            pm.delete(node)

    return unknowns
	def SetModuleMaintenanceVisibility(self, _visibility = True):
		characters = utils.FindInstalledCharacters()
		
		for c in characters:
			characterContainer = "%s:character_container" %c
			pm.lockNode(characterContainer, lock = False, lockUnpublished = False)
			
			characterGroup = "%s:character_grp" %c
			pm.setAttr("%s.moduleMaintenanceVisibility" %characterGroup, _visibility)
			
			pm.lockNode(characterContainer, lock = True, lockUnpublished = True)
Exemple #18
0
 def remove_ref_node(self, ref_nodes):
     for ref_node in ref_nodes:
         try:
             pm.lockNode(ref_node, lock=False)
             file_ref = pm.system.FileReference(ref_node)
             file_ref.remove()
         except:
             self.Log.error('can not remove %s' % ref_node.name())
             self.Log.error(traceback.format_exc())
         else:
             self.Log.debug('remove %s success' % ref_node.name())
Exemple #19
0
def deleteRigBotMetadataNode():
    """
	Deletes if node has no existing metadata.
	:return: None
	"""
    if pm.objExists('rigbot'):
        rb_node = pm.PyNode('rigbot')

    metadata = rb_node.listAttr(ud=True)
    if not metadata:
        pm.lockNode(rb_node, lock=False)
        pm.delete(rb_node)
Exemple #20
0
def creatCACNode():
    
    try:
        pm.select("cycleAnimationListNode", replace = True)
        return None

    except:
        startLib = {}
        startAtt = str(data2String(startLib))

        animNode = pm.createNode('transform', name= 'cycleAnimationListNode')
        
        pm.addAttr(animNode, longName='cycles', dataType='string')
        pm.setAttr('cycleAnimationListNode.cycles', startAtt)

        proj = pm.system.workspace.getPath() + '/movies'

        pm.addAttr(animNode, longName='path', dataType='string')
        pm.setAttr('cycleAnimationListNode.path', proj)

        pm.addAttr(animNode, longName='camera', dataType='string')
        pm.setAttr('cycleAnimationListNode.camera', "Active")

        pm.addAttr(animNode, longName='whichPb', at='bool')
        pm.setAttr('cycleAnimationListNode.whichPb', False)

        pm.addAttr(animNode, longName='namespace', dataType='string')
        pm.setAttr('cycleAnimationListNode.namespace' , '')

        pm.addAttr(animNode, longName='overWrite', at='bool')
        pm.setAttr('cycleAnimationListNode.overWrite', False)

        pm.addAttr(animNode, longName='subFolder', at='bool')
        pm.setAttr('cycleAnimationListNode.subFolder', True)

        pm.addAttr(animNode, longName='sufix', dataType='string')
        pm.setAttr('cycleAnimationListNode.sufix', '')

        pm.addAttr(animNode, longName='pbSize', dataType='string')
        pm.setAttr('cycleAnimationListNode.pbSize', 'HD 1080')

        pm.addAttr(animNode, longName='format', dataType='string')
        pm.setAttr('cycleAnimationListNode.format', '')

        pm.addAttr(animNode, longName='compression', dataType='string')
        pm.setAttr('cycleAnimationListNode.compression', '')

        pm.addAttr(animNode, longName='animator', dataType='string')
        pm.setAttr('cycleAnimationListNode.animator', '')
        
        pm.lockNode(animNode)

        return None
def delete_unknown():

    unknown = pm.ls(type='unknown')
    plugs = pm.unknownPlugin(q=True, l=True)

    if len(unknown) > 0:
        pm.lockNode(unknown, l=False)
        pm.delete(unknown)

    if plugs is not None:
        for p in plugs:
            pm.unknownPlugin(p, r=True)
def cbsStart(*args, **kwargs):
    base = kwargs.setdefault('base', pm.ls(sl=True)[0]) # (string) The base model for the character
    shape = kwargs.setdefault('shape') # (string) The shape node of the base model
    tweak = kwargs.setdefault('tweak') # (string) The tweak node of the base model that is being skinned
    skin = kwargs.setdefault('skin') # (string) The skinCluster node that is driving the base model
    
    #gather some info
    base, shape, tweak, skin = gatherInfo(base, shape, tweak, skin)
    verts = pm.polyEvaluate(base, v=True)
    
    #do a quick check to make sure this part hasn't been done before
    if base.hasAttr('baseTransform'):
        pm.error('You have already run the "Start" function on this model, so it is already ready to go.' +
                 'If corrections have already been made, click "Extract Shape to finish the process"')

    for i in pm.listHistory(base, lv=1):
        if i.type() == 'polySmoothFace':
            pm.error('The selected shape is connected to a smooth modifier. This hinders the ability to track edits. %s must be deleted.' % i)
    
    #turn off a couple things that might mess with things
    pm.symmetricModelling(e=True, symmetry= False)
    pm.softSelect(e=True, softSelectEnabled=False)


    for i in range(verts):

        x = pm.getAttr(('%s.vlist[0].vertex[%i].xVertex'%(tweak, i)))
        y = pm.getAttr(('%s.vlist[0].vertex[%i].yVertex'%(tweak, i)))
        z = pm.getAttr(('%s.vlist[0].vertex[%i].zVertex'%(tweak, i)))

        if not (x+y+z) == 0:
            pm.error('You have used the tweak node. No me gusta. If you really wanna clear it, run clearTweaks and try again. It will save what you have')

    #ok, let's get started, first instance the original mesh
    sculptTrans = pm.instance(base, n=('%s_corrective_sculpt'%base))[0]
    pm.reorderDeformers(skin, tweak, base)
    pm.setAttr('%s.v'%base, False)

    #Here, we'll make a duplicate of the base to look back on later if need be (for instance, using sculpt geometry tends to not register on tweak)
    baseRef = pm.duplicate(base, n='%s_editReference'%base)[0]
    pm.connectAttr(('%s.outMesh' %baseRef.getShapes()[1]), ('%s.inMesh' %baseRef.getShape()))

    #We'll also hook up the original so we can get it later
    pm.addAttr(sculptTrans, ln='baseTransform', at='message')
    pm.addAttr(sculptTrans, ln='baseReference', at='message')
    pm.connectAttr('%s.message'%base, '%s.baseTransform'%sculptTrans)
    pm.connectAttr('%s.message'%baseRef, '%s.baseReference'%sculptTrans)

    #now to keep things from changing between functions, we'll lock the three nodes involved in the
    #other script so our pesky little user won't delete or rename anything
    pm.lockNode(base, l=True)
    pm.lockNode(sculptTrans, l=True)
def placeHighLight(*args):
    ### UI setup 
    global UI_name
    UI_name = [ 'txtBtn_light', 'txtBtn_camera', 'txtBtn_object', 'txtBtn_HLitPoint', 'btn_placeHLit', 'chk_interaction' ]
    
    if pm.window( 'winPlaceHLit', exists=True ):
        pm.deleteUI( 'winPlaceHLit', window=True )
        
    ui_layout['window'] = pm.window( 'winPlaceHLit', title='Place Highlight', sizeable=False, h=100, w=250 )
    ui_layout['mainLayout'] = pm.columnLayout( columnAlign='left', columnAttach=['left', 0] )
    
    #// get active camera
    activeViewCamera = getActiveCam()
    
    '''loc_light_probe = pm.createNode('locator', name='light_probe')
    pm.lockNode(loc_light_probe, lock=False)'''

    #// sub layout
    #// sub1
    ui_layout['ui_sub1'] = pm.rowLayout(nc=2, cw=[(1, 210), (2, 40)], p=ui_layout['mainLayout'] )
    pm.textFieldButtonGrp( UI_name[0], label='Light: ', text='', buttonLabel='Pick',editable=False, buttonCommand='pickLit()', cw=[(1,50), (2,120), (3,40)], p=ui_layout['ui_sub1'] )
    pm.button( 'btn_sel_light' ,label='Sel', command=pm.Callback( doSelItem, UI_name[0] ), p=ui_layout['ui_sub1'] )
    
    #// sub2
    ui_layout['ui_sub2'] = pm.rowLayout(nc=2, cw=[(1, 210), (2, 40)], p=ui_layout['mainLayout'] )
    pm.textFieldButtonGrp( UI_name[1], label='Camera: ', text=activeViewCamera, buttonLabel='Pick', editable=False, buttonCommand='pickCam()', cw=[(1,50), (2,120), (3,40)], p=ui_layout['ui_sub2'] )
    pm.button( 'btn_sel_camera' ,label='Sel', command=pm.Callback( doSelItem, UI_name[1] ), p=ui_layout['ui_sub2'] )
    
    #// sub3
    ui_layout['ui_sub3'] = pm.rowLayout(nc=2, cw=[(1, 210), (2, 40)], p=ui_layout['mainLayout'] )
    pm.textFieldButtonGrp( UI_name[2], label='Object: ', text='', buttonLabel='Pick', editable=False, buttonCommand='pickTgtObj()', cw=[(1,50), (2,120), (3,40)], p=ui_layout['ui_sub3'] )
    pm.button( 'btn_sel_obj' ,label='Sel', command=pm.Callback( doSelItem, UI_name[2] ), p=ui_layout['ui_sub3'] )
    
    #// sub4
    ui_layout['ui_sub4'] = pm.rowLayout(nc=2, cw=[(1, 210), (2, 40)], p=ui_layout['mainLayout'] )    
    pm.textFieldButtonGrp( UI_name[3], label='Point: ', text='', buttonLabel='Pick', editable=False, buttonCommand='pickHLitPt()', cw=[(1,50), (2,120), (3,40)], p=ui_layout['ui_sub4'] )
    pm.button( 'btn_sel_point' ,label='Sel', command=pm.Callback( doSelItem, UI_name[3] ), p=ui_layout['ui_sub4'] )
    
    #// sub5
    ui_layout['ui_sub5'] = pm.rowLayout(nc=2, cw=[(1, 70), (2, 50)], p=ui_layout['mainLayout'] )
    pm.button( UI_name[4] ,label='Place Light!', command='doPlaceHLight()', p=ui_layout['ui_sub5'] )    
    pm.checkBox( UI_name[5], label='interactive mode', onCommand=pm.Callback( doInteractionON ), offCommand=pm.Callback( doInteractionOFF ), p=ui_layout['ui_sub5'] )
    
    
    pm.showWindow( ui_layout['window'] )
    
    pm.spaceLocator( name='light_probe' )
    pm.lockNode( 'light_probe', lock=True )
    pm.textFieldButtonGrp( 'txtBtn_HLitPoint', edit=True, text='light_probe' )
    
    #// clean make live and scriptJob after exit script
    pm.scriptJob( uiDeleted=[ ui_layout['window'], pm.Callback( flushScript ) ] )
Exemple #24
0
def SCENE_kill_turtle_plugin():
    ''' removes turtle maya plugin from scene '''
    import pymel.core as pm
    try:
        pm.lockNode('TurtleDefaultBakeLayer', lock=False)
        pm.delete('TurtleDefaultBakeLayer')
    except RuntimeError:
        pass
    try:
        pm.lockNode('TurtleBakeLayerManager', lock=False)
        pm.delete('TurtleBakeLayerManager')
    except RuntimeError:
        pass
    try:
        pm.lockNode('TurtleRenderOptions', lock=False)
        pm.delete('TurtleRenderOptions')
    except RuntimeError:
        pass
    try:
        pm.lockNode('TurtleUIOptions', lock=False)
        pm.delete('TurtleUIOptions')
    except RuntimeError:
        pass
    try:
        pm.unloadPlugin("Turtle.mll")
    except ValueError:
        msg, status = 'Unable to unload Turtle', 0

    msg, status = 'Turtle Killed', 1
    return msg, status
Exemple #25
0
    def delete_module(self, node):
        """deletes Module """

        node = pm.PyNode(node)
        if node.hasAttr("MetaNode"):
            module_container = utils.getModuleMetaInfo(node, "ModuleContainer")
        else:
            return

        pm.lockNode(module_container, lock = False)
        module_namespace = utils.getModuleMetaInfo(node, "Namespace")
        pm.delete(module_container)
        pm.namespace(setNamespace = ":")
        pm.namespace(removeNamespace = module_namespace)
def run():
    if pm.nodeType(pm.ls(sl=True)[0]) == 'reference':
        result = pm.promptDialog(title='Rename Object',
                                 message='Enter Name:',
                                 button=['OK', 'Cancel'],
                                 defaultButton='OK',
                                 cancelButton='Cancel',
                                 dismissString='Cancel')

        if result == 'OK':
            name = pm.promptDialog(query=True, text=True)
            if name != '':
                pm.lockNode(pm.ls(sl=True)[0], l=False)
                pm.rename(pm.ls(sl=True)[0], name)
                pm.lockNode(pm.ls(sl=True)[0])
Exemple #27
0
def createRigBotMetadataNode():
    """
	Creates or gets existing rigbot metadata node for storing information such as bind pose metadata.
	:return: PyNode of rigbot container.
	"""
    if pm.objExists('rigbot'):
        rb_node = pm.PyNode('rigbot')
    else:
        rb_node = pm.createNode('container', n='rigbot')
        # TODO:
        rb_node.iconName.set(
            r'C:\Users\iaman\Documents\maya\scripts\rigbot\icons\R50.png')
        pm.lockNode(rb_node, lock=True)

    return rb_node
	def SetupInterpolation(self, _unlockContainer = False, *args):
		previousSelection = pm.ls(selection = True)
		
		if _unlockContainer:
			pm.lockNode(self.containerName, lock = False, lockUnpublished = False)
		
		joints = self.GetJoints()
		numberOfJoints = len(joints)
		
		startControl = self.GetTranslationControl(joints[0])
		endControl = self.GetTranslationControl(joints[numberOfJoints - 1])
		
		pointConstraints = []
		
		for i in range(1, numberOfJoints - 1):
			material = "%s_m_translation_control" %joints[i]
			pm.setAttr("%s.colorR" %material, 0.815)
			pm.setAttr("%s.colorG" %material, 0.629)
			pm.setAttr("%s.colorB" %material, 0.498)
			
			translationControl = self.GetTranslationControl(joints[i])
			
			# Calculate constraint influence depending of distance from start/end
			endWeight = 0.0 + (float(i) / (numberOfJoints - 1))
			startWeight = 1.0 - endWeight
			
			# point constraint between start/end
			pointConstraints.append(pm.pointConstraint(startControl, translationControl, maintainOffset = False, weight = startWeight))
			pointConstraints.append(pm.pointConstraint(endControl, translationControl, maintainOffset = False, weight = endWeight))
			
			# Lock translation attribute of control
			for attr in [".translateX", ".translateY", ".translateZ"]:
				pm.setAttr("%s%s" %(translationControl, attr), lock = True)
		
		interpolationContainer = pm.container(name = "%s:interpolation_container" %self.moduleNamespace)
		utils.AddNodeToContainer(interpolationContainer, pointConstraints)
		utils.AddNodeToContainer(self.containerName, interpolationContainer)
		
		if _unlockContainer:
			pm.lockNode(self.containerName, lock = True, lockUnpublished = True)
		
		
		# Reselect initial selection
		if len(previousSelection) > 0:
			pm.select(previousSelection, replace = True)
		else:
			pm.select(clear = True)
	def Lock_phase1(self):

		# Gather and return all require information from this module's control objects

		# jointPositions = List of joint position, from root down the hierarchy
		# jointOrientations = list of orientations, or list of axis information (orientJoint and secondaryAxisOrient for joint command)
		#               # These are passed in the following tuple: (orientation, None) or (None, axisInfo)

		# jointRotationOrder = list of joint rotation orders (integer values gathered with getAttr)
		# jointPreferredAngles = list of joint preferred angles, optional (can pass None)
		# hookObject = self.FindHookObjectForLock()
		# rootTransform = bool, either true or false. True = rotate, translate and scale on root joint. False = rotate only

		# moduleInfo = (jointPositions, jointOrientations, jointRotationOrders, jointPreferredAngles, hookObject, rootTransform)
		# return moduleInfo
		
		moduleInfo = hingeJoint.HingeJoint.Lock_phase1(self)
		
		jointPositions = moduleInfo[0]
		jointOrientationValues = moduleInfo[1][0]
		jointRotationOrders = moduleInfo[2]
		
		joints = self.GetJoints()
		for i in range(3, 5):
			joint = joints[i]
			
			jointPositions.append(pm.xform(joint, query = True, worldSpace = True, translation = True))
			jointRotationOrders.append(pm.getAttr("%s.rotateOrder" %joint))
		
		pm.lockNode(self.containerName, lock = False, lockUnpublished = False)
		
		jointNameInfo = utils.StripAllNamespaces(joints[1])
		cleanParent = "%s:IK_%s" %(jointNameInfo[0], jointNameInfo[1])  # ikKnee
		
		# Get orientation values for ankle and ball joints
		deleteJoints = []
		for i in range(2, 4):
			orientationInfo = self.OrientationControlledJoint_getOrientation(joints[i], cleanParent)
			jointOrientationValues.append(orientationInfo[0])
			cleanParent = orientationInfo[1]
			deleteJoints.append(cleanParent)
		
		pm.delete(deleteJoints)
		
		pm.lockNode(self.containerName, lock = True, lockUnpublished = True)
		
		return moduleInfo
Exemple #30
0
    def _delete_nodes(cls, nodes, message_base):
        """
        Delete passed nodes and return message.

        :param list nodes: list of network nodes
        :param string message_base: Message about why the node was deleted
        :return string: Description of nodes deleted.
        """
        message = ''
        for node in reversed(nodes):
            cls.network_nodes.remove(node)
            message += '{0}: {1}\n'.format(message_base, node.name())
            pm.lockNode(node, lock=False)
            pm.disconnectAttr(node)
            pm.delete(node)
            nodes.remove(node)
        return message
Exemple #31
0
    def _delete_metas(cls, metanodes, message_base):
        """
        Delete passed Metanodes and return message.

        :param list metanodes: list of meta classes
        :param string message_base: Message about why the Metanode was deleted
        :return string: Description of Metanodes deleted.
        """
        message = ''
        for metanode in reversed(metanodes):
            metanodes.remove(metanode)
            cls.network_nodes.remove(metanode.node)
            message += '{0}: {1}\n'.format(message_base, metanode.name)
            pm.lockNode(metanode.node, lock=False)
            pm.disconnectAttr(metanode.node)
            pm.delete(metanode.node)
        return message
Exemple #32
0
    def run(self):
        self.analyze_list = ["Start", "End", 'userRenderer', 'imageFilePrefix', "Ext", "dynMemLimit", \
                             'camera', 'render_camera', "render_layer", 'renderable_layer', 'width', \
                             'height', 'preMel', 'postMel', 'preRenderLayerMel', 'postRenderLayerMel', 'preRenderMel','postRenderMel']

        self.assets_node_dict = {'file': 'fileTextureName', 'aiImage': 'filename', 'alTriplanar': 'texture',\
                                 'AlembicNode': 'abc_File', 'pgYetiMaya': 'cacheFileName', 'aiStandIn': 'dso', \
                                'RMSGeoLightBlocker': 'Map', 'VRayMesh': 'fileName', 'VRayLightIESShape': 'iesFile', \
                                'diskCache': 'cacheName', 'RealflowMesh': 'Path', 'mip_binaryproxy': 'object_filename', \
                                'mentalrayLightProfile': 'fileName', 'aiPhotometricLight': 'ai_filename',\
                                'cacheFile': 'cachePath', 'VRayVolumeGrid': 'inFile'}

        self.assets_node_list = [{"file": "fileTextureName"},{"VRayMesh": "fileName"},{"AlembicNode": "abc_File"},\
                                 {"pgYetiMaya": "groomFileName"},{"pgYetiMaya": "cacheFileName"},{"aiImage": "filename"},\
                                 {"RMSGeoLightBlocker": "Map"},{"PxrStdEnvMapLight": "Map"},{"VRaySettingsNode": "imap_fileName2"}, \
                                 {"VRaySettingsNode": "pmap_file2"}, {"VRaySettingsNode": "lc_fileName"},\
                                 {"VRaySettingsNode": "shr_file_name"}, {"VRaySettingsNode": "causticsFile2"}, \
                                 {"VRaySettingsNode": "imap_fileName"},{"VRaySettingsNode": "pmap_file"}, {"VRaySettingsNode": "fileName"}, \
                                 {"VRayLightIESShape": "iesFile"},{"diskCache": "cacheName"}, {"miDefaultOptions": "finalGatherFilename"}, \
                                 {"RealflowMesh": "Path"}, {"aiStandIn": "dso"}, {"mip_binaryproxy": "object_filename"},\
                                 {"mentalrayLightProfile": "fileName"}, {"aiPhotometricLight": "ai_filename"}, \
                                 {"VRayVolumeGrid": "inFile"}, {"file": "fileTextureName"}, {"RedshiftDomeLight": "tex0"},\
                                 {"RedshiftSprite": "tex0"}, {"ExocortexAlembicXform": "fileName"}, {"ffxDyna": "output_path"}, \
                                 {"ffxDyna": "wavelet_output_path"}, {"ffxDyna": "postprocess_output_path"},\
                                 {"RedshiftIESLight": "profile"}, {"RedshiftDomeLight": "tex1"}, \
                                 {"RedshiftEnvironment": "tex0"}, {"RedshiftEnvironment": "tex1"}, {"RedshiftEnvironment": "tex2"},\
                                 {"RedshiftEnvironment": "tex3"}, {"RedshiftEnvironment": "tex4"},\
                                 {"RedshiftLensDistortion": "LDimage"},{"RedshiftLightGobo": "tex0"}, {"RedshiftNormalMap": "tex0"},\
                                 {"RedshiftOptions": "irradianceCacheFilename"}, {"RedshiftOptions": "photonFilename"},\
                                 {"RedshiftOptions": "irradiancePointCloudFilename"},{"RedshiftOptions": "subsurfaceScatteringFilename"}, \
                                 {"RedshiftProxyMesh": "fileName"}, {"RedshiftVolumeShape": "fileName"},\
                                 {"RedshiftBokeh": "dofBokehImage"}, {"RedshiftCameraMap": "tex0"},{"RedshiftDisplacement": "texMap"},\
                                 {"alTriplanar": "texture"},{"cacheFile": "cachePath"},{"gpuCache": "cacheFileNam"}]

        print "[Rayvision]: open maya file " + self["cg_file"]
        self.set_env()
        # self.set_project()
        try:
            cmds.file(self["cg_file"], o=1, force=1, ignoreVersion=1, prompt=0)
        except:
            pass
        print "[Rayvision]: open maya ok."
        pm.lockNode('defaultRenderGlobals', lock=False)
        # self.set_env()
        self.get_rendersetting()
Exemple #33
0
def deleteUnknownNode():
    '''
    Delete unknown Nodes.
    '''
    for unknownNode in pm.ls(type='unknown'):
        try:
            deletedNodeName = str(unknownNode)
            pm.delete(unknownNode)
            print 'Delete :', deletedNodeName
        except:
            try:
                pm.lockNode(l=False)
                deletedNodeName = str(unknownNode)
                pm.delete(unknownNode)
                print 'Delete :', deletedNodeName
            except:
                traceback.print_exc()
            else:
                pass
Exemple #34
0
def deleteUnknownNode ():
    '''
    Delete unknown Nodes.
    '''
    for unknownNode in pm.ls(type='unknown') :
        try :
            deletedNodeName = str(unknownNode)
            pm.delete(unknownNode)
            print 'Delete :', deletedNodeName
        except :
            try:
                pm.lockNode(l=False)
                deletedNodeName = str(unknownNode)
                pm.delete(unknownNode)
                print 'Delete :', deletedNodeName
            except:
                traceback.print_exc()
            else:
                pass
	def __init__(self):
		
		character = self.FindSelectedCharacter()
		
		if character == None:
			return
		
		niceName = character.partition("__")[2]
		
		result = pm.confirmDialog(title = "Delete Character", message = 'Are you sure you want to delete the character "%s"? \nCharacter deletion cannot be undone.' %niceName, button = ["Yes", "Cancel"], defaultButton = "Yes", cancelButton = "Cancel", dismissString = "Cancel")
		if result == "Cancel":
			return
		
		characterContainer = "%s:character_container" %character
		
		# Unlock and delete selected character
		pm.lockNode(characterContainer, lock = False, lockUnpublished = False)
		pm.delete(characterContainer)
		
		# Collect list of blueprints used by this character
		pm.namespace(setNamespace = character)
		blueprintNamespaces = pm.namespaceInfo(listOnlyNamespaces = True)
		
		# Loop through blueprint namespaces
		for blueprintNamespace in blueprintNamespaces:
			pm.namespace(setNamespace = ":")
			pm.namespace(setNamespace = blueprintNamespace)
			
			# Collect module namespaces within each blueprint
			moduleNamespaces = pm.namespaceInfo(listOnlyNamespaces = True)
			pm.namespace(setNamespace = ":")
			
			# Remove the module namespaces
			if moduleNamespaces != None:
				for moduleNamespace in moduleNamespaces:
					pm.namespace(removeNamespace = moduleNamespace)
			
			# Remove the blueprint namespaces
			pm.namespace(removeNamespace = blueprintNamespace)
		
		# Remove the character namespace
		pm.namespace(removeNamespace = character)
	def DeleteInterpolation(self, *args):
		pm.lockNode(self.containerName, lock = False, lockUnpublished = False)
		
		joints = self.GetJoints()
		
		for i in range(1, len(joints) - 1):
			translationControl = self.GetTranslationControl(joints[i])
			
			for attr in [".translateX", ".translateY", ".translateZ"]:
				pm.setAttr("%s%s" %(translationControl, attr), lock = False)
			
			material = "%s_m_translation_control" %joints[i]
			
			pm.setAttr("%s.colorR" %material, 0.758)
			pm.setAttr("%s.colorG" %material, 0.051)
			pm.setAttr("%s.colorB" %material, 0.102)
		
		pm.delete("%s:interpolation_container" %self.moduleNamespace)
		
		pm.lockNode(self.containerName, lock = True, lockUnpublished = True)
	def AttachGeometryToBlueprint_skinning(self, _blueprintJoints, _geometry):
		
		blueprintModules = set([])
		
		# Get namespaces of joint chains
		for joint in _blueprintJoints:
			blueprintNamespace = utils.StripLeadingNamespace(joint)[0]
			blueprintModules.add(blueprintNamespace)
		
		
		# Unlock containers
		for module in blueprintModules:
			pm.lockNode("%s:module_container" %module, lock = False, lockUnpublished = False)
		
		# Attach all geometry to joint chain
		for geo in _geometry:
			pm.skinCluster(_blueprintJoints, geo, toSelectedBones = True, name = "%s_skinCluster" %geo)
		
		# Lock containers
		for module in blueprintModules:
			pm.lockNode("%s:module_container" %module, lock = True, lockUnpublished = True)
 def write_post_frame_ini(self):
     pm.lockNode('defaultRenderGlobals', lock=False)
     render_node = pm.PyNode("defaultRenderGlobals")
     render_name = render_node.currentRenderer.get()
 
     render_node.postMel.set(l=0)
     render_node.preRenderLayerMel.set(l=0)
     render_node.postRenderLayerMel.set(l=0)
     render_node.preRenderMel.set(l=0)
     render_node.postRenderMel.set(l=0)
 
     preMel = render_node.preMel.get()
     postMel = render_node.postMel.get()
     preRenderLayerMel = render_node.preRenderLayerMel.get()
     postRenderLayerMel = render_node.postRenderLayerMel.get()
     preRenderMel = render_node.preRenderMel.get()
     postRenderMel = render_node.postRenderMel.get()
 
     current_frame = int(cmds.currentTime( query=True ))
     frame_out_ini = "[_____render end_____]"+ "[" + str(current_frame) + "]" + "\n"
     print frame_out_ini
Exemple #39
0
def bdUnlockNodes():
    '''
    Category: General
    '''
    unlockError = False
    selection = pm.ls(sl=1)
    returnMessage = 'No return message'

    if selection:
        for node in selection:
            lockStatus = pm.lockNode(node, q=True)
            for response in lockStatus:
                if response != False:
                    try:
                        pm.lockNode(node, lock=False)
                        returnMessage += ('Unlocked: ' + node + '\n')
                    except:
                        returMessage += ('Error: Could not unlock ' + node +
                                         '\n')
    else:
        returnMessage = 'Nothing selected'

    return returnMessage
Exemple #40
0
def renameDuplicates(nodes=None, splitChar='', padding=2):
    # if an xform name contains a '|', it's appearing more than once and we'll have to rename it.
    badXforms = nodes
    if nodes == None:
        badXforms = [f.name() for f in pm.ls() if '|' in f.name()]
    else:
        badXforms = [f.name() for f in nodes if '|' in f.name()]

    badXformsUnlock = [
        f for f in badXforms if pm.lockNode(f, q=1, lock=1)[0] == False
    ]
    count = 0
    addChar = padding + len(splitChar)
    # sort list by the number of '|' in  name so we can edit names from the bottom of the hierarchy up,
    countDict = {}
    for f in badXformsUnlock:
        countDict[f] = f.count('|')
    # now sort the dictionary by value, in reverse, and start renaming.
    for key, value in sorted(countDict.iteritems(),
                             reverse=True,
                             key=lambda (key, value): (value, key)):
        n = 1
        newObj = pm.rename(
            key,
            key.split('|')[-1] + splitChar + str(n).zfill(padding))

        while newObj.count('|') > 0:
            #PREV INFINITE LOOP PROBLEM: if the transform and the shape are named the same
            n += 1
            basename = newObj.split('|')[-1]

            newName = basename[0:-addChar] + splitChar + str(n).zfill(padding)
            newObj = pm.rename(newObj, newName)
        print 'renamed %s to %s' % (key, newObj)
        count = count + 1
    if count < 1:
        print 'No duplicate names found.'
    else:
        print 'Found and renamed ' + str(
            count
        ) + ' objects with duplicate names. Check script editor for details.'
    return badXforms
Exemple #41
0
def CleanShadingDelivery():
    """CheckSceneMaya"""
    """
    Clean Maya File
    Maya Plugins
    """
    import pymel.core as pm

    Delete = pm.delete(pm.ls(type="unknown"))

    plugins_list = pm.unknownPlugin(q=True, l=True)

    if plugins_list <= 0:

        print 'CleanScene'

    else:

        try:
            for plugin in plugins_list:
                print '---Delete Nodes---> ', (plugin)
                print ''
                pm.unknownPlugin(plugin, r=True)
        except:

            pass

        try:
            [
                pm.lockNode('TurtleDefaultBakeLayer', lock=False)
                for node in pm.ls()
            ]

            pm.delete('TurtleDefaultBakeLayer')

        except:
            pass

    pm.inViewMessage(msg='<hl>CleanScene</hl>.', pos='midCenter', fade=True)
 def ProcessGroup(self, _group, _groupParent):
     
     import System.groupSelected as groupSelected
     reload(groupSelected)
     
     tempGroup = pm.duplicate(_group, parentOnly = True, inputConnections = True)[0]
     emptyGroup = pm.group(empty = True)
     pm.parent(tempGroup, emptyGroup, absolute = True)
     
     scaleAxis = ".scaleX"
     if self.mirrorPlane == "XZ":
         scaleAxis = ".scaleY"
     elif self.mirrorPlane == "XY":
         scaleAxis = ".scaleZ"
     
     pm.setAttr("%s%s" %(emptyGroup, scaleAxis), -1)
     
     instance = groupSelected.GroupSelected()
     groupSuffix = _group.partition("__")[2]
     newGroup = instance.CreateGroupAtSpecified("%s_mirror" %groupSuffix, tempGroup, _groupParent)
     
     pm.lockNode("Group_container", lock = False, lockUnpublished = False)
     pm.delete(emptyGroup)
     
     for moduleLink in ( (_group, newGroup), (newGroup, _group) ):
         attributeValue = "%s__" %moduleLink[1]
         
         if self.mirrorPlane == "YZ":
             attributeValue += "X"
         elif self.mirrorPlane == "XZ":
             attributeValue += "Y"
         elif self.mirrorPlane == "XY":
             attributeValue += "Z"
     
         pm.select(moduleLink[0], replace = True)
     
         pm.addAttr(dataType = "string", longName = "mirrorLinks", keyable = False)
         pm.setAttr("%s.mirrorLinks" %moduleLink[0], attributeValue, type = "string")
     
     pm.select(clear = True)
     
     children = pm.listRelatives(_group, children = True)
     children = pm.ls(children, transforms = True)
     
     # Recursively process group heirarchy
     for child in children:
         if child.find("Group__") == 0:
             self.ProcessGroup(child, newGroup)
         else:
             childNamespaces = utils.StripAllNamespaces(child)
             
             if childNamespaces != None and childNamespaces[1] == "module_transform":
                 for module in self.moduleInfo:
                     if childNamespaces[0] == module[0]:
                         moduleContainer = "%s:module_container" %module[1]
                         pm.lockNode(moduleContainer, lock = False, lockUnpublished = False)
                         
                         moduleTransform = "%s:module_transform" %module[1]
                         pm.parent(moduleTransform, newGroup, absolute = True)
                         
                         pm.lockNode(moduleContainer, lock = True, lockUnpublished = True)
 def MirrorModules(self):
     mirrorModulesProgress_UI = pm.progressWindow(title = "Mirror Module(s)", status = "This may take a few minutes...", isInterruptable = False)
     mirrorModulesProgress = 0
     
     mirrorModulesProgress_stage1_proportion = 15
     mirrorModulesProgress_stage2_proportion = 70
     mirrorModulesProgress_stage3_proportion = 10
     
     moduleNameInfo = utils.FindAllModuleNames("/Modules/Blueprint")
     validModules = moduleNameInfo[0]
     validModuleNames = moduleNameInfo[1]
     
     for module in self.moduleInfo:
         moduleName = module[0].partition("__")[0]
         
         if moduleName in validModuleNames:
             index = validModuleNames.index(moduleName)
             module.append(validModules[index])
     
     
     # COLLECT DATA FOR MIRRORING
     mirrorModulesProgress_progressIncrement = mirrorModulesProgress_stage1_proportion / len(self.moduleInfo)
     for module in self.moduleInfo:
         userSpecifiedName = module[0].partition("__")[2]
         
         mod = __import__("Blueprint.%s" %module[5], {}, {}, [module[5]])
         reload(mod)
         
         moduleClass = getattr(mod, mod.CLASS_NAME)
         moduleInst = moduleClass(userSpecifiedName, None)
         
         hookObject = moduleInst.FindHookObject()
         
         newHookObject = None
         hookModule = utils.StripLeadingNamespace(hookObject)[0]
         
         hookFound = False
         for m in self.moduleInfo:
             if hookModule == m[0]:
                 hookFound = True
                 
                 if m == module:
                     continue
                 
                 hookObjectName = utils.StripLeadingNamespace(hookObject)[1]
                 newHookObject = "%s:%s" %(m[1], hookObjectName)
         
         if not hookFound:
             newHookObject = hookObject
         
         module.append(newHookObject)
         
         hookConstrained = moduleInst.IsRootConstrained()
         module.append(hookConstrained)
         
         
         # Increment progress bar
         mirrorModulesProgress += mirrorModulesProgress_progressIncrement
         pm.progressWindow(mirrorModulesProgress_UI, edit = True, progress = mirrorModulesProgress)
     
     
     
     
     # MIRROR MODULE
     mirrorModulesProgress_progressIncrement = mirrorModulesProgress_stage2_proportion / len(self.moduleInfo)
     for module in self.moduleInfo:
         newUserSpecifiedName = module[1].partition("__")[2]
         
         mod = __import__("Blueprint.%s" %module[5], {}, {}, [module[5]])
         reload(mod)
     
         moduleClass = getattr(mod, mod.CLASS_NAME)
         moduleInst = moduleClass(newUserSpecifiedName, None)
         
         moduleInst.Mirror(module[0], module[2], module[3], module[4])
         
         # Increment progress bar
         mirrorModulesProgress += mirrorModulesProgress_progressIncrement
         pm.progressWindow(mirrorModulesProgress_UI, edit = True, progress = mirrorModulesProgress)
     
     
     
     
     # MIRROR HOOKED RELATIONS
     mirrorModulesProgress_progressIncrement = mirrorModulesProgress_stage3_proportion / len (self.moduleInfo)
     for module in self.moduleInfo:
         newUserSpecifiedName = module[1].partition("__")[2]
         
         mod = __import__("Blueprint.%s" %module[5], {}, {}, [module[5]])
         reload(mod)
         
         moduleClass = getattr(mod, mod.CLASS_NAME)
         moduleInst = moduleClass(newUserSpecifiedName, None)
         
         moduleInst.Rehook(module[6])
         
         hookConstrained = module[7]
         if hookConstrained:
             moduleInst.ConstrainRootToHook()
         
         mirrorModulesProgress += mirrorModulesProgress_progressIncrement
         pm.progressWindow(mirrorModulesProgress_UI, edit = True, progress = mirrorModulesProgress)
     
     
     
     if self.group != None:
         pm.lockNode("Group_container", lock = False, lockUnpublished = False)
         
         groupParent = pm.listRelatives(self.group, parent = True)
         
         if groupParent != []:
             groupParent = groupParent = [0]
         
         self.ProcessGroup(self.group, groupParent)
         
         pm.lockNode("Group_container", lock = True, lockUnpublished = True)
         
         pm.select(clear = True)
     
     
     pm.progressWindow(mirrorModulesProgress_UI, edit = True, endProgress = True)
     
     utils.ForceSceneUpdate()
    def addTag(self, topNode):
        self.tagObj = tifr.TagsInFrustum()
        masters = self.tagObj.getObjectInFrustum()
        if masters:
            self.tagObj.tagMasters(masters)

        if pm.objExists('|assets|lay'):
            pm.lockNode('|assets|lay', l=False)
            self.d_taged_nodes['ignored']['|assets|lay'] = pm.PyNode('|assets|lay')

        self.l_masters = self.getTailMaster(topNode)
        self.l_asset_ar, self.l_unload_ar, self.l_asb_ar = self.getAssemblyReference(topNode)
        l_unload_ar_path = [n.fullPath() for n in self.l_unload_ar]

        if self.cam:
            self.get_angle(self.cam, self.l_frames)

        if self.skip_unload:
            l_all_assets = self.l_masters + self.l_asset_ar
        else:
            l_all_assets = self.l_masters + self.l_asset_ar + self.l_unload_ar

        for m in l_all_assets:
            ref_path = self.getReferencePath(m)
            asset_name = self.findAssetName( ref_path )
            version_dir = self.find_version_dir( ref_path )
            xml_file = self.osPathConvert( version_dir +'/scene_graph_xml/'+ asset_name + '.xml' )
            if '/cty/' in version_dir:
                city_xml_path = self.find_city_path(ref_path)
                if city_xml_path: 
                    xml_file = city_xml_path

            ire = self.isReferenceEdited(m)
            if not os.path.isfile(xml_file):
                self.d_taged_nodes['ignored'][m.fullPath()] = m
                print '### find ignored', m.fullPath()
                print 'invalid xml', xml_file
                continue

            self.d_taged_nodes['ref'][m.fullPath()] = {'xml':xml_file, 'xml_reform':xml_file.replace('Z:/', '/mnt/proj/'), 'bb':None, 'node':m, 'xform':None, 'wform':None, 'isReferenceEdited':ire, 'loaded':True}
            if m.fullPath() in l_unload_ar_path:
                self.d_taged_nodes['ref'][m.fullPath()]['loaded'] = False

        self.find_ignore(topNode)

        for n_name in sorted(self.d_taged_nodes['ignored'].keys()):
            maya2scenegraphXML.setIgnore([n_name])
            #print 'ignore:', n_name

        for n_name in sorted(self.d_taged_nodes['no_bound'].keys()):
            maya2scenegraphXML.setBoundsWriteMode([n_name], value=False)
            #print 'no bound:', n_name

        for n_name in sorted(self.d_taged_nodes['ref'].keys()):
            m = self.d_taged_nodes['ref'][n_name]['node']

            self.d_taged_nodes['ref'][n_name]['bb'] = self.getBoundingBoxFromModelXML('hi', self.d_taged_nodes['ref'][n_name]['xml'])
            self.d_taged_nodes['ref'][n_name]['xform'], self.d_taged_nodes['ref'][n_name]['wform'] = self.getReferenceXform(m)
            maya2scenegraphXML.setReference([n_name], self.d_taged_nodes['ref'][n_name]['xml_reform'] )

            if self.d_taged_nodes['ref'][n_name]['loaded']:
                d_v = self.get_asset_v(m)
                maya2scenegraphXML.setArbAttr([n_name], 'modVersion', d_v['modv'], 'string')
                maya2scenegraphXML.setArbAttr([n_name], 'rigVersion', d_v['rigv'], 'string')
                maya2scenegraphXML.setArbAttr([n_name], 'lookPass', self.getReferencePass(m), 'string')

            if self.cam and self.d_angles.has_key(n_name):
                maya2scenegraphXML.setArbAttr([n_name], 'angle', str(max(self.d_angles[n_name]['angle'])), 'string')
                maya2scenegraphXML.setArbAttr([n_name], 'distance', str(min(self.d_angles[n_name]['distance'])), 'string')

            if self.isViewableMaster(m):
                maya2scenegraphXML.setArbAttr([n_name], 'viewable', 'yes', 'string')
            elif not self.check_asset_visible(m):
                maya2scenegraphXML.setArbAttr([n_name], 'hidden', 'yes', 'string')

            if self.isOverrideAR(m):
                print '[override]', m
                linked_name = self.getOverrideAR(m)
                if linked_name:
                    maya2scenegraphXML.setArbAttr([n_name], 'aniHidden', 'yes', 'string')
                    val = self.getModifiedName(n_name)
                    maya2scenegraphXML.setArbAttr([linked_name], 'aniOverride',val, 'string')
        
        # if layout or animation moves cache assets in scn, we'll record the <ori></ori>ginal value to each ar node
        # attribute name is 'asb_wform'
        if pm.objExists('|assets|scn'):
            self.compare_asb_trans('|assets|scn')
        
        return
Exemple #45
0
    def install_joints(self):
        """
        gathers information from the module and creates the joints
        """
        # create list of joints
        joints = []
        translation_controls = []
        # clear selection
        pm.select(cl = True)
        # set current namespace to root.  that way all namespaces will be child of the root only
        pm.namespace(setNamespace = ":")
        pm.namespace(add = self.userSpecifiedName)

        self.joints_grp = pm.group(empty = True, name = self.userSpecifiedName + ":joints_grp")
        self.misc_grp = pm.group(empty = True, name = self.userSpecifiedName + ":misc_grp")
        self.module_container = pm.container(name = self.userSpecifiedName + ":module_container" )
        self.networkNode()

        # creating joints this way because when you select a joint and create a joint it will correct orientation

        index = 0
        for joint in self.joint_info:
            joint_name = joint[0]
            joint_positions = joint[1]

            #  if not the root joint, selecting the parent joint
            if index > 0:
                pm.select(joints[index-1], replace = True)

            # create joint and append to joints list
            new_joint = pm.PyNode(pm.joint(name = self.userSpecifiedName + ":" + joint_name, position = joint_positions) )
            joints.append(new_joint)
            # if not the root joint, change the orient of the parent joint to defaults
            if index > 0:
                pm.joint(new_joint.getParent(), edit = True, orientJoint = "xyz", secondaryAxisOrient = "yup")

            pm.makeIdentity(new_joint, apply=True, translate=False, rotate=True, scale=False )

            utils.addNodeToContainer(self.module_container, new_joint, ihb = True, includeNetwork = True)
            # Publish and bind rotation values for current joint to cointainer before locking;
            # this is important for later use with IK system setup to be able to rotate the joints attributes.
            pm.container(self.module_container, edit=True, publishAndBind=[new_joint + ".rotate", joint_name + "_r"])
            pm.container(self.module_container, edit=True, publishAndBind=[new_joint + ".rotateOrder", joint_name + "_rotateOrder"])

            pm.addAttr(new_joint, longName = "Meta", at="message")
            self.meta_node.ModuleJoints[index].connect(new_joint.Meta)
            
            index += 1



        '''
        mirrorBehavior = True
        mirrorXY = False
        mirrorYZ = False
        mirrorXZ = False

        pm.mirrorJoint(joints[0], mirrorBehavior = mirrorBehavior, mirrorXY = mirrorXY, mirrorYZ = mirrorYZ, mirrorXZ = mirrorXZ)
        '''

        joints[0].setParent(self.joints_grp)
        joints[0].visibility.set(True)
        # TEMP- TURNING ON LOCAL AXIS
        for joint in joints:
            joint.displayLocalAxis.set(1)
            joint.template.set(1)


        # ------------------------------------------------------------------------- #
        # set up controls for the module
        module_control = controls.loadModuleControl(joints[0], self.userSpecifiedName, self.module_container)

        # install translation controls to each joint and parent it under the module control
        for joint in joints:
            #translation_controls[joint] = controls.loadTranslationControl(joint, self.userSpecifiedName, module_control)
            translation_controls.append(controls.loadTranslationControl(joint, self.userSpecifiedName,self.module_container, module_control) )

        # point constraint root control to root joint
        pm.pointConstraint(translation_controls[0][0], joints[0], maintainOffset = False, name = self.userSpecifiedName + ":" + joints[0].stripNamespace() + "_rootTransContConstraint")


        self.initializeParentModuleSetup(translation_controls[0][0])

        # ------------------------------------------------------------------------- #
        # set up stretch joint segments
        for index in range(len(joints) -1 ):
            # load joint rep onto joins
            # setup stretchy joint segments
            setupStretchyJointSegment = self.setupStretchyJointSegment(joints[index], joints[index + 1])
            setupStretchyJointSegment[0].setParent(self.misc_grp)
            setupStretchyJointSegment[1].setParent(self.joints_grp)

        # ------------------------------------------------------------------------- #
        # parent items
        #module_control_grp.setParent(self.module_container)
        utils.addNodeToContainer(self.module_container, [self.misc_grp, self.joints_grp, module_control], ihb = True, includeNetwork = True)


        # don't know why, but cannot full delete the transform node
        pm.container(self.module_container, edit=True, publishAndBind=[module_control + ".translate", module_control.stripNamespace() + "_translate"])
        pm.container(self.module_container, edit=True, publishAndBind=[module_control + ".rotate", module_control.stripNamespace() + "_rotate"])
        pm.container(self.module_container, edit=True, publishAndBind=[module_control + ".scale", module_control.stripNamespace() + "_globalScale"])

        # add meta information

        if self.module_container.hasAttr("MetaNode") == True:
            for node in pm.container(self.module_container, q = True, nodeList = True):
                if node.nodeType() != "network" or "joint":
                    if not node.hasAttr("MetaNode"):
                        pm.addAttr(node, longName="MetaNode", at="message")
                        self.meta_node.ModuleNodes.connect(node.MetaNode)

        self.install_customAttributes()
        # ------------------------------------------------------------------------- #
        # lock nodes
        pm.lockNode(self.module_container, lock = True, lockUnpublished = True)
        pm.select(cl = True)
Exemple #46
0
    def lock_joints1(self, module_information):
        """
        Locks blueprint module joints.
        Creates a blueprint set of joints that is driven by the animation modules.
        A creationPose set of joints is created so there is a fresh set of joints to duplicate from.

        Each animation module joint has a weighted value multiplied by its attribute value that plugs into
        an AddNode that contains the weighted values of an attribute(translation, rotation, scale) plus the
        weighted value from the creationPose joint equivalent, divided by the number of values in the AddNode.
        """
        _logger.debug("Locking module: {}".format(self.module_container))
        #  clear selection
        pm.select(clear=True )
        pm.namespace(setNamespace=":")


        joints = module_information[0]
        joint_positions = module_information[1]
        joint_orientations = module_information[2]
        joint_rotation_order = module_information[3]
        joint_preferredAngles = module_information[4]


        new_joints_list = []
        number_of_joints = len(joints)
        radius = 1

        if number_of_joints == 1:
            radius = 1.5

        for index in range(number_of_joints):

            new_joint_name = self.userSpecifiedName + "_" + str(self.joint_info[index][0].split("_joint")[0]) + "_bpJoint"
            # create joint and append to joints list
            new_joint = pm.joint(name = new_joint_name, position = joint_positions[index], rotationOrder = joint_rotation_order[index], radius = radius )

            # orient parent joints
            if index > 0:
                pm.joint(new_joint.getParent(), edit = True, orientJoint = "xyz", secondaryAxisOrient = "yup")
            
            # set joint orientation.  rotate values will be 0
            new_joint.setOrientation(joint_orientations[index])

            new_joint.setScaleCompensate(0)
            new_joint.displayLocalAxis.set(1)

            new_joints_list.append(new_joint)


        # create all the module container group and the group to hold all blueprint nodes and put everyone in the right place
        module_blueprint_group = pm.group(empty = True, a = True, name = self.userSpecifiedName + "_blueprint_group")
        module_container_group = pm.group(module_blueprint_group, a = True, name = self.userSpecifiedName + "_module_group")

        pm.parent(new_joints_list[0], module_blueprint_group, absolute=True)
        module_creationPose_group = pm.duplicate(module_blueprint_group, name=self.userSpecifiedName + "_creationPose_group", renameChildren=True)[0]
        module_creationPose_joints = module_creationPose_group.listRelatives(allDescendents = True)

        # rename creation pose joints
        index = 0
        for node in module_creationPose_joints:
            node.rename(self.userSpecifiedName + "_" + str(self.joint_info[index][0].split("_bpJoint")[0]) + "_cpJoint")
            node.visibility.set(False)
            index += 1


        # add all attributes
        if not module_container_group.hasAttr("DefaultWeight"):
            module_container_group.addAttr("DefaultWeight", at = "float", minValue = 0.0, maxValue = 1.0, hasMaxValue = True, hasMinValue = True, defaultValue = 1)
        if not module_container_group.hasAttr("ActiveModule"):
            module_container_group.addAttr("ActiveModule", at = "enum", en="None")


        for index in range(number_of_joints):
            pass






        # lock all attributes
        #for node in [module_blueprint_group, module_creationPose_group, module_container_group]:
        #    utils.lockAndHideAttributes(node, ["translate", "rotate", "scale", "visibility"])

        pm.select(clear=True )
        pm.lockNode(self.module_container, lock = False)
        pm.delete(self.module_container)
        pm.namespace(setNamespace = ":")
        pm.namespace(removeNamespace = self.userSpecifiedName)
import pymel.core as pc

nodes = pc.ls(sl=1)

for node in nodes:
    pc.lockNode(node, lock=0)
def start_cutting(progressControl):
    # Kill all jobs
    cmds.scriptJob(ka=True)

    exclude_shots = service_shots_status()

    # Get shots
    shots = pm.ls(type="shot", sl=1)
    allShots = pm.ls(type="shot")
    allCams = pm.ls(type="camera")
    if not shots: shots = allShots

    location_path = str(
        pm.scrollField('LOC', q=1, text=1).replace('\\\\omega\\' + PRJ_NAME,
                                                   '%root%'))
    cmds.progressBar('progress_control',
                     edit=True,
                     progress=0,
                     maxValue=len(shots),
                     visible=True)

    for count, shot in enumerate(shots):
        cmds.text('progress',
                  edit=True,
                  label=shot + '/' + shots[-1],
                  visible=True)
        if cmds.progressBar(progressControl, query=True, isCancelled=True):
            break
        if exclude_shots[0] not in str(shot) and exclude_shots[1] not in str(
                shot):
            print 'SHOT:', shot
            print 'SHOT type:', type(shot)
            #if count != 0:
            cmds.file(SCENE_FULLPATH,
                      prompt=False,
                      force=1,
                      open=1,
                      resetError=1)
            shot = fix_shot_naming(shot)
            shot_paths = get_shot_paths(shot)

            #remove audio
            audio = pm.ls(type='audio')
            for i in audio:
                pm.delete(i)

            #fix ref paths, remove all refs except exclude list and load location ref
            fix_ref_paths()
            replace_location(location_path, shot_paths['shot_filename'])

            # Get camera for this shot
            print '@DEBUG start Get camera for this shot'
            cam = pm.listConnections(shot, type="shape")
            print '@DEBUG cam', cam
            camShape = cmds.listRelatives(str(cam[0]), shapes=True)[0]
            print '@DEBUG camShape', camShape

            print '@DEBUG start Get camera for this shot2'
            if str(shot) in str(cam[0]) and 'Camera1' in str(cam[0]):
                camName = 'cam_' + str(cam[0]).split('_')[1].replace(
                    'Camera1', '')
                print 'CAMERA OK\n'
                cmds.rename(str(cam[0]), camName)
            elif str(cam[0]) == 'cam_' + str(shot):
                print 'NEW CAMERA OK\n'
                pass
            else:
                print 'create CAMERA for shot', shot, '\n'
                cloneCamera(cam, camShape, str(shot))

            #create image plane for shot camera
            im_plane = create_imagePlane(
                cam[0], shot, shot_paths['shot_cut_filename_path_unr'])

            #cleanup cameras
            tmp = getCameras()
            tmp.remove(str(cam[0]))
            print 'delete cam', str(cam[0]), tmp
            cmds.delete(tmp)  #delete unused cameras

            #create sound
            print '@DEBUG create sound'
            createSound(shot_paths['audio_filename_path_unr'])

            # get out shot's range and move all animation of it to 1st frame
            print '@DEBUG move all animation'
            sf = int(shot.getStartTime())
            ef = int(shot.getEndTime())
            alMoveACsegment(sf, ef)
            pm.playbackOptions(max=(1 + ef - sf),
                               ast=1,
                               aet=(1 + ef - sf),
                               min=1)
            print '@DEBUG move all animation1'
            print shots
            allShots = pm.ls(type='shot')
            pm.lockNode(allShots, lock=False)
            print '@DEBUG move all animation2'
            print shots
            pm.delete(allShots)

            #create destination folder for saving scene
            print '@DEBUG create destination folder'
            create_folder(shot_paths['shot_path_res'])

            #rename and save maya scene
            print '@DEBUG rename and save maya scene'
            cmds.file(rename=(shot_paths['shot_filename_path_res']))
            cmds.file(save=1, type="mayaAscii", options="v=0;", f=1)

            #copy scene to work path and ftp
            if cmds.checkBox('copy_flag', query=True, value=True) == True:
                copy_it(shot_paths['shot_filename_path_res'],
                        shot_paths['shot_filename_work_path_res'])

            if cmds.checkBox('copyftp_flag', query=True, value=True) == True:
                create_folder(shot_paths['shot_work_path_ftp'])
                copy_it(shot_paths['shot_filename_path_res'],
                        shot_paths['shot_filename_work_path_ftp'])

        cmds.progressBar(progressControl, edit=True, step=1)
	def ObjectSelected(self):
		objects = pm.ls(selection = True)
		
		pm.select(clear = True)
		
		
		if pm.window("modMaintenance_UI_window", exists = True):
			pm.deleteUI("modMaintenance_UI_window")
		
		
		characters = utils.FindInstalledCharacters()
		
		for character in characters:
			characterContainer = "%s:character_container" %character
			pm.lockNode(characterContainer, lock = False, lockUnpublished = False)
			
			blueprintInstances = utils.FindInstalledBlueprintInstances(character)
			
			for blueprintInstance in blueprintInstances:
				moduleContainer = "%s:%s:module_container" %(character, blueprintInstance)
				pm.lockNode(moduleContainer, lock = False, lockUnpublished = False)
				
				blueprintJointsGrp = "%s:%s:blueprint_joints_grp" %(character, blueprintInstance)
				
				# Change color of module joints depending on wether animation controls heve been installed or not
				if pm.getAttr("%s.controlModulesInstalled" %blueprintJointsGrp):
					# Blue
					pm.setAttr("%s.overrideColor" %blueprintJointsGrp, 6)
				else:
					# Grey
					pm.setAttr("%s.overrideColor" %blueprintJointsGrp, 2)
				
				pm.lockNode(moduleContainer, lock = True, lockUnpublished = True)
			
			pm.lockNode(characterContainer, lock = True, lockUnpublished = True)
		
		
		
		if len(objects) > 0:
			lastSelected = objects[len(objects)-1]
			
			lastSelected_stripNamespaces = utils.StripAllNamespaces(lastSelected)
			
			if lastSelected_stripNamespaces != None:
				lastSelected_withoutNamespaces = lastSelected_stripNamespaces[1]
				
				if lastSelected_withoutNamespaces.find("blueprint_") == 0:
					blueprintModule_fullNamespace = lastSelected_stripNamespaces[0]
					moduleContainer = "%s:module_container" %blueprintModule_fullNamespace
					
					pm.select(moduleContainer, replace = True)
					
					characterNamespace = utils.StripLeadingNamespace(lastSelected)[0]
					
					characterContainer = "%s:character_container" %characterNamespace
					
					containers = [characterContainer, moduleContainer]
					for container in containers:
						pm.lockNode(container, lock = False, lockUnpublished = False)
					
					
					# Change color of blueprint joints to red
					blueprintJointsGrp = "%s:blueprint_joints_grp" %blueprintModule_fullNamespace
					pm.setAttr("%s.overrideColor" %blueprintJointsGrp, 13)
					
					self.CreateUserInterface(blueprintModule_fullNamespace)
					
					for container in containers:
						pm.lockNode(container, lock = True, lockUnpublished = True)
		
		
		self.SetupSelectionScriptJob()
    def CreateGroup(self, _groupName):
        fullGroupName = "Group__%s" %_groupName
        
        # Check for valid names
        if pm.objExists(fullGroupName):
            pm.confirmDialog(title = "Name Conflict", message = 'Group "%s" already exits.' %_groupName, button= "Accept", defaultButton = "Accept")
            
            return None
        
        groupTransform = pm.rename(self.tempGroupTransform, fullGroupName)

        
        # Create container for grouped objects
        groupContainer = "Group_container"
        if not pm.objExists(groupContainer):
            pm.container(name = groupContainer)
        
        
        # Store containers to be grouped in a list
        containers = [groupContainer]
        for obj in self.objectsToGroup:
            if obj.find("Group__") == 0:
                continue
            
            objNamespace = utils.StripLeadingNamespace(obj)[0]
            containers.append("%s:module_container" %objNamespace)
        
        
        # Unlock all grouped containers
        for c in containers:
            pm.lockNode(c, lock = False, lockUnpublished = False)
        
        
        if len(self.objectsToGroup) != 0:
            
            # Group objects temprorarily to simulate final heirarchy
            tempGroup = pm.group(self.objectsToGroup, absolute = True)
            groupParent = pm.listRelatives(tempGroup, parent = True)
            
            
            if groupParent != []:
                pm.parent(groupTransform, groupParent[0], absolute = True)
            
            
            pm.parent(self.objectsToGroup, groupTransform, absolute = True)
            
            pm.delete(tempGroup)
        
        
        self.AddGroupToContainer(groupTransform)
        
        # Lock all group containers
        for c in containers:
            pm.lockNode(c, lock = True, lockUnpublished = True)
        
        
        # Make sure the created group is selected
        pm.setToolTo("moveSuperContext")
        pm.select(groupTransform, replace = True)
        
        return groupTransform
def run():
    if not pm.ls('cam_focus_*'):
        pm.warning(u'没有可以导出的相机')
        return

    if pm.ls(type='unknown'):
        pm.delete(pm.ls(type='unknown'))
    if pm.ls('shaveGlobals'):
        pm.lockNode(pm.ls('shaveGlobals'), l=False)
        pm.delete(pm.ls('shaveGlobals'))

    path_obj = pft.PathDetails.parse_path(pm.sceneName())
    pubfile = path_obj.getNewVersionForTask('cam-focus', publish=True)
    if not path_obj.user:
        pm.warning(u'请检查本场景文件的路径,特别注意下文件名本身')
        return
    os.makedirs(os.path.dirname(pubfile))

    # --------------------------------------------------------------------------------------------------------
    # 序列帧输出
    # projectdir = pm.Workspace.getPath()
    # imagedir = os.path.join(projectdir, 'images/focus')

    images_in_project = pm.workspace(
        en=pm.workspace('images', q=True, fre=True))
    imagedir = os.path.join(images_in_project, 'focus')

    # os.makedirs(os.path.join(os.path.dirname(pubfile), 'images'))
    # pm.sysFile(imagedir, copy=os.path.join(os.path.dirname(pubfile), 'images'))
    shutil.copytree(imagedir,
                    os.path.join(os.path.dirname(pubfile), 'images/focus'))
    # --------------------------------------------------------------------------------------------------------
    # 相机输出
    cams = map(
        lambda x: x.getParent(),
        filter(lambda x: x.name().startswith('cam_focus_'),
               pm.ls(type='camera')))
    pm.select(cams, r=True)
    camsFile = os.path.splitext(pubfile)[0] + '.ma'
    pm.exportSelected(camsFile, force=True)
    # --------------------------------------------------------------------------------------------------------
    # 生成缩略图
    mmfpeg = 'ffmpeg.exe'
    seqfile = os.path.normpath(
        os.path.join(os.path.dirname(pubfile), 'images/focus/focus.%04d.exr'))
    movfile = os.path.join(
        os.path.dirname(pubfile),
        '{}.mov'.format(os.path.basename(pubfile).split('.')[0]))
    beginframe, endframe = psg.get_cut_range(
        path_obj.project, '%s_%s' % (path_obj.seq, path_obj.shot))
    framenum = endframe - beginframe + 2
    # 这里有个bug在ffmpeg里
    convertcmd = '{} -apply_trc iec61966_2_1 -start_number 1001 -f image2 -r 24 -i {} -vcodec h264 -vframes {} -preset veryslow -qp 0 {}'.format(
        mmfpeg, seqfile, framenum, movfile)

    p = subprocess.Popen(convertcmd, shell=True, cwd=os.path.dirname(__file__))
    p.wait()
    # -----------------------------------------------------------------------------------
    # 上传shotgun
    versionID = psg.addToShotgun(camsFile, '')
    if versionID:
        psg.uploadQuicktime(versionID, movfile)
    # --------------------------------------------------------------------------------------------------------
    # 输出制作文件
    animSourceFile = os.path.join(
        os.path.dirname(pubfile),
        os.path.basename(pm.sceneName()).replace("anim", 'focus'))
    pm.saveAs(animSourceFile)

    # --------------------------------------------------------------------------------------------------------
    # 打开publish目录
    pm.warning(u'导出CamFocus相机完成,文件另存为完成,序列帧复制完成')
    os.startfile(os.path.dirname(pubfile))
Exemple #52
0
        #self.addAttr('Models','-'*50, l=True)
        self.addAttr('FaceGp','')
        self.addAttr('EyeGp','')
        self.addAttr('FaceDeformGp','')
        self.addAttr('FacialTargetPath','')
        #self.addAttr('Bones','-'*100, l=True)
        self.addAttr('HeadBone', 'CH_Head')
        self.addAttr('FacialBoneGp','')
        self.addAttr('EyeBoneGp','')
        self.addAttr('BlendshapeCtl','')
        self.addAttr('FacialCtl','')
        self.addAttr('EyeCtl','')
        self.addAttr('TongueCtl','')
        self.addAttr('JawCtl','')
#r9Meta.registerMClassInheritanceMapping()
if __name__ == 'main':
    try:
        networks = pm.ls(type=pm.nt.Network)
        networks.extend(pm.selected())
        for networknode in networks: 
            pm.lockNode(networknode, lock=False)
            pm.delete(networknode)
    except:
        pass
    myRigmetaGp = pm.nt.Transform(name='facialGP')
    myRigmeta = FacialRig(myRigmetaGp.name())
    myRigmeta.CharacterName='KG'
    #myRigmeta.addRigCtrl(pm.selected()[0],'new')
    #pm.select(myRigmeta)
    print myRigmeta
    #pm.delete(myRigmeta)
Exemple #53
0
def setAttrSpecial(obj, attr, value, prefix=None, channelBox=None, cb=None,
                   preserveValue=False, multi=False, keyable=False, k=False,
                   lock=False, l=False, append=False, **kwargs):
	"""
	Custom setAttr method

	*Arguments:*
		* ``None``

	*Keyword Arguments:*
		* ``None``

	*Returns:*
		* ``None``

	*Author:*
	* Charles.Wardlaw @kattkieru - http://www.skeletalstudios.com/
	"""

	if channelBox is None and cb is None:
		# special-- nothing was passed in
		channelBox = True
	elif channelBox is False or cb is False:
		channelBox = False
	else:
		channelBox = channelBox or cb
	keyable = keyable or k
	lock = lock or l

	attributeType = kwargs.pop("type", None)

	oldValue = None

	if not isinstance(obj, pymel.PyNode):
		obj = pymel.PyNode(obj)
		pymel.lockNode(obj, lock=False)

	attrName = "_".join([prefix, attr]) if prefix is not None else attr

	print(" Setting attr: %s (value %s)" % (attrName, str(value)))

	if attributeType is None:
		# try to intelligently guess the type from what"s been passed in
		if isinstance(value, (list,tuple)):
			if not len(value):
				raise ValueError("setAttrSpecial: empty list passed in.")
			if isinstance(value[0], pymel.PyNode) or isinstance(value[0], (str, unicode)) and cmds.objExists(value[0]):
				attributeType = "message"
				multi = True
			elif len(value) == 3 and unicode(value[0]).isnumeric():
				attributeType = "float3"
		elif isinstance(value, (pymel.dt.Point, pymel.dt.Vector)):
			attributeType = "float3"
		elif isinstance(value, pymel.PyNode) or pymel.objExists(value):
			attributeType = "message"
		elif isinstance(value, unicode) or isinstance(value, str):
			attributeType = "string"
		elif "enumName" in kwargs:
			attributeType="enum"
		elif value is True or value is False:
			attributeType = "bool"
		elif unicode(value).isnumeric():
			attributeType = "float"

	# we have the info-- create the attribute
	attrData = {"multi":multi}

	if attributeType in ["string", "unicode"]:
		attrData["dt"] = "string"
	else:
		attrData["at"] = attributeType

	attrData.update(kwargs)

	try:
		if attributeType == "enum":
			oldValue = obj.attr(attrName).get(asString=True)
		else:
			oldValue = obj.attr(attrName).get()
	except:
		pass

	safeDeleteAttr(obj, attrName)
	# this could still be a compound attribute which cannot be deleted naturally
	if not obj.hasAttr(attrName):
		obj.addAttr(attrName, **attrData)

	if attributeType == "float3":
		childData = deepcopy(attrData)
		childData.pop("at")
		for axis in "XYZ":
			if not obj.hasAttr(attrName+axis):
				obj.addAttr(attrName+axis, p=attrName, at="float", **childData)

		# have to do a second loop because the attribute isn"t "finished"
		# and available for edit until all three are created
		for axis in "XYZ":
			obj.attr(attrName+axis).set(k=False)
			obj.attr(attrName+axis).set(cb=channelBox)

	pAttr = obj.attr(attrName)

	if preserveValue:
		if oldValue is not None:
			value = oldValue

	# doing the set down here is better because string attrs seem
	# to have trouble with default values. Also, this lets you
	# set the float3"s in one go
	if value is not None:
		if attributeType == "message":
			if multi:
				objects = []
				if append and oldValue is not None:
					objects += oldValue

				if isinstance(value, (list, tuple)):
					for item in value:
						if not item in objects:
							objects.append(item)
						else:
							if not isinstance(value, list):
								objects.append(value)

					incoming = pAttr.inputs(plugs=True)
					for plug in incoming:
						pAttr == plug
						pAttr.disconnect()

					added_items = []
					for index, item in enumerate(objects):
						if isinstance(item, pymel.PyNode):
							if not item in added_items:
								added_items.append(item)
							else:
								continue
						pymel.connectAttr(item+".message", pAttr[index], f=True)

					incoming = pAttr.inputs(plugs=True)
					for plug in incoming:
						print "  Plug: {0}".format(plug)

				elif isinstance(value, pymel.PyNode):
					pymel.connectAttr((value + ".message"), (obj + "." + attrName), f=True)					

		elif attributeType == "string":
			# have to convert to string for non-string values
			# or PyMEL kicks up an error
			if multi:
				for index, v in enumerate(value):
					pAttr[index].set(str(v))
			else:
				pAttr.set(str(value))
		else:
			if multi:
				if not attributeType == "float3":
					for index, v in enumerate(value):
						pAttr[index].set(float(v))
			else:
				try:
					pAttr.set(value)
				except Exception as e:
					log("Unable to set value on parameter %s-- %s" % (obj, e.message))

	if not keyable:
		pAttr.set(k=False)
		pAttr.set(cb=channelBox)
	else:
		pAttr.set(k=keyable)

	if lock:
		pAttr.lock()

	return(pAttr)
def cbsStart(*args, **kwargs):
    base = kwargs.setdefault(
        'base',
        pm.ls(sl=True)[0])  # (string) The base model for the character
    shape = kwargs.setdefault(
        'shape')  # (string) The shape node of the base model
    tweak = kwargs.setdefault(
        'tweak'
    )  # (string) The tweak node of the base model that is being skinned
    skin = kwargs.setdefault(
        'skin')  # (string) The skinCluster node that is driving the base model

    #gather some info
    base, shape, tweak, skin = gatherInfo(base, shape, tweak, skin)
    verts = pm.polyEvaluate(base, v=True)

    #do a quick check to make sure this part hasn't been done before
    if base.hasAttr('baseTransform'):
        pm.error(
            'You have already run the "Start" function on this model, so it is already ready to go.'
            +
            'If corrections have already been made, click "Extract Shape to finish the process"'
        )

    for i in pm.listHistory(base, lv=1):
        if i.type() == 'polySmoothFace':
            pm.error(
                'The selected shape is connected to a smooth modifier. This hinders the ability to track edits. %s must be deleted.'
                % i)

    #turn off a couple things that might mess with things
    pm.symmetricModelling(e=True, symmetry=False)
    pm.softSelect(e=True, softSelectEnabled=False)

    for i in range(verts):

        x = pm.getAttr(('%s.vlist[0].vertex[%i].xVertex' % (tweak, i)))
        y = pm.getAttr(('%s.vlist[0].vertex[%i].yVertex' % (tweak, i)))
        z = pm.getAttr(('%s.vlist[0].vertex[%i].zVertex' % (tweak, i)))

        if not (x + y + z) == 0:
            pm.error(
                'You have used the tweak node. No me gusta. If you really wanna clear it, run clearTweaks and try again. It will save what you have'
            )

    #ok, let's get started, first instance the original mesh
    sculptTrans = pm.instance(base, n=('%s_corrective_sculpt' % base))[0]
    pm.reorderDeformers(skin, tweak, base)
    pm.setAttr('%s.v' % base, False)

    #Here, we'll make a duplicate of the base to look back on later if need be (for instance, using sculpt geometry tends to not register on tweak)
    baseRef = pm.duplicate(base, n='%s_editReference' % base)[0]
    pm.connectAttr(('%s.outMesh' % baseRef.getShapes()[1]),
                   ('%s.inMesh' % baseRef.getShape()))

    #We'll also hook up the original so we can get it later
    pm.addAttr(sculptTrans, ln='baseTransform', at='message')
    pm.addAttr(sculptTrans, ln='baseReference', at='message')
    pm.connectAttr('%s.message' % base, '%s.baseTransform' % sculptTrans)
    pm.connectAttr('%s.message' % baseRef, '%s.baseReference' % sculptTrans)

    #now to keep things from changing between functions, we'll lock the three nodes involved in the
    #other script so our pesky little user won't delete or rename anything
    pm.lockNode(base, l=True)
    pm.lockNode(sculptTrans, l=True)
def cbsTrans(*args, **kwargs):

    sculptTrans = kwargs.setdefault(
        'sculptTrans',
        pm.ls(sl=True)
        [0])  # (string) The mesh to get the tweak edits extracted from
    shape = kwargs.setdefault(
        'shape')  # (string) The shape node of the sculptTrans node
    tweak = kwargs.setdefault(
        'tweak')  # (string) The tweak node that is going to be cleared
    skin = kwargs.setdefault(
        'skin')  # (string) The skinCluster node that drives the base mesh
    base = kwargs.setdefault(
        'base')  # (string) The base mesh for the character

    #get some info
    sculptTrans, shape, tweak, skin = gatherInfo(sculptTrans, shape, tweak,
                                                 skin)
    if not 'baseTransform' in pm.listAttr(sculptTrans, ud=True):
        pm.error(
            'This model has not been prepared for sculpting. If you accidentally started, simply run Clear Tweaks to extract what has been done'
        )
    if not base:
        base = sculptTrans.baseTransform.get()

    baseRef = sculptTrans.baseReference.get()

    #turn off a couple things that might mess with things
    pm.symmetricModelling(e=True, symmetry=False)
    pm.softSelect(e=True, softSelectEnabled=False)

    #first, let's unlock the guys from the old function
    pm.lockNode(base, l=False)
    pm.lockNode(sculptTrans, l=False)
    pm.setAttr('%s.v' % base, True)

    #extract from the sculpted shape
    newShape = clearTweaks(base=base, tweak=tweak)

    pm.delete(sculptTrans)

    newOrig = pm.duplicate(base, n='%s_editReference' % base)[0]
    pm.connectAttr(('%s.outMesh' % newOrig.getShapes()[1]),
                   ('%s.inMesh' % newOrig.getShape()))

    pm.select(cl=True)
    deviation = False
    for v in range(pm.polyEvaluate(base, v=True)):
        refPos = pm.xform('%s.vtx[%i]' % (baseRef, v), q=True, t=True)
        adjPos = pm.xform('%s.vtx[%i]' % (newOrig, v), q=True, t=True)

        if not refPos == adjPos:
            deviation = True
            pm.move('%s.vtx[%i]' % (newShape, v),
                    (refPos[0] - adjPos[0], refPos[1] - adjPos[1],
                     refPos[2] - adjPos[2]),
                    r=True)
            pm.move('%s.vtx[%i]' % (base, v),
                    (refPos[0] - adjPos[0], refPos[1] - adjPos[1],
                     refPos[2] - adjPos[2]),
                    os=True,
                    r=True)
            pm.select('%s.vtx[%i]' % (base, v), add=True)

    if deviation:
        pm.warning(
            'It appears there were issues extracting from the mesh, steps have been taken to try and remedy, but unexpected results may occur'
        )

    #apply a texture to the new shape.
    pm.select(newShape, r=True)
    pm.sets('initialShadingGroup', e=True, forceElement=True)

    pm.delete(newOrig, baseRef)
    return newShape