def getNamespaces(self): namespacesList = [] #Check if current namespace is root else set to scene root if not(pm.namespaceInfo(isRootNamespace = True)): #store current namespace currentNamespace = pm.namespaceInfo(currentNamespace = True) #Set to rootnamespace pm.namespace(setNamespace = ':') #Query namespaceList namespacesList = pm.namespaceInfo(listOnlyNamespaces = True, r = True) #Set back to old namespace pm.namespace(setNamespace = currentNamespace) #If namespace is root namespace else: #Query namespaceList namespacesList = pm.namespaceInfo(listOnlyNamespaces = True, r = False) #Rebuild namespaceList without UI and shared namespacesListTmp = [] for namespaceItem in namespacesList: if not(namespaceItem == 'UI' or namespaceItem == 'shared'): namespacesListTmp.append(namespaceItem) namespacesList = namespacesListTmp return namespacesList
def getNamespaces(self): namespacesList = [] #Check if current namespace is root else set to scene root if not (pm.namespaceInfo(isRootNamespace=True)): #store current namespace currentNamespace = pm.namespaceInfo(currentNamespace=True) #Set to rootnamespace pm.namespace(setNamespace=':') #Query namespaceList namespacesList = pm.namespaceInfo(listOnlyNamespaces=True, r=True) #Set back to old namespace pm.namespace(setNamespace=currentNamespace) #If namespace is root namespace else: #Query namespaceList namespacesList = pm.namespaceInfo(listOnlyNamespaces=True, r=False) #Rebuild namespaceList without UI and shared namespacesListTmp = [] for namespaceItem in namespacesList: if not (namespaceItem == 'UI' or namespaceItem == 'shared'): namespacesListTmp.append(namespaceItem) namespacesList = namespacesListTmp #append root namespacesList.append('root') return namespacesList
def _updateNameSpaceList(self): """update namespace menu item""" # delete all items self._deleteNameSpaceList() # get current namespace current = pmc.namespaceInfo(currentNamespace=True) # get all namespace pmc.namespace(set=':') listNamespace = pmc.namespaceInfo(listOnlyNamespaces=True, recurse=True) pmc.namespace(set=current) if current == ':': current = self.rootNamespace # add root namespace listNamespace.append(self.rootNamespace) # add menuItem i = 1 for nameSpace in listNamespace: if nameSpace in ['UI', 'shared']: continue pmc.menuItem(label=nameSpace, parent=self.uiMain['namespaceOpM']) if nameSpace == current: self.uiMain['namespaceOpM'].setSelect(i) i=i+1
def testSetNamespace(self): self.assertRaises(ValueError, set_namespace_active, '') pmc.namespace(add='before') pmc.namespace(add='after') pmc.namespace(set='before') self.assertEqual('before', pmc.namespaceInfo(cur=True)) with set_namespace_active(':after'): self.assertEqual('after', pmc.namespaceInfo(cur=True)) self.assertEqual('before', pmc.namespaceInfo(cur=True)) with set_namespace_active(':'): self.assertEqual(':', pmc.namespaceInfo(cur=True)) self.assertEqual('before', pmc.namespaceInfo(cur=True))
def removeNamespace(self): #remove namespaces pm.namespace(setNamespace=':') #setting namespace to root namespaces = pm.namespaceInfo(listOnlyNamespaces = True, recurse = True) namespaceLooper = 0 for i in namespaces: #this for loop checks for all the namespaces if i != 'shared' and i != 'UI': namespaceLooper +=1 #this keeps track of the number of namespaces to delete while namespaceLooper >0: #this while loop will keep running for as long as there are namespaces that are not root to delete namespaces = pm.namespaceInfo(listOnlyNamespaces = True) for i in namespaces: if i != 'shared' and i != 'UI': pm.namespace(mergeNamespaceWithRoot = True, removeNamespace = i) namespaceLooper -= 1 #this will decrement the namespace count so the loop will be able to break out
def RefreshAnimationModuleList(self, _index = 1): pm.textScrollList(self.UIElements["animationModule_textScroll"], edit = True, removeAll = True) pm.symbolButton(self.UIElements["deleteModuleButton"], edit = True, enable = False) pm.symbolButton(self.UIElements["duplicateModuleButton"], edit = True, enable = False) selectedBlueprintModule = pm.textScrollList(self.UIElements["blueprintModule_textScroll"], query = True, selectItem = True) self.selectedBlueprintModule = self.blueprintModules[selectedBlueprintModule[0]] self.SetupActiveModuleControls() pm.namespace(setNamespace = self.selectedBlueprintModule) controlModuleNamespaces = pm.namespaceInfo(listOnlyNamespaces = True) pm.namespace(setNamespace = ":") if len(controlModuleNamespaces) != 0: for module in controlModuleNamespaces: moduleName = utils.StripAllNamespaces(module)[1] pm.textScrollList(self.UIElements["animationModule_textScroll"], edit = True, append = moduleName) pm.textScrollList(self.UIElements["animationModule_textScroll"], edit = True, selectIndexedItem = _index) pm.symbolButton(self.UIElements["deleteModuleButton"], edit = True, enable = True) pm.symbolButton(self.UIElements["duplicateModuleButton"], edit = True, enable = True) self.SetupModuleSpecificControls() self.previousBlueprintListEntry = selectedBlueprintModule
def __init__(self): version = "1.0" if pm.window('ms_copyAnimWin', exists=True): pm.deleteUI('ms_copyAnimWin', window=True) self.window = pm.window( 'ms_copyAnimWin', title="Copy Animation v%s" % version, iconName='ms_copyAnimWin') #, widthHeight=(200,100) ) with pm.columnLayout(adj=1): self.mainLO = pm.columnLayout(adjustableColumn=True) removeList = ['shared', 'UI'] self.namespaces = pm.namespaceInfo(lon=1) for each in removeList: self.namespaces.remove(each) with pm.rowLayout(nc=2): self.srcFld = pm.optionMenu(label='Source Namespace') for each in self.namespaces: pm.menuItem(label=each) self.tgtFld = pm.optionMenu(label='Target Namespace') for each in self.namespaces: pm.menuItem(label=each) pm.button(l='Copy animation', c=self.copyAnim) pm.showWindow(self.window)
def get_main_ctrl(): namespaces = pm.namespaceInfo(lon=True) name = '' for ns in namespaces: if len(ns) == 2 and ns != 'UI': name = ns return name + ':Main'
def installModule(self, module, *args): #1. Create Unique Module Name: name = BlueprintModuleName__UserSpecifiedName:objectName basename = "instance_" pm.namespace(setNamespace=":") namespace = pm.namespaceInfo(listOnlyNamespaces=True) #1a. search existing namespaces for all that have __UserSpecifiedName for i in range(len(namespace)): #index of first occurence, find __, if found if namespace[i].find("__") != -1: namespace[i] = namespace[i].partition("__")[2] #1b. create unique UserSpecifiedName (get hightest digit that exists and add 1) newSuffix = utils.findHeighestTrailingNumber(namespace, basename) + 1 userSpecName = basename + str(newSuffix) #import module mod = __import__("Blueprint." + module, {}, {}, [module]) reload(mod) #create class reference from string (without ()) moduleClass = getattr(mod, mod.CLASS_NAME) #with class reference, call constructor and istall method of this module moduleInstance = moduleClass(userSpecName) moduleInstance.install() moduleTransform = mod.CLASS_NAME + "__" + userSpecName + ":module_transform" pm.select(moduleTransform, replace=True) pm.setToolTo("moveSuperContext")
def check(self): """@brief Check if the namespaces are legal. """ illegalNamespaces = list() progStandard = re.compile("^[A-Z]{4}[0-9]{2}_[0-9]{3}$") progShot = re.compile("^SH[0-9]{4}_[0-9]{3}$") for namespaces in pm.namespaceInfo(listOnlyNamespaces=True, internal=False, recurse=True): for namespace in namespaces.split(":"): if not progStandard.match(namespace) and not progShot.match( namespace) not in ["UI", "shared"]: illegalNamespaces.append(namespace) if not illegalNamespaces: self.status = "OK" else: self.status = self.errorMode self.errorNodes = illegalNamespaces for illegalNamespace in illegalNamespaces: self.addError("%s is a illegal namespace" % illegalNamespace) self.errorMessage = "%s illegal namespace" % ( len(illegalNamespaces))
def get_scene_namespaces(self): self.logger.debug('--- get_namespaces()') tmp_namespaces = pm.namespaceInfo(listOnlyNamespaces = 1) self.logger.debug('namespaces: ') self.logger.debug(tmp_namespaces) for obj in tmp_namespaces: chunks = obj.split('_') for chunk in chunks: if chunk == 'ulfbert': self.ns_ulfbert.append(obj + ':') if chunk == 'snorri': self.ns_snorri.append(obj + ':') if chunk == 'helga': self.ns_helga.append(obj + ':') self.logger.debug(self.ns_ulfbert) self.logger.debug(self.ns_snorri) self.logger.debug(self.ns_helga)
def findAttr(attr, lNS): attr, envelop = deenvelop(attr) found = False curr = pym.namespaceInfo(cur=True) if curr == ":": curr = "" if attrExists(attr) and (curr in attr): found = True foundattr = attr else: for ns in lNS: attrLastHierachy = attr.split("|")[-1] attrStripNamespace = attrLastHierachy.split(":")[-1] searchWildCard = ns + "::" + attrStripNamespace lAttr = pym.ls(searchWildCard) if len(lAttr) == 1: found = True if type(lAttr[0]) == pym.Attribute: foundattr = lAttr[0].name(fullDagPath=True, fullAttrPath=True) elif type(lAttr[0]) == pym.general.Pivot: foundattr = lAttr[0].name() else: foundattr = lAttr[0].name(long=True) break if found: oAttr = pym.PyNode(foundattr) if any(envelop): attr = reenvelop(foundattr, envelop) return oAttr, foundattr else: return None, None
def preserve_namespace(on_enter_namespace=None): current_namespace = pm.namespaceInfo(currentNamespace=True) if on_enter_namespace: set_namespace(on_enter_namespace) try: yield finally: set_namespace(current_namespace)
def test_searches_all_namespaces_if_ns_not_in_current(self): pm.namespace(set=':') ns = self.create_namespace(':foo') ns2 = self.create_namespace(':bar') pm.namespace(set=ns2) namespaceutils.set_namespace('foo') current_ns = pm.namespaceInfo(currentNamespace=True) self.assertEqual(ns, current_ns)
def bdImportController(self, n): con = self.conList[n] animConName = self.bdGetConName() overrideColor = self.conColors[str(self.inputConSide.currentText())] conSize = self.inputConSize.text() selection = pm.ls(sl=True) selPos = [0, 0, 0] selRot = [0, 0, 0] if selection: selPos = selection[0].getTranslation(space='world') selRot = selection[0].getRotation(space='world') if not conSize: conSize = 1 if animConName != '': scriptPath = os.path.dirname(__file__) conFile = scriptPath + '/controllers/' + con + '.ma' conTransform = \ [f for f in pm.importFile(conFile, returnNewNodes=True, namespace='temp') if f.type() == 'transform'][0] # conTransform = pm.importFile( conFile,returnNewNodes=True,namespace='temp') sceneNS = pm.namespaceInfo(lon=True, r=True) importNS = [] for ns in sceneNS: if 'temp' in ns: importNS.append(ns) importNS.reverse() for ns in importNS: pm.namespace(rm=ns, mergeNamespaceWithRoot=True) print conTransform conTransform.rename(animConName) conTransformChidlren = conTransform.getChildren(ad=True, type='transform') for child in conTransformChidlren: child.rename( str(self.inputConSide.currentText()) + child.name()) scaleVector = om.MVector(1, 1, 1) * float(conSize) conTransform.setScale( [scaleVector.x, scaleVector.y, scaleVector.z]) pm.makeIdentity(conTransform, apply=True, t=0, r=0, s=1) for shape in conTransform.getChildren(): shape.overrideEnabled.set(1) shape.overrideColor.set(overrideColor) conTransformGrp = pm.group(conTransform, name=conTransform.name() + '_GRP') conTransformGrp.setPivots([0, 0, 0]) conTransformGrp.setTranslation(selPos, space='world') conTransformGrp.setRotation(selRot, space='world')
def duplicate_skeleton(root_joint, dup_parent=None, dup_namespace=None): dup_namespace = dup_namespace or pm.namespaceInfo(currentNamespace=True) dup_root = nsutils.duplicate_to_namespace([root_joint], dup_namespace=dup_namespace, dup_parent=dup_parent)[0] dup_hierarchy = get_hierarchy_from_root(dup_root) to_delete = get_extra_nodes_in_skeleton(dup_hierarchy) pm.delete(to_delete) return dup_root
def listAllNamespaces(self): """ List all namespaces except the UI and shared """ pc.namespace(set=":") nss = pc.namespaceInfo(listOnlyNamespaces=True) nss.remove('UI') nss.remove('shared') return(nss)
def duplicate_triangulate_mesh(skinned_mesh, dup_namespace=None, dup_parent=None): dup_namespace = dup_namespace or pm.namespaceInfo(currentNamespace=True) with nsutils.preserve_namespace(dup_namespace): dup_skinned_mesh_tri = nsutils.duplicate_to_namespace( skinned_mesh, dup_namespace=dup_namespace, dup_parent=dup_parent)[0] pm.polyTriangulate(dup_skinned_mesh_tri, ch=True) pm.delete(dup_skinned_mesh_tri, constructionHistory=True) dup_skin_cluster = bind_mesh_like_mesh(skinned_mesh, dup_skinned_mesh_tri) copy_weights(skinned_mesh, dup_skinned_mesh_tri) return dup_skinned_mesh_tri, dup_skin_cluster
def scene_namespaces(self): nm = pmc.namespaceInfo(lon=True, r=True) namespaces = [] exclude = ['UI', 'shared'] for i in nm: if i not in exclude: namespaces.append(i) return namespaces
def test_start_at_root_true(self): pm.namespace(set=':') ns_foo = self.create_namespace(':foo') ns_bar = self.create_namespace(':bar') ns_bar_foo = self.create_namespace(':bar:foo') ns_bar_foo_spam_foo = self.create_namespace(':bar:foo:spam:foo') pm.namespace(set=ns_bar) namespaceutils.set_namespace('foo', start_at_root=True) current_ns = pm.namespaceInfo(currentNamespace=True) self.assertEqual(ns_foo, current_ns)
def test_if_multiple_matching_ns_take_first_nested_first(self): pm.namespace(set=':') ns_foo = self.create_namespace(':foo') ns_bar = self.create_namespace(':bar') ns_bar_foo = self.create_namespace(':bar:foo') ns_bar_foo_spam_foo = self.create_namespace(':bar:foo:spam:foo') pm.namespace(set=ns_bar) namespaceutils.set_namespace('foo') current_ns = pm.namespaceInfo(currentNamespace=True) self.assertEqual(ns_bar_foo, current_ns)
def bdImportController(self,n): con = self.conList[n] animConName = self.bdGetConName() overrideColor = self.conColors[str(self.inputConSide.currentText())] conSize = self.inputConSize.text() selection = pm.ls(sl = True) selPos = [0,0,0] selRot = [0,0,0] if selection: selPos = selection[0].getTranslation(space='world') selRot = selection[0].getRotation(space='world') if not conSize: conSize=1 if animConName != '': scriptPath = os.path.dirname(__file__) conFile = scriptPath + '/controllers/' + con + '.ma' conTransform = [f for f in pm.importFile(conFile,returnNewNodes=True,namespace='temp') if f.type()=='transform'][0] #conTransform = pm.importFile( conFile,returnNewNodes=True,namespace='temp') sceneNS = pm.namespaceInfo(lon=True,r=True) importNS = [] for ns in sceneNS: if 'temp' in ns: importNS.append(ns) importNS.reverse() for ns in importNS: pm.namespace( rm = ns,mergeNamespaceWithRoot=True) print conTransform conTransform.rename(animConName) conTransformChidlren = conTransform.getChildren(ad=True,type='transform') for child in conTransformChidlren : child.rename(str(self.inputConSide.currentText()) + child.name()) scaleVector = om.MVector(1,1,1) * float(conSize) conTransform.setScale([scaleVector.x,scaleVector.y,scaleVector.z]) pm.makeIdentity(conTransform,apply=True,t=0,r=0,s=1) for shape in conTransform.getChildren(): shape.overrideEnabled.set(1) shape.overrideColor.set(overrideColor) conTransformGrp = pm.group(conTransform,name=conTransform.name() + '_GRP') conTransformGrp.setPivots([0,0,0]) conTransformGrp.setTranslation(selPos,space='world') conTransformGrp.setRotation(selRot,space='world')
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 duplicate_skinned_mesh_to_influences(skinned_mesh, influences, copy_skinning=True, bind_method=bind_mesh_to_joints, dup_namespace=None, dup_parent=None): dup_namespace = dup_namespace or pm.namespaceInfo(currentNamespace=True) with nsutils.preserve_namespace(dup_namespace): skinned_mesh_duplicate = nsutils.duplicate_to_namespace( skinned_mesh, dup_namespace=dup_namespace, dup_parent=dup_parent)[0] skincluster_duplicate = bind_method(skinned_mesh_duplicate, influences) if copy_skinning: copy_weights(skinned_mesh, skinned_mesh_duplicate) # copy_weights_vert_order(skinned_mesh, skinned_mesh_duplicate) return skinned_mesh_duplicate, skincluster_duplicate
def FindInstalledCharacters(): pm.namespace(setNamespace = ":") namespaces = pm.namespaceInfo(listOnlyNamespaces = True) characterNamespaces = [] for n in namespaces: if n.find("Character__") == 0: characterNamespaces.append(n) return characterNamespaces
def DoesBlueprintUserSpecifiedNameExist(_name): pm.namespace(setNamespace = ':') namespaces = pm.namespaceInfo(listOnlyNamespaces = True) names = [] for namespace in namespaces: if namespace.find('__') != -1: names.append(namespace.partition('__')[2]) return _name in names
def lock(self, *args): result = pm.confirmDialog( messageAlign='center', title='Lock Blueprints', message= 'Locking will convert modules to joints. This action can not bet undone. \n Modification to blueprint system can not be done after this.', button=['Accept', 'Cancel'], defaultButton='Accept', cancelButton='Cancel') if result != 'Accept': return moduleInfo = [] #store (module, userSpecifiedName) pairs #find all modules in scene and store them in moduleInfo list [moduleName, userSpecifiedName] pm.namespace(setNamespace=":") namespace = pm.namespaceInfo(listOnlyNamespaces=True) moduleNameInfo = utils.findAllModuleNames("/Modules/Blueprint") validModules = moduleNameInfo[0] validModuleNames = moduleNameInfo[1] for n in namespace: splitString = n.partition("__") if splitString[1] != "": module = splitString[0] userSpecifiedName = splitString[2] if module in validModuleNames: index = validModuleNames.index(module) moduleInfo.append([validModules[index], userSpecifiedName]) if len(moduleInfo) == 0: pm.confirmDialog(messageAlign='center', title='Lock Blueprints', message='No Blueprint Modules in scene', button=['Accept'], defaultButton='Accept') return print moduleInfo moduleInstances = [] #lock phase 1 - gather tranform/rotation info of joints for module in moduleInfo: mod = __import__('Blueprint.' + module[0], {}, {}, [module[0]]) reload(mod) moduleClass = getattr(mod, mod.CLASS_NAME) moduleInst = moduleClass(userSpecifiedName=module[1]) moduleInfo = moduleInst.lock_phase1() moduleInstances.append((moduleInst, moduleInfo)) print moduleInfo #lock phase 2 for module in moduleInstances: module[0].lock_phase2(module[1])
def removeNamespace(self, namespace, force=False): ''' Removes namespace with all its content. ''' if namespace in self.listAllNamespaces(): pc.namespace(set=':'+namespace) pc.delete(pc.namespaceInfo(listNamespace=True)) pc.namespace(removeNamespace=':'+namespace, force=force) pc.namespace(set=":") else: print('Warning namespace %s could not be found.'%namespace)
def removeNamespace(): sceneNS = pm.namespaceInfo(lon=True, r=True) importNS = [] mayaNS = set([u'UI', u'shared']) for ns in sceneNS: if ns not in mayaNS: importNS.append(ns) importNS.reverse() for ns in importNS: pm.namespace(rm=ns, mergeNamespaceWithRoot=True)
def namespace_deleter(cls): """the legendary namespace deleter from Mehmet Erer finds and deletes unused namespaces """ all_namespaces = pm.listNamespaces() ref_namespaces = [ref.namespace for ref in pm.listReferences()] missing_namespaces = [] from anima.ui.progress_dialog import ProgressDialogManager if len(all_namespaces) > 0: pdm = ProgressDialogManager() pdm.close() caller = pdm.register(len(all_namespaces), 'Locating Unused Namespaces...') for nsa in all_namespaces: i = 0 for nsr in ref_namespaces: i += 1 if nsr == nsa: break if i == len(ref_namespaces): missing_namespaces.append(nsa) caller.step() if len(missing_namespaces) > 0: caller = pdm.register(len(missing_namespaces), 'Deleting Unused Namespaces...') for ns in missing_namespaces: ns_info = pm.namespaceInfo(ns, lon=1, fn=1, r=1) if len(ns_info) > 0: nsc = ns_info[len(ns_info) - 1] nsc_array = nsc.split(':') if len(nsc_array) > 0: for del_nsc in nsc_array: pm.namespace(rm=del_nsc, mnr=1) else: pm.namespace(rm=ns, mnr=1) print('Deleted -> :' + ns) caller.step() else: pm.warning( 'There are no first-level unused namespaces in this scene.' ) if len(ref_namespaces) == 0 and len(all_namespaces) > 0: for ns in all_namespaces: pm.namespace(rm=ns, mnr=1) print('Deleted -> : %s' % ns) pm.warning( 'There are no references in this scene. All empty namespaces ' 'are deleted.' )
def get_namespaces(): # gets the namespaces from the scene # returns list of strings names = ['None'] for name in pm.namespaceInfo(listOnlyNamespaces=True, recurse=True): if name not in ['UI', 'shared']: names.append(name) return names
def getAnimatedTextures(conf): """ read conf to get candidate textures from the scene """ texture_attrs = [] for key, attrs in conf.get('texture_export_data', []): for namespace in pc.namespaceInfo(lon=True): if re.match(key, namespace): for attr in attrs: attr = pc.Attribute(namespace + ':' + attr) texture_attrs.append(attr) return texture_attrs
def removeNamespace(): sceneNS = pm.namespaceInfo(lon=True,r=True) importNS = [] mayaNS = set([u'UI', u'shared']) for ns in sceneNS: if ns not in mayaNS: importNS.append(ns) importNS.reverse() for ns in importNS: pm.namespace( rm = ns,mergeNamespaceWithRoot=True)
def noNameSpaces(): pm.namespace(set=':') nameSpacesInScene = pm.namespaceInfo(listOnlyNamespaces=True, recurse=True, absoluteName=True) nameSpacesInScene.remove(':UI') nameSpacesInScene.remove(':shared') if nameSpacesInScene: return True return False
def remove_all_namespaces(): allNameSpace = cmds.namespaceInfo(":", recurse = True, listOnlyNamespaces = True, absoluteName = True) for whole_ns in allNameSpace : if whole_ns != ":UI" and whole_ns != ":shared": ns = whole_ns.split(':')[-1] try : pm.namespace(mv=[ns,':'],f=1) if ns in pm.namespaceInfo(lon=1): pm.namespace(rm=ns) logger.info('namespace "{}" removed succeed'.format(ns)) except Exception as e: logger.warning('namespace "{}" removed error'.format(ns))
def delete_empty_namespaces(): ''' Remove all empty namespaces from bottom up to remove children namespaces first ''' namespace_list = [] for ns in pm.listNamespaces( recursive =True, internal =False): namespace_list.append(ns) # Reverse Iterate through the contents of the list to remove the deepest layers first for ns in reversed(namespace_list): if not pm.namespaceInfo(ns, ls=True): pm.namespace(removeNamespace = ns, mergeNamespaceWithRoot = True)
def FindInstalledBlueprintInstances(_characterNamespace): pm.namespace(setNamespace = _characterNamespace) moduleInstances = pm.namespaceInfo(listOnlyNamespaces = True) returnModuleInstances = [] for module in moduleInstances: returnModuleInstances.append(StripLeadingNamespace(module)[1]) pm.namespace(setNamespace = ":") return returnModuleInstances
def superRename( object, newName, force=False ): print 'object:', object result = pm.rename( object, newName ) result = str( result ) if result == newName: print '// Result:', result else: nsList = pm.namespaceInfo( listOnlyNamespaces=True ) nodeList = pm.ls( '*' + newName ) if force: if newName in nsList: nsName = newName + 'NS' try: pm.namespace( add=nsName ) except RuntimeError: pass pm.namespace( force=True, moveNamespace=( newName, nsName ) ) pm.namespace( removeNamespace=newName ) mel.warning( 'Renamed namespace "%s" to "%s".' % ( newName, nsName ) ) if newName in nodeList: for n in nodeList: if n.type() == 'displayLayer': pm.rename( n, n + 'L' ) mel.warning( 'SuperRename: Forced DisplayLayer "%s" to "%s".' % ( newName, n + 'L' ) ) else: try: print n.nextName().split( '|' )[-1] r = pm.rename( n, n.nextName().split( '|' )[-1] ) except RuntimeError: # pass r = pm.rename( n, n + '100' ) except: pass mel.warning( 'SuperRename: Forced renamed "%s" to "%s".' % ( newName, r ) ) # renamed conflicting nodes, try again superRename( result, newName, force=False ) else: print '// Conflicts:' if newName in nsList: print '// (namespace)'.ljust( 10 ), newName if nodeList: for n in nodeList: print '// (%s)'.ljust( 10 ) % n.type(), n
def _iter_namespace( ns_list, level=0 ): count = 0 for ns in ns_list: count += 1 pm.namespace( set=':' ) pm.namespace( set=ns ) print '// ' + ' ' * level + '- ' + ns if pm.namespaceInfo( lon=1 ): count += _iter_namespace( pm.namespaceInfo( lon=1 ), ( level + 1 ) ) pm.namespace( set=':' ) for obj in pm.ls( ns + ':*' ): obj.rename( obj.replace( ns + ':', '' ) ) pm.namespace( rm=ns ) return count
def cleanNamespaces(): sceneNS = pm.namespaceInfo(lon=True, r=True) print sceneNS importNS = [] for ns in sceneNS: importNS.append(ns) importNS.reverse() for ns in importNS: try: pm.namespace(rm=ns) except: pm.namespace(moveNamespace=[ns, ':'], force=1)
def rig(self, component_node, control, bake_controls=False, default_space=None, use_global_queue=False, **kwargs): # Create the dynamic pendulum to be used as the Aim space for the overdriver self.network = self.create_meta_network(component_node) #self.zero_character(self.network['character'], use_global_queue) aim_up_group_name = "{0}pre_dynamics_{1}_grp".format(self.namespace, self.prefix) pre_dynamic_group = pm.group(empty=True, name=aim_up_group_name) pre_dynamic_group.setParent(self.network['addon'].group) pm.parentConstraint(self.character_world, pre_dynamic_group, mo=False) cur_namespace = pm.namespaceInfo(cur=True) pm.namespace(set=":") time_range = (pm.playbackOptions(q=True, min=True), pm.playbackOptions(q=True, max=True)) object_space = pm.polySphere(r=8, sx=20, sy=20, ax=[0,1,0], cuv=2, ch=1, n="pendulum")[0] object_space.setParent(pre_dynamic_group) ws_pos = pm.xform(control, q=True, ws=True, t=True) pm.xform(object_space, ws=True, t=ws_pos) rigid_body = pm.rigidBody(object_space, b=0, dp=5) rigid_body_nail = pm.PyNode(pm.constrain(rigid_body, nail=True)) rigid_body_nail.setParent(pre_dynamic_group) rigid_point_constraint = pm.pointConstraint(control, rigid_body_nail, mo=False) pm.select(None) gravity_field = pm.gravity(m=980) gravity_field.setParent(pre_dynamic_group) pm.connectDynamic(object_space, f=gravity_field) self.reset_pendulum(object_space) if not super(Pendulum, self).rig(component_node, control, [object_space], bake_controls=bake_controls, default_space=default_space, use_global_queue=use_global_queue, **kwargs): return False driver_control = self.network['controls'].get_first_connection() driver_control.addAttr("damping", type='double', hidden=False, keyable=True) driver_control.damping.set(rigid_body.damping.get()) driver_control.damping >> rigid_body.damping driver_control.addAttr("bounciness", type='double', hidden=False, keyable=True) driver_control.bounciness.set(rigid_body.bounciness.get()) driver_control.bounciness >> rigid_body.bounciness driver_control.addAttr("gravity", type='double', hidden=False, keyable=True) driver_control.gravity.set(gravity_field.magnitude.get()) driver_control.gravity >> gravity_field.magnitude self.reset_pendulum(object_space)
def IsModuleInstalled(self, _moduleName): pm.namespace(setNamespace = self.currentBlueprintModule) installedModules = pm.namespaceInfo(listOnlyNamespaces = True) pm.namespace(setNamespace = ":") if installedModules != None: for module in installedModules: installedModuleNameWithoutSuffix = utils.StripAllNamespaces(module)[1] installedModuleName = installedModuleNameWithoutSuffix.rpartition("_")[0] if installedModuleName == _moduleName: return True return False
def removeNamespaces(): """ Strips and removes all possible namespaces from scene. """ core_ns = sets.Set( ['UI', 'shared'] ) pm.namespace( set=':' ) root_ns = sets.Set( pm.namespaceInfo( lon=1 ) ) ns_list = list( root_ns.difference( core_ns ) ) print '// Clearning Namespaces:' count = _iter_namespace( ns_list ) print '//', count, 'namespaces removed.'
def fixEditsNS(rn, bad, new): bad_neds = [] curr = pym.namespaceInfo(cur=True) if curr == ":": curr = "" else: curr = curr + ":" for es in pym.system.referenceQuery(rn, es=True): ns = es.replace(bad + ":", curr + new + ":") try: pym.mel.eval(ns) except Exception as e: print e bad_neds.append([ns, e]) return bad_neds
def get_nodes_with_namespace_and_attr(self, pynode_list, attr_name): """ Select nodes with a certain namespace that have given attribute. A namespace is mandatory. Operation will fail if namespace of node in pynode_list is empty. """ #convert to list if not if not (type(pynode_list) is list): pynode_list = [pynode_list] #node_selection_list node_selection_list = [] #iterate for pynode in pynode_list: #namespace namespace = pynode.namespace() #check if not (namespace): #log self.logger.debug( 'Node {0} does not have a namespace. Continuing'.format( pynode.name())) continue #namespace_node_list namespace_node_list = pm.namespaceInfo(namespace, lod=True, recurse=True) #check if not (namespace_node_list): #log self.logger.debug( 'Namespace node list for namespace: {0} and node {1} empty. Continuing' .format(namespace, pynode.name())) continue #append to node_selection_list node_selection_list += [ namespace_node for namespace_node in namespace_node_list if namespace_node.hasAttr(attr_name) ] #return return node_selection_list
def moduleNamespace(module_name): """ Checks to see if module namespace exists. If it does add a number to the end """ pm.namespace(setNamespace = ":") all_names = pm.namespaceInfo(listOnlyNamespaces = True) module_name = module_name # check to see if module namespace is in all namespaces if module_name in all_names: module_basename, module_number = stripTrailingNumber(module_name) highest_number = findHighestTrailingNumber(module_name, all_names) module_name = module_basename + str(highest_number) return module_name
def importFiles(self, i=-1): """Proceed the importation""" # check if user choose a group if self._grp: if pmc.objExists(self._grp.name()): hasGrp = True else: hasGrp = False # set namespace if need currentNamespace = pmc.namespaceInfo(currentNamespace=True) if self._nameSpace: pmc.namespace(set=self._nameSpace) # import each file if i>-1: fil = [self._files[i]] else: fil = self._files for f in fil: objs = pmc.importFile(f, groupReference=hasGrp, returnNewNodes=True) if objs: if self.verbose: print '\tINFO: Import file %s Done' % f else: if self.verbose: print '\tERROR: Could not import file %s' % f continue if not self._grp: continue # parenting for child in objs[0].getChildren(): child.setParent(self._grp) # delete main group pmc.delete(objs[0]) # reset to previous namespace pmc.namespace(set=currentNamespace)
def get_nodes_with_namespace_and_attr(self, pynode_list, attr_name): """ Select nodes with a certain namespace that have given attribute. A namespace is mandatory. Operation will fail if namespace of node in pynode_list is empty. """ #convert to list if not if not (type(pynode_list) is list): pynode_list = [pynode_list] #node_selection_list node_selection_list = [] #iterate for pynode in pynode_list: #namespace namespace = pynode.namespace() #check if not (namespace): #log self.logger.debug('Node {0} does not have a namespace. Continuing'.format(pynode.name())) continue #namespace_node_list namespace_node_list = pm.namespaceInfo(namespace, lod = True, recurse = True) #check if not (namespace_node_list): #log self.logger.debug('Namespace node list for namespace: {0} and node {1} empty. Continuing'.format(namespace, pynode.name())) continue #append to node_selection_list node_selection_list += [namespace_node for namespace_node in namespace_node_list if namespace_node.hasAttr(attr_name)] #return return node_selection_list
def InitializeBlueprintModuleList(self): pm.namespace(setNamespace = self.selectedCharacter) blueprintNamespaces = pm.namespaceInfo(listOnlyNamespaces = True) pm.namespace(setNamespace = ":") self.blueprintModules = {} if len(blueprintNamespaces) > 0: for namespace in blueprintNamespaces: blueprintModule = utils.StripLeadingNamespace(namespace)[1] userSpecifiedName = blueprintModule.partition("__")[2] pm.textScrollList(self.UIElements["blueprintModule_textScroll"], edit = True, append = userSpecifiedName) self.blueprintModules[userSpecifiedName] = namespace pm.textScrollList(self.UIElements["blueprintModule_textScroll"], edit = True, selectIndexedItem = 1) selectedBlueprintModule = pm.textScrollList(self.UIElements["blueprintModule_textScroll"], query = True, selectItem = True) self.selectedBlueprintModule = self.blueprintModules[selectedBlueprintModule[0]]
def __init__(self): version = "1.0" if pm.window('ms_copyAnimWin',exists=True): pm.deleteUI('ms_copyAnimWin' ,window=True) self.window = pm.window( 'ms_copyAnimWin' , title="Copy Animation v%s" % version, iconName='ms_copyAnimWin' ) #, widthHeight=(200,100) ) with pm.columnLayout(adj=1): self.mainLO = pm.columnLayout( adjustableColumn=True ) removeList = ['shared', 'UI'] self.namespaces = pm.namespaceInfo(lon=1) for each in removeList: self.namespaces.remove(each) with pm.rowLayout(nc=2): self.srcFld = pm.optionMenu( label='Source Namespace' ) for each in self.namespaces: pm.menuItem( label=each ) self.tgtFld = pm.optionMenu( label='Target Namespace' ) for each in self.namespaces: pm.menuItem( label=each ) pm.button(l='Copy animation', c=self.copyAnim) pm.showWindow( self.window )
def create(self): """ Create the render layer. This will generate the colors for each namespace, create flat shaders for each of these colors per namespace. A namespace render layer is also generated in maya. """ # Query for the shading group set assigned = pm.sets("initialShadingGroup", query=True) if assigned: # Create new lambert shader default_lambert = pm.shadingNode("lambert", asShader=True) attrs = default_lambert.listAttr(scalar=True, read=True, settable=True, keyable=True) for attr in attrs: num_child_attrs = pm.attributeQuery( attr.name(includeNode=False), node="lambert1", numberOfChildren=True ) plug = attr.listConnections(plugs=True, destination=False, source=True) if plug: attr.connectAttr(plug[0]) elif num_child_attrs: attr_val = pm.getAttr('lambert1.{0}'.format(attr)) default_lambert.setAttr(attr_val) # Add parent attribute if there are any parent_attr = pm.attributeQuery(attr, lp=True, n="lambert1") if parent_attr and parent_attr[0] not in attrs: attrs.append(parent_attr[0]) shading_group = pm.sets(renderable=True, noSurfaceShader=True) default_lambert.connectAttr( 'outColor', '{0}.surfaceShader'.format(shading_group.name()), f=True ) for item in assigned: is_object = pm.ls(item, o=True) if is_object: try: shade_remove = pm.sets(item.name(), rm='initialShadingGroup', e=True) pm.sets(item, e=True, fe=shading_group) except RuntimeError: shade_remove = None print "Problem removing " + str(item) + " from the initialShadingGroup" # Get namespaces and generate colors based on those namespaces self.get_namespaces() self.get_namespace_colors() # Must replace with internal object function # _getNamespaceInfoFromStructureFile(self.struc, self.namespaces, # [], [], [], [], []) # _getColors(self.namespaces, self.colors) old_namespace = pm.namespaceInfo(currentNamespace=True) old_render_layer = pm.editRenderLayerGlobals(q=True, currentRenderLayer=True) layer = "" for i, cur_namespace in enumerate(self.namespaces): # Will probably need to remove if cur_namespace == 'stereoCam': continue if layer == '': layer = pm.createRenderLayer(makeCurrent=True, name="namespaceLayer") if not pm.namespace(set=(":" + str(cur_namespace))): continue (red, green, blue) = self.colors[i] dag_namespace = pm.namespaceInfo(dp=1, lod=True) pm.select(dag_namespace, replace=True) geom = pm.ls(visible=True, type=['mesh', 'nurbsSurface'], dag=True, ni=True, selection=True) gpu_mesh = [] if pm.objectType(tagFromType="rfxAlembicMeshGpuCache"): gpu_mesh = pm.ls(selection=True, visible=True, dag=True, noIntermediate=True, type="rfxAlembicMeshGpuCache", long=True) pm.select(clear=True) if len(geom)>0: material=str(shadingNode('surfaceShader', asShader=True)) setAttr((material + ".outColor"), red,green,blue, type='double3') shader=str(cmds.sets(renderable=True, noSurfaceShader=True, empty=True)) connectAttr((material + ".outColor"),(shader + ".surfaceShader"), f=True) for j in range(0,len(geom)): existingShaders=listConnections(geom[j], source=False, plugs=False, destination=True, type="shadingEngine") if len(existingShaders)>0: editRenderLayerMembers(layer,geom[j]) retry=0 # first try to set the shader in object mode retry=1 # Use shading group hijack method for everything... #if (catch(`sets -noWarnings -forceElement $shader $geom[$j]`)) { # $retry = 1; #} if retry == 1: # Couldn't assign shader. Various alternative approaches to assigning the shader have not worked 100% of the time. # So add a couple of extra attributes to the shadingGroup - defaultShader and namespaceShader, and connect the respective # shaders to these. During pushRenderLayer (PlayblastTool), check for the existence of the namespaceShader, and if present, # find it's connection and plug it into the surfaceShader attribute, thus "hijacking" the shading group. During popRenderLayer, # connect the attribute plugged into defaultShader and plug this back into the surfaceShader attribute. This is messy, but it # sidesteps material assignment alltogether. for k in range(0,len(existingShaders)): if not objExists(existingShaders[k] + ".defaultShader"): addAttr(existingShaders[k], ln="defaultShader",at="message") defaultMat=listConnections((existingShaders[k] + ".surfaceShader"), s=1,d=0) if len(defaultMat): connectAttr((defaultMat[0] + ".message"),(existingShaders[k] + ".defaultShader")) addAttr(existingShaders[k], ln="namespaceShader",at="message") connectAttr((material + ".message"),(existingShaders[k] + ".namespaceShader")) retry=0 # temp until we feel confident retiring the next section of code if retry == 1: print "Using alternate shader assignment strategy on " + geom[j] + "\n" # couldn't assign shader. Emergency fall-back: Switch back to defaultRenderLayer, unassign and re-assign the existing shaders, then # switch back to namespace layer and try again. existingShaders = self.stringArrayReverse(existingShaders) """ To-do: Add an explanation about why reversing the shaders array is necessary once we've confirmed that we are good. -HM """ # store the existing material assignments comps=[] indices=[] for k in range(1,len(existingShaders)): indices[k - 1]=len(comps) assigned=cmds.sets(existingShaders[k], q=1) for m in range(0,len(assigned)): obj=ls(o=assigned[m]) if obj[0] == geom[j]: comps.append(assigned[m]) # unassign the existing materials for k in range(0,len(existingShaders)): cmds.sets(geom[j], rm=existingShaders[k],e=1) if catch( lambda: cmds.sets(geom[j], noWarnings=1,forceElement=shader) ): mel.warning("Couldn't " "assign namespace shader to " + geom[j]) continue else: print ("DeepPlayblastUtilities: Alternate " "shader assignment worked for " + geom[j] + ".\n") editRenderLayerGlobals(currentRenderLayer="defaultRenderLayer") # switch back to defaultRenderLayer # and re-assign (assign first shader to whole # object, then component assign subsequent shaders) cmds.sets(geom[j], e=1,fe=existingShaders[0]) for k in range(0,len(indices)): end = (int((k<len(indices) - 1) and indices[k + 1] or (len(comps)))) for m in range(indices[k],end): cmds.sets(comps[m], e=1,fe=existingShaders[k + 1]) # switch to namespace layer editRenderLayerGlobals(currentRenderLayer=layer) if len(gpu_mesh)>0: # end if size($existingShaders) for j in range(0,len(gpu_mesh)): pm.editRenderLayerMembers(layer,gpu_mesh[j]) pm.setAttr((gpu_mesh[j] + ".defaultColor"), red,green,blue, type='double3') pm.setAttr((gpu_mesh[j] + ".colorsMode"), 0) self.gpu_meshes.append(gpu_mesh[j]) if layer != "": pm.namespace(set=old_namespace) pm.editRenderLayerGlobals(currentRenderLayer=old_render_layer) self.layer = layer self.gpu_meshes = list(set(self.gpu_meshes))
def __enter__(self): self.oldns = pmc.namespaceInfo(currentNamespace=True) pmc.namespace(setNamespace=self.ns)