def getAllNS(): #set the current naemspace to world curNS = mc.namespaceInfo(cur=True) mc.namespace(set=":") #because maya can only list the child namespaces of the current set namespace, we have to recursively go through setting #and checking child namespaces #start by getting the worlds children namespaces = [] childspaces = mc.namespaceInfo(lon=True) while childspaces: #move the current add spaces into the namespaces list (what we will return) namespaces.extend(childspaces) #create a list from the childspaces so that we can check for their children checkspaces = childspaces #empty the childspaces so all new children can be added to it for the next round childspaces = [] #cycle through the current checkspaces and get their child namespaces for check in checkspaces: mc.namespace(set=(":" + check)) grandchildspaces = mc.namespaceInfo(lon=True) if grandchildspaces: childspaces.extend(grandchildspaces) #remove default namespaces if namespaces.count('UI'): namespaces.remove('UI') if namespaces.count('shared'): namespaces.remove('shared') mc.namespace(set=(":" + curNS)) namespaces.sort() return namespaces
def __init__(self): character = self.findSelectedCharacter() if character == None: return niceName = character.partition('__')[2] result = cmds.confirmDialog(title='Delete Character',message='Are you sure you want to delete the character \'' + niceName + '\'?\nCharacter deletion cannot be undone.',button=['Yes','Cancel'],defaultButton='Yes',cancelButton='Cancel',dismissString='Cancel') if result == 'Cancel': return characterContainer = character + ':character_container' cmds.lockNode(characterContainer, lock=False, lockUnpublished=False) cmds.delete(characterContainer) cmds.namespace(setNamespace=character) blueprintNamespaces = cmds.namespaceInfo(listOnlyNamespaces=True) for blueprintNamespace in blueprintNamespaces: cmds.namespace(setNamespace=':') cmds.namespace(setNamespace=blueprintNamespace) moduleNamespaces = cmds.namespaceInfo(listOnlyNamespaces=True) cmds.namespace(setNamespace=':') if moduleNamespaces != None: for moduleNamespace in moduleNamespaces: cmds.namespace(removeNamespace=moduleNamespace) cmds.namespace(removeNamespace=blueprintNamespace) cmds.namespace(removeNamespace=character)
def bdImportGeneric(args): basicFilter = "Maya Files (*.ma *.mb);;Maya ASCII (*.ma);;Maya Binary (*.mb)" genericFile = cmds.fileDialog2(fileFilter=basicFilter, dialogStyle=0,cap='Import Generic',fm=1) if genericFile: print genericFile #cmds.file( genericFile[0], namespace="generic", import = True) cmds.file( genericFile[0], i=True,namespace = 'genericchar' ) #remove namespaces sceneNS = cmds.namespaceInfo(lon=True,r=True) importNS = [] for ns in sceneNS: if 'genericchar' in ns: importNS.append(ns) importNS.reverse() for ns in importNS: cmds.namespace(setNamespace=ns) parentNS = cmds.namespaceInfo( parent = True) nemName = ":" + ns cmds.namespace( force = True, moveNamespace = [ nemName, ':' ] ) cmds.namespace( rm = nemName) else: print 'No file was selected' bipsInScene = cmds.ls('Bip??') if len(bipsInScene) == 1: target = bipsInScene[0] dest = 'Generic|Controllers|World_Anim_grp|Global_Scale_Anim' const = cmds.parentConstraint(target,dest) cmds.delete(const) cmds.setAttr(dest + ".translateZ", 0) cmds.setAttr(dest + ".rotateX", 0) cmds.setAttr(dest + ".rotateY", 0)
def resolveNamespaceClashes(self, tempNamespace): returnNames = [] cmds.namespace(setNamespace=tempNamespace) namespaces = cmds.namespaceInfo(listOnlyNamespaces=True) cmds.namespace(setNamespace=":") existingNamespaces = cmds.namespaceInfo(listOnlyNamespaces=True) for i in range(len(namespaces)): namespaces[i] = namespaces[i].partition(tempNamespace+":")[2] for name in namespaces: newName = str(name) oldName = tempNamespace + ":" + name if name in existingNamespaces: highestSuffix = utils.findHighestTrailingNumber(existingNamespaces, name+"_") highestSuffix += 1 newName = str(name) + "_" + str(highestSuffix) returnNames.append([oldName, newName]) self.resolveNameChangeMirrorLinks(returnNames, tempNamespace) self.renameNamespaces(returnNames) return returnNames
def list_cam(self, cam_namespace): set_name = '{}:{}'.format(cam_namespace, defaults._camrig_export_set_) if cmds.objExists(set_name): cmds.select(set_name, replace=1) shapes_list = cmds.ls(selection=True) camera = shapes_list[0] camera_shape = cmds.listRelatives(camera, shapes=1) return camera_shape[0] else: if cmds.namespaceInfo(cur=1) != cam_namespace: cmds.namespace(set=cam_namespace) shapes_list = cmds.namespaceInfo(listNamespace=True) cam = None for shape in shapes_list: if cmds.objectType(shape) == 'camera': cam = shape break if cam: return cam else: print('camera or {} not found'.format(set_name)) return None
def test_import_without_dag(taskfile_without_dagnodes, djprj, assettypinter, mrefobjinter): cmds.file(new=True, force=True) cmds.namespace(add="foo") cmds.namespace(set="foo") assert cmds.namespaceInfo(absoluteName=True) == ":foo" tf = djprj.assettaskfiles[0] tfi = TaskFileInfo.create_from_taskfile(tf) refobj = mrefobjinter.create(typ="Asset", identifier=0) assettypinter.import_taskfile(refobj, tfi) # assert namespace is still the same assert cmds.namespaceInfo(absoluteName=True) == ":foo" ns = cmds.getAttr("%s.namespace" % refobj) assert ns == "smurf_1" assert not cmds.ls(type="jb_asset") assert cmds.getAttr("%s.taskfile_id" % refobj) == tf.pk # reference2 refobj2 = mrefobjinter.create(typ="Asset", identifier=1) assettypinter.import_taskfile(refobj2, tfi) # assert namespace is still the same assert cmds.namespaceInfo(absoluteName=True) == ":foo" ns2 = cmds.getAttr("%s.namespace" % refobj2) assert ns2 == "smurf_2" assert ns2 != ns assert not cmds.ls(type="jb_asset") assert cmds.getAttr("%s.taskfile_id" % refobj2) == tf.pk content = cmds.namespaceInfo(ns, listNamespace=True) content2 = cmds.namespaceInfo(ns2, listNamespace=True) for n in content + content2: assert cmds.referenceQuery(n, isNodeReferenced=True) is False
def deleteNsContents(self, nameSpace): mc.namespace(set=":") mc.namespace(set=":"+nameSpace) if self.debug: print"current ns: ", mc.namespaceInfo(currentNamespace=True) nsContent = mc.namespaceInfo(ls=True, listOnlyDependencyNodes=True) if not nsContent: return for i in mc.namespaceInfo(ls=True, listOnlyDependencyNodes=True): delStr = i.split(":")[-1] try: print "deleting:", delStr #print mc.nodeType(i) mc.delete(i) self.count += 1 except: if self.debug:print "can not delete: ", i pass if self.debug: print "renaming namespace: ", nameSpace self.setNsCleaned(nameSpace)
def addCharacter(self, close, *args): project = cmds.optionMenu(self.widgets["project"], q=True, value=True) selectedCharacter = cmds.textScrollList(self.widgets["characterList"], q=True, si=True)[0] rigPath = os.path.join( self.mayaToolsDir, "General", "ART", "Projects", project, "AnimRigs", selectedCharacter + ".mb" ) # find existing namespaces in scene namespaces = cmds.namespaceInfo(listOnlyNamespaces=True) # reference the rig file cmds.file( rigPath, r=True, type="mayaBinary", loadReferenceDepth="all", namespace=selectedCharacter, options="v=0" ) # clear selection and fit view cmds.select(clear=True) cmds.viewFit() panels = cmds.getPanel(type="modelPanel") # turn on smooth shading for panel in panels: editor = cmds.modelPanel(panel, q=True, modelEditor=True) cmds.modelEditor(editor, edit=True, displayAppearance="smoothShaded", displayTextures=True, textures=True) # find new namespaces in scene (this is here in case I need to do something later and I need the new name that was created) newCharacterName = selectedCharacter newNamespaces = cmds.namespaceInfo(listOnlyNamespaces=True) for name in newNamespaces: if name not in namespaces: newCharacterName = name # launch UI import ART_animationUI reload(ART_animationUI) ART_animationUI.AnimationUI() if close: cmds.deleteUI(self.widgets["window"])
def removeAllNS(deleteContent=False): checkingMessage(checkingWhat='REMOVING A LEVEL OF NAMESPACE NOW...', start=True, failed=False) ## Now remove all the nameSpaces!! This is to remove any clashes with the core_assemblies later on... safeNS = ['UI', 'shared'] getAllNameSpaces = cmds.namespaceInfo(listOnlyNamespaces=True) for eachNS in getAllNameSpaces: if eachNS not in safeNS: try: if deleteContent: cmds.namespace(removeNamespace=eachNS, deleteNamespaceContent=True) else: cmds.namespace(removeNamespace=eachNS, mergeNamespaceWithRoot=True) except RuntimeError: pass if cmds.namespaceInfo(listOnlyNamespaces=True) != ['UI', 'shared']: removeAllNS() else: checkingMessage(checkingWhat='NAMESPACES REMOVED...', start=False, failed=False)
def deleteNsContents(self, nameSpace): mc.namespace(set=":") mc.namespace(set=":" + nameSpace) if self.debug: print "current ns: ", mc.namespaceInfo(currentNamespace=True) nsContent = mc.namespaceInfo(ls=True, listOnlyDependencyNodes=True) if not nsContent: return for i in mc.namespaceInfo(ls=True, listOnlyDependencyNodes=True): delStr = i.split(":")[-1] try: print "deleting:", delStr #print mc.nodeType(i) mc.delete(i) self.count += 1 except: if self.debug: print "can not delete: ", i pass if self.debug: print "renaming namespace: ", nameSpace self.setNsCleaned(nameSpace)
def parse_sub_matrix(self, data): """ """ import maya.cmds as cmds from reveries.lib import DEFAULT_MATRIX from reveries.maya.hierarchy import container_from_id_path current_NS = cmds.namespaceInfo(currentNamespace=True, absoluteName=True) for container_id, sub_matrix in data["subMatrix"].items(): container = container_from_id_path(container_id, current_NS) full_NS = cmds.getAttr(container + ".namespace") nodes = cmds.namespaceInfo(full_NS, listOnlyDependencyNodes=True) # Collect hidden nodes' address hidden = data.get("hidden", {}).get(container_id, []) transform_id_map = self.transform_by_id(nodes) for address in sub_matrix: is_hidden = False if address == "GROUP": name, matrix = sub_matrix[address].popitem() transform = full_NS + ":" + name else: transform = transform_id_map.get(address) matrix = sub_matrix[address] if address in hidden and transform is not None: is_hidden = True if matrix == "<default>": matrix = DEFAULT_MATRIX yield transform, matrix, is_hidden
def resolveNamespaceClashes(self, tempNamespace): returnNames = [] cmds.namespace(setNamespace=tempNamespace) namespaces = cmds.namespaceInfo(listOnlyNamespaces=True) cmds.namespace(setNamespace=':') existingNamespaces = cmds.namespaceInfo(listOnlyNamespaces=True) for i in range(len(namespaces)): namespaces[i] = namespaces[i].partition(tempNamespace+ ':')[2] for name in namespaces: newName = str(name) oldName = tempNamespace + ':' + name if name in existingNamespaces: highestSuffix = utils.findHighestTrailingNumber(existingNamespaces, name+'_') highestSuffix += 1 newName = str(name) + '_' + str(highestSuffix) returnNames.append([oldName,newName]) self.resolveNameChangeMirrorLinks(returnNames,tempNamespace) self.renameNamespaces(returnNames) return returnNames
def rmSelect(_mode): if _mode == 0: _sel = mc.textScrollList("nameList", q=1, selectItem=1) else: _sel = mc.textScrollList("nameList", q=1, allItems=1) if _sel == None: return for eachSel in _sel: mc.namespace(set=':') allName = [eachSel] mc.namespace(set=eachSel) while mc.namespaceInfo(p=1) != ":": allName.append(mc.namespaceInfo(p=1)) parentName = mc.namespaceInfo(p=1) mc.namespace(set=':') mc.namespace(set=parentName) mc.namespace(set=':') for eachName in allName: mc.namespace(f=1, mv=(eachName, ":")) mc.namespace(rm=eachName) if mc.namespace(exists=eachSel) == 0: sys.stdout.write(u"已经清除%s..." % eachSel) mc.textScrollList("nameList", e=1, removeItem=eachSel)
def fixDoubleNamespaces(): """Import all elements into existing hierarchy if it already exists. Then delete the namespace and fixReferences()""" namespaces = cmds.namespaceInfo(listOnlyNamespaces=True, recurse=True, fullName=True) namespacesTofix = list(set([i.split(':')[0] for i in namespaces if ':' in i])) # Fix double namespaces for namespace in namespacesTofix: content = cmds.namespaceInfo(namespace, listNamespace=True, dagPath=True) tofixList = [i for i in content if cmds.ls(i.replace(namespace + ':', ''))] # Check if nodes already exists with the same name if we remove the namespace tofix = {} for i in tofixList: # Sort the elements by hierarchy level lenght = len(i.split('|')) try: tofix[lenght].append(i) except KeyError: tofix[lenght] = [i] for keys, values in reversed(sorted(tofix.iteritems())): for node in values: if isGroup(node): childrens = cmds.listRelatives(node, children=True, fullPath=True) or [] for u in childrens: upperGrp = node.replace(namespace + ':', '') cmds.parent(u, upperGrp) # parent each child to the original group cmds.delete(node) # then delete the empty group fixReferences() cmds.namespace(removeNamespace=namespace, mergeNamespaceWithRoot=True) return namespacesTofix
def retrieveListEmptyNamespaces(self, root): del self.listEmptyNamespace[:] listNs = cmds.namespaceInfo(root, listOnlyNamespaces=True, recurse = True ) if listNs != None: for namespace in listNs: if namespace != "UI" and namespace != "shared": if cmds.namespaceInfo(namespace, listNamespace=True ) == None: self.listEmptyNamespace.append(namespace)
def cleanUp_Namespace(self, match_NSChar): mc.namespace(set=":") allNamespaces = mc.namespaceInfo(listOnlyNamespaces=True) p = re.compile(match_NSChar) idleNamespace = [allNamespaces[i] for i in range(len(allNamespaces)) if len(p.findall(allNamespaces[i])) != 0] for eachINS in idleNamespace: self.remove_namespace(eachINS) return (mc.namespaceInfo(listOnlyNamespaces=True))
def nameSpaceRemover(*args): cmds.namespace(setNamespace=':') namespaces = cmds.namespaceInfo(':', listOnlyNamespaces=True) while len(namespaces) > 2: namespaces = cmds.namespaceInfo(':', listOnlyNamespaces=True) for d in ('UI', 'shared'): if d in namespaces: namespaces.remove(d) for n in namespaces: cmds.namespace(mergeNamespaceWithRoot=True, removeNamespace=n) print 'Namespace ' + n + 'removed.'
def reference(self, refobj, taskfileinfo): """Reference the given taskfileinfo into the scene and return the created reference node The created reference node will be used on :meth:`RefobjInterface.set_reference` to set the reference on a reftrack node. Do not call :meth:`RefobjInterface.set_reference` yourself. This will also create a group node and group all dagnodes under a appropriate node. :param refobj: the reftrack node that will be linked to the reference :type refobj: str :param taskfileinfo: The taskfileinfo that holds the information for what to reference :type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo` :returns: the reference node that was created and should set on the appropriate reftrack node :rtype: str :raises: None """ # work in root namespace with common.preserve_namespace(":"): jbfile = JB_File(taskfileinfo) filepath = jbfile.get_fullpath() ns_suggestion = reftrack.get_namespace(taskfileinfo) newnodes = cmds.file(filepath, reference=True, namespace=ns_suggestion, returnNewNodes=True) # You could also use the filename returned by the file command to query the reference node. # Atm there is a but, that if you import the file before, the command fails. # So we get all new reference nodes and query the one that is not referenced for refnode in cmds.ls(newnodes, type='reference'): if not cmds.referenceQuery(refnode, isNodeReferenced=True): node = refnode break ns = cmds.referenceQuery( node, namespace=True) # query the actual new namespace content = cmds.namespaceInfo(ns, listOnlyDependencyNodes=True, dagPath=True) # get the content # connect reftrack with scenenode scenenode = self.get_scenenode(content) self.get_refobjinter().connect_reftrack_scenenode( refobj, scenenode) reccontent = cmds.namespaceInfo( ns, listOnlyDependencyNodes=True, dagPath=True, recurse=True) # get the content + content of children dagcontent = cmds.ls( reccontent, ap=True, assemblies=True ) # get only the top level dagnodes so we can group them if not dagcontent: return node # no need for a top group if there are not dagnodes to group # group the dagnodes grpname = reftrack.get_groupname(taskfileinfo) reftrack.group_content(dagcontent, ns, grpname, "jb_asset") return node
def _getNamespace(): namespaces = mc.namespaceInfo(lon=True) _nestedNS = [] for ns in namespaces: nestedNS = mc.namespaceInfo(ns, lon=True) print ns, nestedNS if nestedNS != None: _nestedNS += nestedNS namespaces += _nestedNS namespaces.remove('UI') namespaces.remove('shared') return namespaces
def addCharacter(self, close, *args): project = cmds.optionMenu(self.widgets["project"], q=True, value=True) selectedCharacter = cmds.textScrollList(self.widgets["characterList"], q=True, si=True)[0] rigPath = self.mayaToolsDir + "/General/ART/Projects/" + project + "/AnimRigs/" + selectedCharacter + ".mb" #find existing namespaces in scene namespaces = cmds.namespaceInfo(listOnlyNamespaces=True) #reference the rig file cmds.file(rigPath, r=True, type="mayaBinary", loadReferenceDepth="all", namespace=selectedCharacter, options="v=0") #clear selection and fit view cmds.select(clear=True) #query autoKeyFrame state if not cmds.autoKeyframe(q=True, state=True): cmds.viewFit() #cmds.viewFit() panels = cmds.getPanel(type='modelPanel') #turn on smooth shading for panel in panels: editor = cmds.modelPanel(panel, q=True, modelEditor=True) cmds.modelEditor(editor, edit=True, displayAppearance="smoothShaded", displayTextures=True, textures=True) #find new namespaces in scene (this is here in case I need to do something later and I need the new name that was created) newCharacterName = selectedCharacter newNamespaces = cmds.namespaceInfo(listOnlyNamespaces=True) for name in newNamespaces: if name not in namespaces: newCharacterName = name #launch UI import ART_animationUI reload(ART_animationUI) ART_animationUI.AnimationUI() if close: cmds.deleteUI(self.widgets["window"])
def removeAllNamespaces(self) : print('[removeAllNamespaces]') cmds.namespace(setNamespace=":") spaces = cmds.namespaceInfo(listOnlyNamespaces=True) omit = ['shared', 'UI'] while(len(spaces) > 2) : for s in spaces : if s in omit : continue print(s) objs = cmds cmds.namespace(moveNamespace=[s, ':'], force=True) cmds.namespace(removeNamespace=s) spaces = cmds.namespaceInfo(listOnlyNamespaces=True)
def removeNS(str): eachSel = str mc.namespace(set=':') allName = [eachSel] mc.namespace(set=eachSel) while mc.namespaceInfo(p=1) != ":": parentName = mc.namespaceInfo(p=1) allName.append(parentName) mc.namespace(set=':') mc.namespace(set=parentName) mc.namespace(set=':') for eachName in allName: mc.namespace(f=1,mv=(eachName,":")) mc.namespace(rm=eachName)
def getNamespace(self): returnNamespaces = [] namespaces = cmds.namespaceInfo(lon=True) for namespace in namespaces: if namespace != 'UI' and namespace != 'shared': returnNamespaces.append(namespace) return returnNamespaces
def iterNamespaces( namespace=':' ): ''' iterates over all namespaces under and including the one given... holy sH1t namespaces suck b4lls in maya ''' if namespace.endswith( ':' ): namespace = namespace[ :-1 ] namespaces = [ namespace ] idx = 0 while True: try: curNS = namespaces[ idx ] except IndexError: break idx += 1 try: cmd.namespace( set=curNS ) except RuntimeError: continue subs = cmd.namespaceInfo( listOnlyNamespaces=True ) if subs is None: continue namespaces += subs return iter( namespaces )
def import_taskfile(self, refobj, taskfileinfo): """Import the given taskfileinfo and update the refobj :param refobj: the refobject :type refobj: refobject :param taskfileinfo: the taskfileinfo to reference :type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo` :returns: None :rtype: None :raises: None """ # work in root namespace with common.preserve_namespace(":"): jbfile = JB_File(taskfileinfo) filepath = jbfile.get_fullpath() ns_suggestion = reftrack.get_namespace(taskfileinfo) nodes = cmds.file(filepath, i=True, namespace=ns_suggestion, returnNewNodes=True, preserveReferences=True) # import assert nodes, 'Nothing was imported! this is unusual!' ns = common.get_top_namespace(nodes[0]) # get the actual namespace cmds.setAttr("%s.namespace" % refobj, ns, type="string") nscontent = cmds.namespaceInfo(ns, listOnlyDependencyNodes=True, dagPath=True) # get the content scenenode = self.get_scenenode(nscontent) self.get_refobjinter().connect_reftrack_scenenode(refobj, scenenode) dagcontent = cmds.ls(nodes, ap=True, assemblies=True) # get only the dagnodes so we can group them if not dagcontent: return # no need for a top group if there are not dagnodes to group # group the dagnodes in the new namespace grpname = reftrack.get_groupname(taskfileinfo) reftrack.group_content(dagcontent, ns, grpname, "jb_asset") return
def get_node_in_namespace_hierarchy(node, namespace=None, shape=False): """Searches a namespace and all nested namespaces for the given node. :param node: Name of the node. :param namespace: Root namespace :param shape: True to get the shape node, False to get the transform. :return: The node in the proper namespace. """ if shape and node and cmds.objExists(node): node = get_shape(node) if node and cmds.objExists(node): return node if node and namespace: # See if it exists in the namespace or any child namespaces namespaces = [namespace.replace(":", "")] namespaces += cmds.namespaceInfo(namespace, r=True, lon=True) or [] for namespace in namespaces: namespaced_node = "{0}:{1}".format(namespace, node) if shape: namespaced_node = get_shape(namespaced_node) if namespaced_node and cmds.objExists(namespaced_node): return namespaced_node return None
def refreshAnimationModuleList(self, index=1): cmds.textScrollList(self.UIElements["animationModule_textScroll"], edit=True, removeAll=True) cmds.symbolButton(self.UIElements["deleteModuleButton"], edit=True, enable=False) cmds.symbolButton(self.UIElements["duplicateModuleButton"], edit=True, enable=False) selectedBlprnModule = cmds.textScrollList(self.UIElements["blueprintModule_textScroll"], q=True, selectItem=True) self.selectedBlueprintModule = self.blueprintModules[selectedBlprnModule[0]] self.setupActiveModuleControls() cmds.namespace(setNamespace=self.selectedBlueprintModule) controlModuleNamespaces = cmds.namespaceInfo(listOnlyNamespaces=True) cmds.namespace(setNamespace=":") if controlModuleNamespaces != None: for module in controlModuleNamespaces: moduleName = utils.stripAllNamespaces(module)[1] cmds.textScrollList(self.UIElements["animationModule_textScroll"], edit=True, append=moduleName) cmds.textScrollList(self.UIElements["animationModule_textScroll"], edit=True, selectIndexedItem = index) cmds.symbolButton(self.UIElements["deleteModuleButton"], edit=True, enable=True) cmds.symbolButton(self.UIElements["duplicateModuleButton"], edit=True, enable=True) cmds.symbolButton(self.UIElements["zeroModulesButton"], edit=True, enable=True) self.setupModuleSpecificControls() self.previousBlueprintListEntry = selectedBlprnModule
def cmd_makeRefOfSelection(pathField='', fileField='', nsField='', *args): path = cmds.textFieldGrp(pathField, q=True, text=True) fyle = cmds.textFieldGrp(fileField, q=True, text=True) ns = cmds.textFieldGrp(nsField, q=True, text=True) nsList = cmds.namespaceInfo(lon=True) sel = cmds.ls(sl=True) if sel: f = fyle if f: path = os.path.join(path, f) else: message('Provide a file name, excluding path.', warning=True) return None if ns: if ns not in nsList: try: cmds.file(path, type='mayaAscii', er=True, namespace=ns) except: message('Export Failed... In case your object is already a reference, make a duplicate or import it. Then try again.', warning=True) else: message('Namespace "' + ns + '" already exists. Choose another!', warning=True) else: message('Provide a namespace for the reference.', warning=True) return None else: message( 'Select and object', warning=True)
def findNamaSpaces(): cmds.namespace(setNamespace=":") namespaces = cmds.namespaceInfo(listOnlyNamespaces=True) for namespace in namespaces: if cmds.objExists(namespace + ":*"): # create a tab widgets[(namespace + "_tab")] = cmds.columnLayout( w=400, h=600, parent=widgets["tabLayout"]) # create attr field grps for translate rotate and scale cmds.separator(h=10, style="none") widgets[(namespace + "_attrFG_T")] = cmds.attrFieldGrp( attribute=(namespace + ":null.translate")) widgets[(namespace + "_attrFG_R")] = cmds.attrFieldGrp( attribute=(namespace + ":null.rotate")) widgets[(namespace + "_attrFG_S")] = cmds.attrFieldGrp( attribute=(namespace + ":null.scale")) cmds.separator(h=10, style="none") widgets[(namespace + "_attrEOM_Vis")] = cmds.attrEnumOptionMenu( label="Test", attribute=(namespace + ":null.Test")) # edit the tab name cmds.tabLayout(widgets["tabLayout"], edit=True, tabLabel=(widgets[(namespace + "_tab")], namespace))
def nsPaths(): nsList = cmds.namespaceInfo(lon=True) nsPathsList = [] for ns in nsList: if 'Path_' in ns: nsPathsList.append(ns) return nsPathsList
def installModule(self, module, *arg): basename = 'instance_' cmds.namespace(setNamespace=":") namespaces = cmds.namespaceInfo(listOnlyNamespaces=True) for i in range(len(namespaces)): if namespaces[i].find('__') != -1: namespaces[i] = namespaces[i].partition('__')[2] newSuffix = utils.findHighestTrailingNumber(namespaces, basename) + 1 userSpecName = basename + str(newSuffix) hookObj = self.findHookObjectFromSelection() mod = __import__('Blueprint.'+ module,{},{},[module]) reload(mod) moduleClass = getattr(mod, mod.CLASS_NAME) moduleInstance = moduleClass(userSpecName, hookObj) moduleInstance.install() #this is to make sure move tool is selected by default moduleTransform = mod.CLASS_NAME + '__' + userSpecName + ':module_transform' cmds.select(moduleTransform, replace=True) cmds.setToolTo('moveSuperContext')
def searchCharsName(): """检索当前场景中的所有角色名 Description: 根据绑定文件的命名规范与reference原则,从命名空间中就可获得角色名称 Arguments: 无 Returns: allCharsNameList:所有角色名列表(无重复) """ cmds.namespace(set = ":") allNamespace = cmds.namespaceInfo(listOnlyNamespaces = True) #拿到所有根目录下的命名空间名称 allCharsName = [] for eachNamespace in allNamespace: #拿到带有_Char_的命名空间名称,从中拿到角色名 if eachNamespace.find("_chr_") < 0: print "This Is Not A Char!" else: namesapceWithChar = eachNamespace charName = namesapceWithChar.split("_")[2] #charName存放角色名 allCharsName.append(charName) allCharsNameList = cT.delDupFromList(allCharsName) #调用函数去除list中的重复元素 return allCharsNameList
def get_non_existing_namespace(prefix='dw'): i = 0 namespace = '%s%i' % (prefix, i) while namespace in mc.namespaceInfo(listNamespace=True): i += 1 namespace = '%s%i' % (prefix, i) return namespace
def iterNamespaces(namespace=':'): ''' iterates over all namespaces under and including the one given... holy sH1t namespaces suck b4lls in maya ''' if namespace.endswith(':'): namespace = namespace[:-1] namespaces = [namespace] idx = 0 while True: try: curNS = namespaces[idx] except IndexError: break idx += 1 try: cmd.namespace(set=curNS) except RuntimeError: continue subs = cmd.namespaceInfo(listOnlyNamespaces=True) if subs is None: continue namespaces += subs return iter(namespaces)
def importSkinByRef(ref, file, skip=[], **kwargs): """Import skin for every dag node in reference.""" if not os.path.exists(file): rigUtils.log('Skin file not found - skipping: %s' % file) return rigUtils.log('Reading file: %s' % file) f = open(file, 'r') j = json.loads(f.read()) f.close() cmds.namespace(set=ref) dagnodes = cmds.namespaceInfo(lod=True) cmds.namespace(set=':') skinned = [] for dagnode in dagnodes: if skip: if dagnode in skip: continue if dagnode in j: dict = j[dagnode] try: skindict = dict['skinCluster'] except: continue importSkin(skindict, dagnode, **kwargs) skinned.append(dagnode) return skinned
def get_scene_namespaces(): """ Return a list of namespaces *Arguments:* * ``None`` *Keyword Arguments:* * ``None`` *Returns:* * ``None`` *Author:* * randall.hess, [email protected], 11/6/2014 1:36:02 PM """ try: cmds.namespace(setNamespace=":") except: pass ignore_names = ["UI","shared"] all_namespaces = cmds.namespaceInfo(listOnlyNamespaces=True, recurse=True) namespaces = [] for namespace in all_namespaces: if not any ([x in namespace for x in ignore_names]): namespaces.append(namespace) return namespaces
def deleteModule(self, *args): """ Delete the Guide, ModuleLayout and Namespace. """ # delete mirror preview: try: cmds.delete(self.moduleGrp[:self.moduleGrp.find(":")]+"_MirrorGrp") except: pass # delete the guide module: utils.clearNodeGrp(nodeGrpName=self.moduleGrp, attrFind='guideBase', unparent=True) # clear default 'dpAR_GuideMirror_Grp': utils.clearNodeGrp() # remove the namespaces: allNamespaceList = cmds.namespaceInfo(listOnlyNamespaces=True) if self.guideNamespace in allNamespaceList: cmds.namespace(moveNamespace=(self.guideNamespace, ':'), force=True) cmds.namespace(removeNamespace=self.guideNamespace, force=True) try: # delete the moduleFrameLayout from window UI: cmds.deleteUI(self.moduleFrameLayout) self.clearSelectedModuleLayout() # edit the footer A text: self.currentText = cmds.text("footerAText", query=True, label=True) cmds.text("footerAText", edit=True, label=str(int(self.currentText[:self.currentText.find(" ")]) - 1) +" "+ self.langDic[self.langName]['i005_footerA']) except: pass # clear module from instance list (clean dpUI list): delIndex = self.dpUIinst.moduleInstancesList.index(self) self.dpUIinst.moduleInstancesList.pop(delIndex)
def createModuleButtonCommand(self, moduleClassName, *args): ## DEALING WITH NAMESPACES moduleName = cmds.textFieldGrp(self.UIwidgets[moduleClassName + "ModuleName"], q=True, text=True) if moduleName == "": moduleName = moduleClassName ## need to check if name has "_" character in it. If so we need to remove it. ## if name does not have "_" at the end, add it if moduleName.partition("_")[1] == "": moduleName = moduleName + "_" ## gather all namespaces allNamespaces = cmds.namespaceInfo(listNamespace=True) ## gather the highest number index = util.findHighestTrailingNumber(allNamespaces, moduleName) ## check to see if module name is in the list of namespaces. if so, add 1. if not leave alone if moduleName + str(index) in allNamespaces: moduleName = moduleName + str(index + 1) else: moduleName = moduleName + str(index) # need to find correct module file modName = util.findModule(RIGGING_TOOL_ROOT, moduleClassName) # import that module mod = __import__(environ.BlueprintModulePath + modName, {}, {}, [modName]) reload(mod) # Get class reference for Blueprint module class, then create user specified instance of Blueprint module class and call it's Constructor and install method. # getAttr returns import reference, moduleClass = getattr(mod, mod.ClassName) moduleInstance = moduleClass(moduleName) moduleInstance.install_joints()
def test_replace(taskfile_with_dagnodes, taskfile_with_dagnodes2, djprj, assettypinter, mrefobjinter): cmds.file(new=True, force=True) tf = djprj.assettaskfiles[0] tfi = TaskFileInfo.create_from_taskfile(tf) refobj = mrefobjinter.create(typ="Asset", identifier=0) assettypinter.reference(refobj, tfi) refnode = cmds.referenceQuery(taskfile_with_dagnodes, referenceNode=True) ns = cmds.referenceQuery(refnode, namespace=True) ns = cmds.namespaceInfo(ns, fullName=True) assert "%s:testdagnode" % ns in cmds.ls(type="transform") assert "%s:othertestnode" % ns not in cmds.ls(type="transform") tf2 = djprj.assettaskfiles[1] tfi2 = TaskFileInfo(task=tf2.task, version=tf2.version, releasetype=tf2.releasetype, descriptor=tf2.descriptor, typ=tf2.typ) assettypinter.replace(refobj, refnode, tfi2) assert "%s:othertestnode" % ns in cmds.ls(type="transform") assert "%s:testdagnode" % ns not in cmds.ls(type="transform") assert cmds.getAttr("%s.taskfile_id" % refobj) == tf2.pk assert '%s:jb_sceneNode_test' % ns in cmds.listConnections('%s.scenenode' % refobj) assert cmds.listConnections('%s.taskfile_id' % refobj) == ['%s:jb_sceneNode_test' % ns] assettypinter.replace(refobj, refnode, tfi2) # this will reference the same file again. it will get a copy number # the file command does not return the name with copy number. seems like a bug # because the doc sais it will. You have to use the reference node for referenceQuery instead # to get the namespace, not the filename that is returned by the file command. assettypinter.replace(refobj, refnode, tfi)
def removeAllNS(deleteContent = False): ## Now remove all the nameSpaces!! This is to remove any clashes with the core_assemblies later on... safeNS = ['UI', 'shared'] getAllNameSpaces = cmds.namespaceInfo(listOnlyNamespaces = True) for eachNS in getAllNameSpaces: if eachNS not in safeNS: try: if deleteContent: cmds.namespace(removeNamespace = eachNS, deleteNamespaceContent = True) else: cmds.namespace(removeNamespace = eachNS, mergeNamespaceWithRoot = True) except RuntimeError: pass if cmds.namespaceInfo(listOnlyNamespaces = True) != ['UI', 'shared']: removeAllNS()
def _fixTheFuckingCores(self): """ This is used to clean sweep the static scenes and remove the duplicate Namespaces and reconnect the bases to the duplicates """ removedNameSpaces = [] ## Remove duplicate root core namespaces getAllNameSpaces = cmds.namespaceInfo(listOnlyNamespaces = True) for eachNS in getAllNameSpaces: if eachNS.endswith('1'): print 'Removing %s' % eachNS cmds.namespace(removeNamespace = eachNS, mergeNamespaceWithRoot = True) removedNameSpaces.append(eachNS.replace('1', '').replace('_CORE', '')) ## Remove duplicate base cores for each in cmds.ls(type = 'core_archive'): if '1'in each: print 'Cleaned rootCore %s from scene...' % each cmds.delete(each) ## Now find all geo with the core name in it and proceess it for reconnection for eachCore in removedNameSpaces: #print eachCore ## Check child _hrc grps for processing getAllGeo = [eachGeo for eachGeo in cmds.ls('*%s*' % eachCore) if cmds.nodeType(eachGeo) == 'transform'] for eachGeo in getAllGeo: self._reconnectDuplicates(eachGeo, '%s_CORE_Geoshader' % eachCore) coreLib.cleanupDeadCoreArchives()
def _createNativeModel(self, name='Model', nativeObjects=[], referenced=False): name = 'Model' if not name else name # Create a "model" namespace and add the locator to it # TODO: Make this a context currentNamespace = cmds.namespaceInfo(currentNamespace=True) namespace = cmds.namespace(addNamespace=name) cmds.namespace(setNamespace=namespace) # Create the transform node then the shape node so the transform is properly named parent = cmds.createNode('transform', name='Model') #name = cmds.createNode('locator', name='{}Shape'.format(name), parent=parent) output = cross3d.SceneWrapper._asMOBject(parent) userProps = cross3d.UserProps(output) userProps['model'] = True if referenced: userProps['referenced'] = referenced # Create the Active_Resolution enum if it doesn't exist # cmds.addAttr(name, longName="Active_Resolution", attributeType="enum", enumName="Offloaded:") # userProps['Resolutions'] = OrderedDict(Offloaded='') cmds.namespace(setNamespace=currentNamespace) # Add each of nativeObjects to the model namespace if nativeObjects: for nativeObject in nativeObjects: nativeObject = cross3d.SceneWrapper._getTransformNode(nativeObject) objName = cross3d.SceneWrapper._mObjName(nativeObject) # cmds.parent(objName, cross3d.SceneWrapper._mObjName(nativeParent)) nameInfo = cross3d.SceneWrapper._namespace(nativeObject) newName = '{namespace}:{name}'.format(namespace=namespace, name=nameInfo['name']) cmds.rename(objName, newName) nativeObjects.append(output) return output
def delete_ns(): logger.info("Deleting namespaces ----------------------------------") try: defaults = ['UI', 'shared'] # Used as a sort key, this will sort namespaces by how many children they have. def num_children(ns): return ns.count(':') namespaces = [ ns for ns in cmds.namespaceInfo(lon=True, r=True) if ns not in defaults ] # We want to reverse the list, so that namespaces with more children are at the front of the list. namespaces.sort(key=num_children, reverse=True) for ns in namespaces: if namespaces.index(ns) + 1 < len(namespaces): parent_ns = namespaces[namespaces.index(ns) + 1] cmds.namespace(mv=[ns, parent_ns], f=True) cmds.namespace(rm=ns) else: cmds.namespace(mv=[ns, ":"], f=True) cmds.namespace(rm=ns) except Exception, err: logger.info(err) logger.info("Delete namespaces failed")
def remove(name): all_namespace = cmds.namespaceInfo(listOnlyNamespaces=1) if name not in all_namespace: print "%s is not a namespace" % name return children = cmds.namespaceInfo(name, lon=1) if children: for child in children: remove(child) try: cmds.namespace(mv=(name, ':'), f=1) cmds.namespace(rm=name) except: print "## Failed:", name else: print "// Removed:", name
def namespaceList(current= None): """ """ if not current: cmds.namespace(set = ':') return cmds.namespaceInfo(lon= 1, r= 1, an= 1)
def getCharacterInfo(): cmds.namespace(set=":") namespaces = cmds.namespaceInfo(lon=True) characterName = [] for name in namespaces: """ TODO: """ """ I need a global check for valid characters in the scene """ characterContainer = (name + ":character_container") setupContainer = name.replace("Character__", "Export__") setupContainer = (setupContainer + ":Setup") if cmds.objExists (characterContainer): fullCharName = name tmpCharName = name.split("__")[1] tmpCharName = tmpCharName[:tmpCharName.rfind("_")] characterName = tmpCharName return (characterName, characterContainer, fullCharName, setupContainer) else: characterContainer = 'Character__tmp_1:character_container' fullCharName = name tmpCharName = name.split("__")[1] tmpCharName = tmpCharName[:tmpCharName.rfind("_")] characterName = tmpCharName return (characterName, characterContainer, fullCharName, setupContainer) # Warn no character in the scene #charConfirm = ("No character exists in this scene") #cmds.confirmDialog(messageAlign="center", title="Create Directory", message= charConfirm) characterName = 'Character__tmp' return characterName
def namespaces(): namespaces = [] namespaceInfo = cmds.namespaceInfo(lon=1) for i in range(0,len(namespaceInfo)): if (namespaceInfo[i].count("UI")!=1) and (namespaceInfo[i].count("shared")!=1): namespaces.append(namespaceInfo[i]) return namespaces
def install_module(self,module,*args): basename = "instance_" cmds.namespace(setNamespace =":") namespaces = cmds.namespaceInfo(listOnlyNamespaces=True) for i in range(len(namespaces)): if namespaces[i].find("__") != -1: namespaces[i] = namespaces[i].partition("__")[2] new_suffix = utils.find_highest_trailing_number(namespaces, basename)+1 user_specified_name = basename+str(new_suffix) hook_obj = self.find_hook_obj_from_selection() mod = __import__("blueprint."+module, {}, {}, [module]) reload(mod) module_class = getattr(mod, mod.CLASS_NAME) module_instance = module_class(user_specified_name, hook_obj) module_instance.install() module_trans = mod.CLASS_NAME+"__"+user_specified_name+":module_transform" cmds.select(module_trans,replace=True) cmds.setToolTo("moveSuperContext")
def current( cls ): """:return: the currently set absolute namespace """ # will return namespace relative to the root - thus is absolute in some sense nsname = cmds.namespaceInfo( cur = 1 ) if not nsname.startswith( ':' ): # assure we return an absoslute namespace nsname = ":" + nsname return cls( nsname )
def unique_namespace(namespace, format="%02d", prefix="", suffix=""): """Return unique namespace Similar to :func:`unique_name` but evaluating namespaces as opposed to object names. Arguments: namespace (str): Name of namespace to consider format (str, optional): Formatting of the given iteration number suffix (str, optional): Only consider namespaces with this suffix. """ iteration = 1 unique = prefix + (namespace + format % iteration) + suffix # The `existing` set does not just contain the namespaces but *all* nodes # within "current namespace". We need all because the namespace could # also clash with a node name. To be truly unique and valid one needs to # check against all. existing = set(cmds.namespaceInfo(listNamespace=True)) while unique in existing: iteration += 1 unique = prefix + (namespace + format % iteration) + suffix return unique
def remove_namespace(self, namespace_name): children = mc.namespaceInfo(namespace_name, listOnlyNamespaces=1) if children: for child in children: self.remove_namespace(child) mc.namespace(moveNamespace=(namespace_name, ":"), f=1) mc.namespace(removeNamespace=namespace_name)
def get_node_in_namespace_hierarchy(node, namespace=None, shape=False): """Searches a namespace and all nested namespaces for the given node. :param node: Name of the node. :param namespace: Root namespace :param shape: True to get the shape node, False to get the transform. :return: The node in the proper namespace. """ if shape and node and cmds.objExists(node): node = get_shape(node) if node and cmds.objExists(node): return node if node and namespace: # See if it exists in the namespace or any child namespaces namespaces = [namespace.replace(':', ''),] namespaces += cmds.namespaceInfo(namespace, r=True, lon=True) or [] for namespace in namespaces: namespaced_node = '{0}:{1}'.format(namespace, node) if shape: namespaced_node = get_shape(namespaced_node) if namespaced_node and cmds.objExists(namespaced_node): return namespaced_node return None
def stripNamespace(filename): try: #open the file cmds.loadPlugin("fbxmaya.mll") string = "FBXImportMode -v \"add\";" string += "FBXImport -file \"" + filename + "\"" string += "FBXImportFillTimeline -v true" mel.eval(string) #remove the namespace cmds.namespace(setNamespace="::") currentNamespaces = cmds.namespaceInfo(listOnlyNamespaces=True) restricted = ['UI', 'shared'] for namespace in currentNamespaces: if namespace not in restricted: cmds.namespace(mv=(':' + namespace, ':'), force=True) cmds.namespace(removeNamespace=namespace) #re-export the file mel.eval("FBXExport -f \"" + filename + "\"") #exit std.uninitialize() except Exception, e: sys.stderr.write(str(e)) sys.exit(-1)
def isRootTransformInstalled(self): cmds.namespace(setNamespace=':') namespaces = cmds.namespaceInfo(listOnlyNamespaces=True) for namespace in namespaces: if namespace.find('RootTransform__') == 0: return True return False
def remove(namespaces = 'all'): if namespaces == 'all': namespaces = cmds.namespaceInfo(lon = 1) for namespace in namespaces: cmds.namespace(f=1,mv=(namespace,":")) if namespace.count("UI") <1 and namespace.count("uv") <1 and namespace.count("shared") <1: cmds.namespace(f=1,rm=str(namespace))