示例#1
2
def referenceRelatives( rfn, onlyLoaded=False, parents=False ):
    """
    List all currently loaded references in current scene.
    """
    result = []
    references = [ rfn ]
    if references:
        while references:
            mcache = []
            for i in range( 0, len( references )):
                if references[i] not in result and ( onlyLoaded is True and cmds.referenceQuery( references[i], isLoaded=True ) or onlyLoaded is not True ):
                    result.append( references[i] )
                    if parents is False:
                        relatives = cmds.referenceQuery( references[i], child=True, rfn=True )
                    else:
                        relatives = cmds.referenceQuery( references[i], parent=True, rfn=True )
                    if relatives:
                        relatives = type( relatives ) is not list and [ relatives ] or relatives
                        for n in range( 0, len( relatives )):
                            if relatives[n] not in result:
                                mcache.append( relatives[n] )
            if mcache:
                references = mcache
            else:
                break
    return result
    def get_invalid(instance):
        """Return invalid reference nodes in the instance

        Terminology:
            reference node: The node that is the actual reference containing
                the nodes (type: reference)
            referenced nodes: The nodes contained within the reference
                (type: any type of nodes)

        """
        referenced_nodes = cmds.ls(instance, referencedNodes=True, long=True)
        if not referenced_nodes:
            return list()

        # Get reference nodes from referenced nodes
        # (note that reference_nodes != referenced_nodes)
        reference_nodes = set()
        for node in referenced_nodes:
            reference_node = cmds.referenceQuery(node, referenceNode=True)
            if reference_node:
                reference_nodes.add(reference_node)

        # Check for failed edits on each reference node.
        invalid = []
        for reference_node in reference_nodes:
            failed_edits = cmds.referenceQuery(reference_node,
                                               editNodes=True,
                                               failedEdits=True,
                                               successfulEdits=False)
            if failed_edits:
                invalid.append(reference_node)

        return invalid
示例#3
0
    def getAssetSelection(self): 
        objs = mc.ls(sl=True)
        assets = []
        namespaces = []
        if objs: 
            for obj in objs: 
                if mc.referenceQuery(obj, inr=True): 
                    path = mc.referenceQuery(obj, f=True)
                    asset = entityInfo.info(path)
                    if not asset.name() in assets: 
                        assets.append(asset.name())

                else: 
                    namespace = obj.split(':')[0]
                    if not namespace in namespaces: 
                        namespaces.append(namespace)

            for namespace in namespaces: 
                attr = '%s:Geo_Grp.assetName' % namespace 
                if mc.objExists(attr): 
                    assetName = mc.getAttr(attr)
                    if not assetName in assets: 
                        assets.append(assetName)


        return assets
示例#4
0
def doNameObject(obj,sceneUnique = False,fastIterate = True):
    """ 
    Names an object

    ARGUMENTS:
    obj(string) - the object we'd like to name
    sceneUnique(bool)- whether to do a full scene check or just the faster check

    RETURNS:
    newName(string) on success
    
    """
    ### input check
    assert mc.objExists(obj) is True, "'%s' doesn't exist" %obj
    assert mc.referenceQuery(obj, isNodeReferenced=True) is not True, "'%s' is referenced, can't name!" %obj
    
    name = returnUniqueGeneratedName(obj,sceneUnique, fastIterate)
    nameFactory = NameFactory(obj)
    
    if nameFactory.amIMe(name):
        guiFactory.warning("'%s' is already named correctly."%nameFactory.nameBase)
        return name
    else:
        objLong = mc.ls(obj,long=True)
        renameBuffer = mc.rename(objLong,name)

        shapes = mc.listRelatives(renameBuffer,shapes=True,fullPath=True)
        if shapes:
            for shape in shapes:
                if not mc.referenceQuery(shape, isNodeReferenced=True):
                    name = returnUniqueGeneratedName(shape,sceneUnique, fastIterate)
                    mc.rename(shape,name)
    
        return renameBuffer
示例#5
0
        def doTest(successfulEdits, failedEdits, force, expectedNum):
            self.setUp()
            self.createFailedEdits()

            # Should have 3 total, 2 successful, 1 failed
            refNode = str(self.sphereRef1.refNode)
            getKwargs = {'editStrings':True, 'onReferenceNode':refNode}

            getKwargs['successfulEdits'] = False
            getKwargs['failedEdits'] = True
            self.assertEqual(len(cmds.referenceQuery(refNode, **getKwargs)), 1)

            getKwargs['successfulEdits'] = True
            getKwargs['failedEdits'] = False
            self.assertEqual(len(cmds.referenceQuery(refNode, **getKwargs)), 2)

            getKwargs['successfulEdits'] = True
            getKwargs['failedEdits'] = True
            self.assertEqual(len(cmds.referenceQuery(refNode, **getKwargs)), 3)

            kwargs = {}
            if successfulEdits is not None:
                kwargs['successfulEdits'] = successfulEdits
            if failedEdits is not None:
                kwargs['failedEdits'] = failedEdits

            if force:
                kwargs['force'] = True

            self.sphereRef1.removeReferenceEdits(**kwargs)

            self.assertEqual(len(cmds.referenceQuery(refNode, **getKwargs)),
                             expectedNum)
示例#6
0
def cleanupReference( rfn ):
    #Get reference node.
    if cmds.nodeType( rfn ) == "reference":
        rfn = rfn
    elif os.path.isfile( rfn ):
        rfn = cmds.referenceQuery( rfn, rfn=True )
    else:
        print "%s is not reference" % rfn
        return None
    references = []
    pm = cmds.listConnections( rfn, type="proxyManager" )
    if pm:
        references = cmds.listConnections( "%s.proxyList" % pm[0], type="reference" )
    if not references:
        references = [ rfn ]
        m_words = "|".join( references )
    else:
        references = [ rfn ]
        m_words = rfn
    edits = []
    if references:
        for i in range( 0, len( references )):
            strings = cmds.referenceQuery( references[i], failedEdits=True, successfulEdits=True, editStrings=True )
            if strings:
                for i in range( 0, len( strings )):
                    if strings[i] not in edits:
                        if not re.findall( m_words, strings[i] ):
                            edits.append( strings[i] )
    if edits:
        removeEdits( rfn, edits )
示例#7
0
def getReferences(loadState=False, nodesInRef=False):
    """Returns a dictionary with the namespace as keys
    and a list containing the proxyManager if there is one, the refnode, and its load state
    """
    result = dict()
    proxyManagers = set()
    references = cmds.file(query=True, reference=True)
    for i in references:
        refNode = cmds.referenceQuery(i, referenceNode=True)
        connection = cmds.connectionInfo(refNode + '.proxyMsg', sourceFromDestination=True)
        if connection:
            proxyManagers.update([connection.split('.')[0]])
        else:
            namespace = cmds.file(i, parentNamespace=True, query=True)[0] + ':' + cmds.file(i, namespace=True, query=True)
            namespace = cmds.file(i, namespace=True, query=True)
            # namespace = ('' if namespace.startswith(':') else ':') + namespace
            result[i] = {'namespace': namespace, 'proxyManager': None, 'refNode': refNode}

    for proxy in proxyManagers:
        connection = cmds.connectionInfo(proxy + '.activeProxy', destinationFromSource=True)
        activeProxy = cmds.listConnections(connection, source=False)[0]
        namespace = cmds.referenceQuery(activeProxy, parentNamespace=True)[0]
        refNode = cmds.referenceQuery(activeProxy, referenceNode=True)
        result[namespace] = {'proxyManager': proxy, 'refNode': refNode}

    for ref in result:
        if loadState:
            isLoaded = cmds.referenceQuery(result[ref]['refNode'], isLoaded=True)
            result[ref]['isLoaded'] = isLoaded
        if nodesInRef:
            nodes = cmds.referenceQuery(result[ref]['refNode'], nodes=True, dagPath=True)
            result[ref]['nodesInRef'] = nodes
    return result
示例#8
0
def unloadReference( rfn ):
    #Get reference node.
    result = []
    if cmds.nodeType( rfn ) == "reference":
        rfn = rfn
    elif os.path.isfile( rfn ):
        rfn = cmds.referenceQuery( rfn, rfn=True )
    else:
        print "%s is not reference" % rfn
        return None
    relatives = referenceRelatives( rfn, onlyLoaded=True, parents=False )
    if cmds.referenceQuery( rfn, isLoaded=True ):
        if relatives:
            for i in range( len( relatives )-1, -1, -1 ):
                parent = cmds.referenceQuery( relatives[i], parent=True, filename=True )
                parent = parent and parent or "untitled"
                pm = cmds.listConnections( relatives[i], type="proxyManager" )
                if pm:
                    mcache = cmds.listConnections( "%s.proxyList" % pm[0], type="reference" )
                else:
                    mcache = [ relatives[i] ]
                for n in range( 0, len( mcache )):
                    if mcache[n] not in result:
                        result.append( mcache[n] )
                        pcache = cmds.referenceQuery( mcache[n], parent=True, filename=True )
                        pcache = pcache and pcache or "untitled"
                        if parent != pcache:
                            print "//Warning:\n//\treference is not valid:\n//\t{0} has parent {1}\n//\t{2} has parent {3}\n//\tplease check reference nodes connections.\n".format( relatives[i], parent, mcache[n], pcache )
                        if cmds.referenceQuery( mcache[n], isLoaded=True ):
                            print "unload reference: %s" % mcache[n]
                            cmds.file( unloadReference=mcache[n] )
    return result
示例#9
0
	def _modifiedAttrs(self):
		""" Returns a dictionary of modifications made to this referenced model.
		
		For referneced models return info describing the modifications made by the referencing
		system.
		"""
		modified = {}
		if self.isReferenced():
			fullName = self.path()
			refNode = cmds.referenceQuery(fullName, referenceNode=True)
			# Build the setAttr pattern
			pattern = r'setAttr {node}.(?P<attr>[^ ]+)'.format(node = fullName.replace('|', r'\|'))
			setAttrRegex = re.compile(pattern)
			# TODO: Add patterns for other mel commands like addAttr, etc
			for s in cmds.referenceQuery(refNode, editStrings=True):
				# Process setAttr
				match = setAttrRegex.match(s)
				if match:
					key = match.groupdict()['attr']
					if s.endswith('"'):
						# Found a string. Note, this does not include escaped quotes.
						openingQuote = s[::-1].find('"', 1)
						value = s[-openingQuote:-1]
					else:
						# its not a string
						value = s.split(' ')[-1]
					modified.setdefault(key, {}).setdefault('setAttr', {}).update(value=value, command=s)
		return modified
 def do(self, *args):
     try:
         sel = mc.ls(sl=1)
         sum = 0.0
         sum = len(sel)
         amount = 0.0
         for item in sel:
             mc.progressWindow(
                 title="Removing References", progress=amount, status="Removing: 0%", isInterruptable=True
             )
             if mc.progressWindow(query=True, isCancelled=True):
                 break
             if mc.progressWindow(query=True, progress=True) >= 100:
                 break
             RN = mc.referenceQuery(item, referenceNode=1)
             Nodes = mc.referenceQuery(RN, referenceNode=True, topReference=True)
             referenceFile = mc.referenceQuery(Nodes, f=1)
             reLoaded = mc.referenceQuery(referenceFile, il=True)
             if reLoaded == 1:
                 mc.file(referenceFile, unloadReference=1)
             amount = float((sel.index(item) + 1)) / float(len(sel)) * 100.0
             mc.progressWindow(edit=True, progress=amount, status=("Removing: " + ` amount ` + "%"))
             # mc.pause( seconds=1 )
         mc.progressWindow(endProgress=1)
     except:
         pass
示例#11
0
def listReferenceEdits( rfn ):
    """
    List all edits for current reference node.
    """
    result = []
    successfull = []
    if cmds.nodeType( rfn ) == "reference":
        rfn = rfn
    else:
        rfn = cmds.referenceQuery( rfn, rfn=True ) 
    edits = cmds.referenceQuery( rfn, failedEdits=True, successfulEdits=True, editStrings=True )
    if edits:
        edits = [ "".join( [ m_part for m_part in re.split( "\|:[A-z0-9:]+", edits[i] ) if m_part != "" ] ) for i in range( 0, len( edits )) ]
        m_content = cmds.ls( cmds.referenceQuery( rfn, nodes=True, dagPath=True ), long=True )
        for c in range( 0, len( m_content )):
            m_levels = listReferenceLevels( m_content[c] )
            for l in range( 0, len( m_levels )):
                m_expr = re.compile( "(\A|\s|\||\")+([A-z0-9_|]+|){0}(\Z|\s|\$|\"|\.)+".format( "(\||)".join( m_levels[l][0].split( "|" ))))
                for e in range( 0, len( edits )):
                    if edits[e] not in successfull:
                        if m_expr.findall( edits[e] ):
                            m_temp = [ rfn, m_content[c], m_levels[l][-1], m_levels[l][0], edits[e].split( " " )[0], edits[e] ]
                            result.append( m_temp )
                            successfull.append( edits[e] )
        for e in range( 0, len( edits )):
            if edits[e] not in successfull:
                m_temp = [ rfn, "unknown", "unknown", "unknown", edits[e].split( " " )[0], edits[e] ]
                result.append( m_temp )
    return result
 def deformCharacterShapeSel(self, value):
     RN = mc.referenceQuery(self.core.skCharacter[int(value)-1], referenceNode=1)
     Nodes = mc.referenceQuery(RN, nodes=1)
     self.characterdeformShape = []
     self.allCharacterRightdeformShape = []
     for item in Nodes:
         if self.nodeTypeSelf(item) in self.shapeType:
             self.characterdeformShape.append(item)
     for each in self.characterdeformShape:
         itemP = mc.listRelatives(each, p=1)[0]
         itemPP = mc.listRelatives(itemP, p=1)
         if itemPP != None and mc.getAttr('%s.v'%itemP) != 0 and mc.getAttr('%s.v'%itemPP[0]) != 0:
             self.allCharacterRightdeformShape.append(each)
             self.allCharacterRightdeformShape.reverse()
     for item in self.allCharacterRightdeformShape:
         if mc.filterExpand( item, sm=(10,12)) == None:
             self.allCharacterRightdeformShape.remove(item)
     for item in self.allCharacterRightdeformShape:
         if item.endswith('Orig') == True:
             self.allCharacterRightdeformShape.remove(item)
     for item in self.allCharacterRightdeformShape:
         if item.endswith('Orig') == True:
             self.allCharacterRightdeformShape.remove(item)
     for item in self.allCharacterRightdeformShape:
         if item.endswith('Orig') == True:
             self.allCharacterRightdeformShape.remove(item)
     for item in self.allCharacterRightdeformShape:
         if item.endswith('Orig') == True:
             self.allCharacterRightdeformShape.remove(item)
     for item in self.allCharacterRightdeformShape:
         if item.endswith('Orig') == True:
             self.allCharacterRightdeformShape.remove(item)
     return self.allCharacterRightdeformShape
示例#13
0
	def exportShaders(self):
		"""export custom shaders from scene, ex: shaders for masks etc..."""
		lays = rlayer.renderlayers()
		finalExport = []
		for l in lays:
			if l.name == 'defaultRenderLayer':
				continue
			if l.overridedShader:
				finalExport.append( l.overridedShader )
			else:
				if l.overridesWithConnections[1]:
					finalExport.extend( l.overridesWithConnections[1] )
		if finalExport:
			shadersToExport = []
			for i in finalExport:
				if mc.referenceQuery( i, inr = True ) or i in shadersToExport: #is a referenced node
					continue
				if mc.referenceQuery( i.a.surfaceShader.input, inr = True ): #check if shader is a reference
					continue
				if i.a.displacementShader.input:
					if mc.referenceQuery( i.a.displacementShader.input, inr = True ): #check if displacement is a reference
						continue
				shadersToExport.append( i )
			mc.select( shadersToExport, r = 1, ne = 1 )
			mc.file( self.shaderPath.path, op = "v=0", typ = "mayaAscii", pr = 1, es = 1 )
示例#14
0
 def defineAsset(self):
     self.assetType, self.topGrp, self.astRes = None, None, None
     self.refObjs = []
     if not mc.referenceQuery(self.refNode,il=1):
         utils.msgWin("Warning", "Reference not loaded for %s"%self.refNode, self.silent)
         self.refLoaded = False
     else:
         self.refLoaded = True
     self.assetPath = mc.referenceQuery(self.refNode, f = True, wcn = True)
     self.assetPathCopyNum = mc.referenceQuery(self.refNode, f = True, wcn = False)
     self.namespace = mc.file(self.assetPathCopyNum, q = 1, ns = 1)
     if "/char/" in self.assetPath: self.assetType = "char" 
     if "/prop/" in self.assetPath: self.assetType = "prop"
     if "/sets/" in self.assetPath: self.assetType = "sets"
     if not self.assetType:
         utils.msgWin("Error", "Error identifying asset type from asset path for %s"%self.refNode, self.silent)
         self.validAsset = False
     if self.refLoaded:
         self.refObjs = mc.referenceQuery(self.refNode,n=1)
         if not self.refObjs:
             utils.msgWin("Error", "Couldn't find any referenced objects", self.silent)
             self.validAsset = False
         self.topGrp = self.refObjs[0]
         if self.assetType == "prop":
             topGrpAttrs = mc.listAttr(self.topGrp,ud=1)
             if topGrpAttrs:
                 if ('Elements' in topGrpAttrs):
                     self.assetType = 'elms'
         self.astRes = str(utils.findObjRes(self.topGrp))
示例#15
0
def buildScene(cameraFile, envFile, charFile):
    '''
    Build the final lighting scene file.
    :param cameraFile: Camera alembic file to import
    :param envFile:  Published layout env file to reference
    :param charFile: Baked char file to reference
    :return:
    '''
    if isValidFile(envFile):
        try:
            # Check if env file is already referenced.
            cmds.referenceQuery(envFile, filename=True)
        except RuntimeError:
            cmds.file(envFile, r=True)

    if isValidFile(charFile):
        try:
            # Check if env file is already referenced.
            cmds.referenceQuery(charFile, filename=True)
        except RuntimeError:
            cmds.file(charFile, r=True)

    if isValidFile(cameraFile):
        # Check if camera exists in scene
        cameraNodes = cmds.ls('renderCam')
        if len(cameraNodes) == 1:
            # Camara exists, delete and re-import alembic
            cameraNode = cameraNodes[0]
            cmds.delete(cameraNode)
        cmds.AbcImport(cameraFile, mode='import')

    cmds.file(save=True, type='mayaBinary', force=True)
    def clearHeadPart(self, *args):

        #find the current character
        try:
            character = cmds.optionMenu(self.widgets["characterList"], q = True, v = True)

        except:
            cmds.warning("No valid character selected")

        #find any body part references
        refs = cmds.ls(type = "reference")
        headPartRefs = []
        for ref in refs:
            namespace = cmds.referenceQuery(ref, namespace = True)

            if namespace.find("_headPart") != -1:
                headPartRefs.append([ref, namespace])


        #find out which, if any, are tied to this character and remove
        for ref in headPartRefs:
            joint = ref[1] + ":root"
            constraint = cmds.listConnections(joint, type = "parentConstraint")[0]
            target = cmds.listConnections(constraint + ".target")[0].partition(":")[0]

            if target == character:
                filename = cmds.referenceQuery(ref[0], filename = True)
                cmds.file(filename, rr = True)

            #unhide the original geometry
            if cmds.objExists(character + ":Geo_Layer"):
                cmds.setAttr(character + ":Geo_Layer.v", 1)
示例#17
0
def dupReferenceForSelectedObjects():
	"""
	Duplicate reference of the selected objects, only one time, and copy their edits
	"""
	allreadyDup = []
	for a in mc.ls( sl = True ):
		ap = mc.referenceQuery( a, referenceNode=True, topReference=True )
		if any( ap == r for r in allreadyDup ):
			print 'skipping',a
			continue
		allreadyDup.append( ap )
		edits = mc.referenceQuery( ap , editStrings = True )
		mc.select( a )
		try:
			mm.eval( 'duplicateReference 0 ""' )
		except:
			print 'maya de mierda'
		baseOldName = edits[0][edits[0].find( '|' )+1:edits[0].find( ':' )]
		baseNewName = mc.ls( sl = True )[0].split( ':' )[0]
		for e in edits:
			print '"""""""'
			print e
			print baseOldName,baseNewName
			try:
				mm.eval( e.replace( baseOldName, baseNewName, 1 ) )
			except:
				continue
示例#18
0
def addReferences():
    cmds.select("dsMetaData")
    shotList = cmds.ls(type = "shot")
    refList = cmds.ls(rf=True)
    for shot in shotList:
        
        """ skips namespaces"""
        if re.search(":",shot):
            sSplit = shot.split(":")
            shot = sSplit[-1]
        
        for ref in refList:
            if cmds.referenceQuery(ref,n=True,dp=True) != None:
                refNs = cmds.referenceQuery(ref,ns=True,shn=True)
                refN = cmds.referenceQuery(ref,f=True,shn=True)
                
                print refNs
                print refN
                
                if not cmds.objExists("dsMetaData." + str(shot) + "_" + refNs):
                    cmds.addAttr(ln= str(shot) + "_" + refNs, at="message", h=False,r=True)
                    cmds.addAttr(ln= str(shot) + "_" + refNs + "_viz", at='bool', h=False,r=True)
                    cmds.addAttr(ln= str(shot) + "_" + refNs + "_assetID",at="long",h=False,r=True)
                    cmds.addAttr(ln= str(shot) + "_" + refNs + "_version",dt="string",h=False,r=True)
                    connectReferences(str(shot)+ "_" + refNs,refNs,refN)
	def fixNode(self, nodeToFix, invert=False):
		print ("\n" + nodeToFix)

		# gets all attributes that need to be fixed
		attrs = cmds.listAttr(nodeToFix, st=["hubElement"])
		for attr in attrs:
			print ("Found Attribute -> '" + attr + "'")
			
			# check if the attribute is empty and if yes, fixs it
			val = cmds.getAttr(nodeToFix + "." + attr)

			condition = (not val or val != "neverBirdA")
			if invert: condition = (val == "neverBirdA")

			if condition:
				msg = ("Attribute '" + attr + "' is empty or incorrect.")
				if invert: msg = ("Attribute '" + attr + "' is OK.")
				print msg

				# if the attribute is locked, unlocks it first
				isLocked = cmds.getAttr((nodeToFix + "." + attr), lock=True)
				if isLocked:
					print ("Attribute '" + attr + "' is locked. Unlocking it.")
					isReferenced = cmds.referenceQuery((nodeToFix + "." + attr), isNodeReferenced=True)
					if isReferenced:
						try:
							cmds.setAttr((nodeToFix + "." + attr), lock=False)
						except:
							print ("Attribute '" + attr + "' could not be unlocked, it is referenced.")
					else:
						cmds.setAttr((nodeToFix + "." + attr), lock=False)

				# if the attribute is now unlocked, fixes the value
				isLocked = cmds.getAttr((nodeToFix + "." + attr), lock=True)
				if not isLocked:
					msg = ("Attribute '" + attr + "'. Setting value to 'neverBirdA'")
					if invert: msg = ("Attribute '" + attr + "'. Setting value to 'empty string'.")
					print msg

					newVal = "neverBirdA"
					if invert: newVal = ""
					
					print (nodeToFix + "." + attr)
					print (cmds.getAttr((nodeToFix + "." + attr), settable=True))

					cmds.setAttr((nodeToFix + "." + attr), newVal, type="string")
					
					isReferenced = cmds.referenceQuery((nodeToFix + "." + attr), isNodeReferenced=True)
					if not isReferenced:
						print ("Attribute '" + attr + "'. Locking again")
						cmds.setAttr((nodeToFix + "." + attr), lock=True)
					else:
						print ("Attribute '" + attr + "'. Is referenced, unable to locl again.")
				else:
					print ("Attribute '" + attr + "' could not be unlocked.")

			else:
				msg = ("Attribute '" + attr + "' is OK -> '" + val + "'")
				if invert: msg = ("Attribute '" + attr + "' is not OK.")
				print msg
示例#20
0
	def _removeNativeModels(self, models):
		""" Deletes provided native models.
			:param models: list of native models
			:return: <bool> success
		"""
		ret = True
		for model in models:
			nameInfo = cross3d.SceneWrapper._namespace(model)
			fullName = cross3d.SceneWrapper._mObjName(model)
			if cmds.referenceQuery(fullName, isNodeReferenced=True):
				# The model is referenced and we need to unload it.
				refNode = cmds.referenceQuery(fullName, referenceNode=True)
				filename = cmds.referenceQuery(refNode, filename=True)
				# If all nodes in the namespace are referenced, the namespace will be removed, otherwise
				# the namespace will still exist and contain all of those unreferenced nodes.
				cmds.file(filename, removeReference=True)
				# Remove nodes that were parented to referneced nodes
				leftovers = self.objects(wildcard='{refNode}fosterParent*'.format(refNode=refNode))
				if leftovers:
					self.removeObjects(leftovers)
			# Local node processing: check for unreferenced items in the namespace and remove them.
			namespace = nameInfo['namespace']
			if cmds.namespace(exists=namespace):
				cmds.namespace(removeNamespace=namespace, deleteNamespaceContent=True)
			if cmds.namespace(exists=namespace):
				print 'The namespace {ns} still exists the model {model} was not entirely removed.'.format(namespace, model=fullName)
				ret = False
		return ret
示例#21
0
    def export_mesh(self, transform, shape, awd_ctr):
        try:
            mtx = mc.xform(transform, q=True, m=True)
        except:
            print('skipping invalid %s' % transform)
 
        tf_name = self.get_name(transform)
        sh_name = self.get_name(shape)

        tf_is_ref = mc.referenceQuery(transform, inr=True)
        sh_is_ref = mc.referenceQuery(shape, inr=True)
        if (tf_is_ref or sh_is_ref) and self.replace_exrefs:
            # This is an external reference, and it should be
            # replaced with an empty container in the AWD file
            ctr = AWDContainer(name=tf_name, transform=AWDMatrix3x4(mtx))
            self.set_attributes(transform, ctr)
            self.block_cache.add(transform, ctr)
            if awd_ctr is not None:
                awd_ctr.add_child(ctr)
            else:
                self.awd.add_scene_block(ctr)

        else:
            md = self.block_cache.get(sh_name)
            if md is None:
                print('Creating mesh data %s' % sh_name)
                md = AWDTriGeom(sh_name)
                md.bind_matrix = AWDMatrix3x4(mtx)
                self.export_mesh_data(md, shape)
                self.awd.add_tri_geom(md)
                self.block_cache.add(sh_name, md)
 
            inst = AWDMeshInst(md, tf_name, self.mtx_list2awd(mtx))
 
            self.set_attributes(transform, inst)

            # Look for materials
            if self.include_materials:
                self.export_materials(transform, inst)
 
            self.block_cache.add(transform, inst)
            if awd_ctr is not None:
                awd_ctr.add_child(inst)
            else:
                self.awd.add_scene_block(inst)
 
            if self.include_skeletons:
                history = mc.listHistory(transform)
                clusters = mc.ls(history, type='skinCluster')
                if len(clusters) > 0:
                    #TODO: Deal with multiple clusters?
                    sc = clusters[0]
 
                    influences = mc.skinCluster(sc, q=True, inf=True)
                    if len(influences) > 0:
                        skel_path = self.get_skeleton_root(influences[0])
 
                        if self.block_cache.get(skel_path) is None:
                            self.export_skeleton(skel_path)
示例#22
0
def listCurrentProxy(sel=""):
    '''List the current proxy, the selection belongs to'''
    if str(sel) == "":
        sel = cmds.ls(sl=True, hd=1, type="transform")
    if not str(sel) == "":
        proxfile = cmds.referenceQuery(sel ,filename=True )
        prox = cmds.referenceQuery( proxfile, referenceNode=True )
    return prox
示例#23
0
def getSelectReferenceFile():
    selectObjs = mc.ls(sl = True)
    result = []
    for obj in selectObjs:
        if mc.referenceQuery(obj, isNodeReferenced = True):
            if not result.count(mc.referenceQuery(obj, filename = True)):
                result.append( mc.referenceQuery(obj, filename = True))
    return result
示例#24
0
 def deformShapeSel(self, value):
     RN = mc.referenceQuery(self.core.allPropPath[int(value)-1], referenceNode=1)
     Nodes = mc.referenceQuery(RN, nodes=1)
     self.propdeformShape = []
     for item in Nodes:
         if mc.nodeType(item) in self.shapeType:
             self.propdeformShape.append(item)
     return self.propdeformShape
示例#25
0
 def deformCharacterShapeSel(self, value):
     RN = mc.referenceQuery(self.core.skCharacter[int(value)-1], referenceNode=1)
     Nodes = mc.referenceQuery(RN, nodes=1)
     self.characterdeformShape = []
     for item in Nodes:
         if mc.nodeType(item) in self.shapeType:
             self.characterdeformShape.append(item)
     return self.characterdeformShape
示例#26
0
def export(ref_node):
    """
    """
    data = {}
    data['filename'] = cmds.referenceQuery(ref_node, filename=True)
    data['namespace'] = cmds.referenceQuery(ref_node, namespace=True)
    data['parents'] = get_parents(data['namespace'])
    return data
    def process(self, context):
        from maya import cmds

        self.log.info("Collecting references..")

        # Get only valid top level reference nodes
        # This makes it easier than using `cmds.ls` since it lists only
        # top level references, and skips sharedReferenceNode.
        ref_files = cmds.file(q=1, reference=1)
        ref_nodes = [cmds.file(x, q=1, referenceNode=True) for x in ref_files]

        references = dict()
        for reference in ref_nodes:

            # Ensure only top-level references
            assert cmds.referenceQuery(reference,
                                       referenceNode=True,
                                       topReference=True) == reference

            filename = cmds.referenceQuery(
                reference,
                filename=True,
                withoutCopyNumber=True  # Exclude suffix {1}
                ).replace("\\", "/")

            if filename in references:
                continue

            references[filename] = {
                "node": reference,
                "filename": filename
            }

            self.log.info("Collecting %s" % references[filename])

        for instance in context:

            object_set = instance.data['objSetName']

            if not cmds.objExists(object_set):
                self.log.info("{0} is not a Maya node".format(object_set))
                continue

            userattrs = dict()
            for attr in cmds.listAttr(object_set, userDefined=True):
                try:
                    value = cmds.getAttr(object_set + "." + attr)
                except RuntimeError:
                    continue

                userattrs[attr] = value

            metadata = instance.data("metadata")
            assert metadata
            metadata["references"] = references.values()
            metadata["userattrs"] = userattrs
示例#28
0
def listReferences():
    """Returns a dictionary with the path to the ref, its refNode, the nodes contained in the ref, and if the ref is loaded or not"""
    references = cmds.file(query=True, reference=True)
    referencesDict = dict()
    for ref in references:
        refNode = cmds.file(ref, query=True, referenceNode=True)
        isLoaded = cmds.referenceQuery(refNode, isLoaded=True)
        nodesInRef = cmds.referenceQuery(refNode, nodes=True)
        referencesDict[ref] = [refNode, nodesInRef, isLoaded]
    return referencesDict
示例#29
0
def populateReferenceList():
	references = cmds.ls(et='reference')
	#del references[len(references)-1]
	#print references
	for ref in references:
		refFileName  = cmds.referenceQuery(ref ,filename = True)
		print refFileName  
		if not(cmds.file(rfn=ref,q=True,dr=True)):
			bla = cmds.referenceQuery(ref ,n = True)
			cmds.textScrollList('ceRefList',e=True,append=[bla[0]])
示例#30
0
def removeSelected():
	"""unload selected reference"""
	objs = mn.ls( sl = True )
	for obj in objs:
		try:
			referenceNode = mc.referenceQuery( obj.name, rfn = True )
			path = mc.referenceQuery( obj.name, f = True )
			mc.file( referenceNode  = referenceNode, removeReference = True  )
		except:
			continue
示例#31
0
    def getReferences(selected=False):
        ''' returns a list of maya references from
        scene selection in form of objects '''
        selected_references = []
        sel = cmds.ls(sl=True) if selected else cmds.ls(type="reference")
        for item in sel:
            try:
                ref_node = cmds.referenceQuery(item, rfn=True)
                if ref_node not in selected_references:
                    selected_references.append(ref_node)
            except RuntimeError:
                pass

        return [MayaReference(r) for r in selected_references]
示例#32
0
    def get_tagged_node(self, ref):
        refNodes = cmds.referenceQuery(unicode(ref), nodes=True)
        rootNode = ls(refNodes[0])
        if rootNode[0].hasAttr("BYU_Alembic_Export_Flag"):
            taggedNode = rootNode[0]
        else:
            taggedNode = self.get_tagged_children(rootNode[0])

        if taggedNode == "":
            self.showNoTagFoundDialog(unicode(ref))
            return ""

        print taggedNode
        return taggedNode
    def get_invalid(instance):

        # Collect all referenced members
        references = defaultdict(set)
        relationships = instance.data["lookData"]["relationships"]
        for relationship in relationships.values():
            for member in relationship['members']:
                node = member["name"]

                if cmds.referenceQuery(node, isNodeReferenced=True):
                    ref = cmds.referenceQuery(node, referenceNode=True)
                    references[ref].add(node)

        # Validate whether any has changes to 'cbId' attribute
        invalid = list()
        for ref, nodes in references.items():
            edits = cmds.referenceQuery(editAttrs=True,
                                        editNodes=True,
                                        showDagPath=True,
                                        showNamespace=True,
                                        onReferenceNode=ref)
            for edit in edits:

                # Ensure it is an attribute ending with .cbId
                # thus also ignore just node edits (like parenting)
                if not edit.endswith(".cbId"):
                    continue

                # Ensure the attribute is 'cbId' (and not a nested attribute)
                node, attr = edit.split(".", 1)
                if attr != "cbId":
                    continue

                if node in nodes:
                    invalid.append(node)

        return invalid
示例#34
0
    def create_breakdown(self, shot_name, requiered_nodes):
        """
        """

        shot_entity = self.ensure_shot_entity(shot_name)

        assets = []

        for node in requiered_nodes:
            node_type = cmds.nodeType(node)

            if node_type == 'reference':
                file_path = cmds.referenceQuery(node, filename=True)
                namespace = cmds.referenceQuery(node, namespace=True).replace(
                    ':', '')

                asset_entity = self.ensure_breakdown_entity(
                    shot_entity, file_path, namespace)
                if asset_entity:
                    assets.append(asset_entity)

            if node_type == 'transform':
                # this one gets tricky, but we in theory now that its a gpuCache
                # Lets first get the children and verify its indeed a gpuCache
                children = cmds.listRelatives(node, children=True)
                if children and cmds.nodeType(children[0]) == 'gpuCache':
                    child = children[0]
                    file_path = cmds.getAttr("%s.cacheFileName" % child)

                    asset_entity = self.ensure_breakdown_entity(
                        shot_entity, file_path, None)
                    if asset_entity:
                        assets.append(asset_entity)

        # finally just update the assets shot field
        data = {'assets': assets}
        self.shotgun.update('Shot', shot_entity['id'], data)
示例#35
0
def cleanREF_SG():
    print('Running %s...' % 'cleanREF_SG')
    allRef = mc.ls(references=True)

    #remove unloaded reference from the list
    for ref in allRef:
        if not mc.referenceQuery(ref, isLoaded=1):
            allRef.remove(ref)
            print('****COULDN\'T FIND: %s' % ref)
    print('Found:')
    for ref in allRef:
        print('    %s' % ref)

    #unloading all references
    print('\nUnloading references...')
    for ref in allRef:
        mc.file(unloadReference=ref)

    #remove Shading group reference edits
    print('Removing Shading Group reference edits...')
    for ref in allRef:
        sgEdits = [
            sge for sge in mc.referenceQuery(ref, editNodes=True)
            if 'SG' in sge
        ]
        for sge in sgEdits:
            mc.referenceEdit(sge + '.dagSetMembers',
                             failedEdits=True,
                             successfulEdits=True,
                             removeEdits=True)

    #reload reference
    print('Reloading...')
    for ref in allRef:
        print('    %s' % ref)
        mc.file(loadReference=ref)
    print('')
def _maya_find_additional_session_dependencies():
    """
    Find additional dependencies from the session
    """

    # default implementation looks for references and
    # textures (file nodes) and returns any paths that
    # match a template defined in the configuration
    ref_paths = set()

    # first let's look at maya references
    ref_nodes = cmds.ls(references=True)
    for ref_node in ref_nodes:
        # get the path:
        ref_path = cmds.referenceQuery(ref_node, filename=True)
        # make it platform dependent
        # (maya uses C:/style/paths)
        ref_path = ref_path.replace("/", os.path.sep)
        if ref_path:
            ref_paths.add(ref_path)

    # now look at file texture nodes
    for file_node in cmds.ls(l=True, type="file"):
        # ensure this is actually part of this session and not referenced
        if cmds.referenceQuery(file_node, isNodeReferenced=True):
            # this is embedded in another reference, so don't include it in
            # the breakdown
            continue

        # get path and make it platform dependent
        # (maya uses C:/style/paths)
        texture_path = cmds.getAttr("%s.fileTextureName" % file_node).replace(
            "/", os.path.sep)
        if texture_path:
            ref_paths.add(texture_path)

    return list(ref_paths)
示例#37
0
文件: compat.py 项目: yazici/core
def remove(container):
    """Remove an existing `container` from Maya scene

    Deprecated; this functionality is replaced by `api.remove()`

    Arguments:
        container (avalon-core:container-1.0): Which container
            to remove from scene.

    """

    node = container["objectName"]

    # Assume asset has been referenced
    reference_node = next((node for node in cmds.sets(node, query=True)
                          if cmds.nodeType(node) == "reference"), None)

    assert reference_node, ("Imported container not supported; "
                            "container must be referenced.")

    log.info("Removing '%s' from Maya.." % container["name"])

    namespace = cmds.referenceQuery(reference_node, namespace=True)
    fname = cmds.referenceQuery(reference_node, filename=True)
    cmds.file(fname, removeReference=True)

    try:
        cmds.delete(node)
    except ValueError:
        # Already implicitly deleted by Maya upon removing reference
        pass

    try:
        # If container is not automatically cleaned up by May (issue #118)
        cmds.namespace(removeNamespace=namespace, deleteNamespaceContent=True)
    except RuntimeError:
        pass
示例#38
0
    def execute(self, **kwargs):
        """
        Main hook entry point
        :returns:       A list of any items that were found to be published.  
                        Each item in the list should be a dictionary containing 
                        the following keys:
                        {
                            type:   String
                                    This should match a scene_item_type defined in
                                    one of the outputs in the configuration and is 
                                    used to determine the outputs that should be 
                                    published for the item
                                    
                            name:   String
                                    Name to use for the item in the UI
                            
                            description:    String
                                            Description of the item to use in the UI
                                            
                            selected:       Bool
                                            Initial selected state of item in the UI.  
                                            Items are selected by default.
                                            
                            required:       Bool
                                            Required state of item in the UI.  If True then
                                            item will not be deselectable.  Items are not
                                            required by default.
                                            
                            other_params:   Dictionary
                                            Optional dictionary that will be passed to the
                                            pre-publish and publish hooks
                        }
        """
        items = []
        # get the main scene:
        scene_name = cmds.file(query=True, sn=True)
        if not scene_name:
            raise TankError("Please Save your file before Publishing")

        scene_path = os.path.abspath(scene_name)
        name = os.path.basename(scene_path)

        # create the primary item - this will match the primary output 'scene_item_type':
        items.append({"type": "work_file", "name": name})
        for node in cmds.ls(type="file"):
            if not cmds.referenceQuery(node, isNodeReferenced=True):
                items.append({"type": "texture_file", "name": node})

        return items
示例#39
0
    def global_repair_func(self):
        item = QtWidgets.QTreeWidgetItemIterator(self.rfn_tree)
        while item.value():

            name_space = item.value().text(0)
            filename = item.value().text(1)
            temp_matrix = eval(item.value().text(2))

            rfn = cmds.file(filename, reference=True, namespace=name_space)
            _temp_namespace = cmds.referenceQuery(rfn, namespace=True)
            main_curve = "{}:{}".format(_temp_namespace, "Main")

            if cmds.objExists(main_curve):
                cmds.xform(main_curve, matrix=temp_matrix)
            item = item.__iadd__(1)
示例#40
0
def setMetaData(node, className, data, undoable=True, replace=False):
    """
    Set the meta data for the a meta class type on a node.

    The className must be a valid attribute name.

    Args:
        node (PyNode or str): The node on which to set data
        className (str): The data's meta class type name
        data (dict): The data to serialize and store on the node
        undoable (bool): When True, the operation will be undoable
        replace (bool): When True, will replace all data on the node
            with the new meta data. This uses setAllMetaData and can
            be much faster with large data sets.
    """
    if replace:
        setAllMetaData(node, {className: data}, undoable)
        return

    mfnnode = utils.getMFnDependencyNode(node)
    plug = _getOrCreateMetaDataPlug(mfnnode, undoable)
    _addMetaClassAttr(mfnnode, className, undoable)

    # update meta data
    refNode = None
    if cmds.referenceQuery(str(node), isNodeReferenced=True):
        refNode = cmds.referenceQuery(str(node), rfn=True)
    fullData = decodeMetaData(plug.asString(), refNode)
    fullData[className] = data
    newValue = encodeMetaData(fullData)

    if undoable:
        plugName = _getUniquePlugName(mfnnode, plug)
        cmds.setAttr(plugName, newValue, type='string')
    else:
        plug.setString(newValue)
示例#41
0
def get_camera(with_panel=None):
    all_cams = [cam for cam in mc.listCameras(p=1) if not mc.referenceQuery(cam, isNodeReferenced=True)]
    extra_cams = ['persp', 'left', 'right', 'top', 'side', 'bottom']
    if with_panel:
        try:
            current_cam = pm.PyNode(pm.modelPanel(pm.getPanel(wf=True), q=True, cam=True))
            return current_cam
        except RuntimeError:
            pass
    all_cam_transform = [str(cam) for cam in all_cams if str(cam) not in extra_cams]
    # print all_cam_transform
    if all_cam_transform:
        return all_cam_transform
    else:
        return ["persp"]
示例#42
0
def reference_in_scene(scene):

    scene_references = cmds.ls(references=True)

    for node in scene_references:

        reference_file = cmds.referenceQuery(node, filename=True)

        if os.path.normpath(scene) == os.path.normpath(reference_file):

            print node, 'Already exists in the scene'

            return True

    return False
示例#43
0
 def formatAudioNode_to_Path(self):
     '''
     rename the AudioNode so it ties to the wav name
     '''
     try:
         cmds.rename(
             self.audioNode,
             r9Core.nodeNameStrip(
                 os.path.splitext(os.path.basename(self.path))[0]))
     except:
         if cmds.referenceQuery(self.audioNode, inr=True):
             log.info('failed to Rename Referenced Audio Node : %s' %
                      self.audioNode)
         else:
             log.info('failed to Rename Audio node : %s' % self.audioNode)
示例#44
0
 def renameReferenceh_AnimChangeTomc_Anim(self):
     ReferenceFiles = self.ChangeReferenceFiles()
     for ReferenceFile in ReferenceFiles:
         if "_h_msAnim" in ReferenceFile:
             referFile = mc.referenceQuery(ReferenceFile,
                                           withoutCopyNumber=True,
                                           shortName=True,
                                           filename=True)
             pathFileName = os.path.dirname(ReferenceFile) + "/" + referFile
             fileName = pathFileName.replace("_h_msAnim", "_mc_msAnim")
             if os.path.isfile(fileName):
                 referenceNode = mc.file(ReferenceFile,
                                         q=True,
                                         referenceNode=True)
                 mc.file(fileName, loadReference=referenceNode)
示例#45
0
def _filteredReferenceNode():
  newRefNodes = []
  refNodes = cmds.ls(type="reference")
  for refNode in refNodes:
    if re.match(refNode, "\w+:sharedReferenceNode"):
      continue
    if re.match(refNode, "sharedReferenceNode"):
      continue
    if re.match(refNode, "_UNKNOWN_REF_NODE_"):
      continue

    newRefNode = cmds.referenceQuery(refNode, referenceNode=True)
    newRefNodes.append(newRefNode)

  return newRefNodes
示例#46
0
def getReferenceNode(node):
	'''
	Get the reference node associated with the given referenced object
	@param refNode: Reference node to query
	@type refNode: str
	'''
	# Check Referenced Node
	if not isReferenced(node):
		raise Exception('Object "'+node+'" is not a referenced node!')
	
	# Get Reference Node
	refNode = mc.referenceQuery(node,referenceNode=True)
	
	# Retrun Result
	return refNode
示例#47
0
    def _get_relevant_objects_from_ref_node(self, src_mtl_mapping, ref_node):

        child_nodes = cmds.referenceQuery(ref_node, nodes=True)

        relevant_nodes = list()
        # we need the object that matches objects from src_mtl_mapping
        for child in child_nodes:
            ns_stripped_object_name = pm.PyNode(child).stripNamespace()

            if ns_stripped_object_name in src_mtl_mapping:
                relevant_nodes.append(child)
            # if not cmds.listRelatives(child, parent=True):
            #     return child

        return relevant_nodes
示例#48
0
def RNfromSelection():
    '''This will select every master reference node for selected geometries that has a controller'''
    # 1. controllers from selection
    ctrls = []
    for n in cmds.ls(selection=True, referencedNodes=True):
        if not 'ctrl' in n:
            pass
        else:
            ctrls.append(n)
    # 2. master reference node from ctrl
    rn = []
    for ctrl in ctrls:
        n = cmds.referenceQuery(ctrl, referenceNode=True, p=True)
        rn.append(n)
    return rn
示例#49
0
def openReference(rfn):
    """
    Open current reference node in new maya window.
    """
    rfn = type(rfn) is list and rfn or [rfn]
    for i in range(0, len(rfn)):
        if cmds.nodeType(rfn[i]) == "reference":
            node = rfn
        elif os.path.isfile(rfn):
            node = cmds.referenceQuery(rfn[i], rfn=True)
        else:
            print "%s is not reference" % rfn[i]
            return None
        maya = sys.executable
        filename = cmds.referenceQuery(node, filename=True)
        expression = re.compile(
            "^(/Server-3d/Project)|(/mnt/server-3d)|(P:)|(/home/.*/Project)|(D:/Work/Project)|(//Server-3d/Project)",
            re.IGNORECASE)
        filename = expression.sub("//Server-3d/Project", filename)
        if filename:
            filename = filename.split("{")[0]
            m_command = "python(\"import chekProject; chekProject.setMayaProject({0}); import melnik_setup; melnik_setup.updateScene();import maya.cmds as cmds; cmds.file({0}, force=True, open=True )\")".format(
                "'%s'" % filename)
            subprocess.Popen([maya, "-command", m_command])
示例#50
0
 def renameReferenceFileNoTex(self):
     self.changeReferenceFiles()
     for ReferenceFile in self.allReference:
         if "_h_msNoTex" in ReferenceFile:
             referFile = mc.referenceQuery(ReferenceFile,
                                           withoutCopyNumber=True,
                                           shortName=True,
                                           filename=True)
             pathFileName = os.path.dirname(ReferenceFile) + "/" + referFile
             fileName = pathFileName.replace("_h_msNoTex", "_h_msAnim")
             if os.path.isfile(fileName):
                 referenceNode = mc.file(ReferenceFile,
                                         q=True,
                                         referenceNode=True)
                 mc.file(fileName, loadReference=referenceNode)
示例#51
0
def getNodesInReferenceFromFileName(ref_file):
    """   """
    if not os.path.exists(ref_file):
        logging.error(u"file not exists:%s"%ref_file)
        return None

    if not isFileReferenced(ref_file):
        logging.error("File Not referenced:%s"%ref_file)
        return None

    node_list = cmds.referenceQuery(ref_file, nodes=True)
    if not node_list:
        logging.warning("reference file has no nodes:%s"%ref_file)

    return node_list
示例#52
0
def getAllReferencedFileNames():
    """
    get all file name
    """
    ref_node_list = cmds.ls(type="reference")
    if not ref_node_list:
        logging.warning("No file referenced in current scene")
        return None

    ref_file_list = []
    for ref_node in ref_node_list:
        ref_file = cmds.referenceQuery(ref_node, filename=True)
        ref_file_list.append(ref_file)

    return ref_file_list
示例#53
0
def light():
    """ clear light

    """
    _lights = cmds.ls(type=cmds.listNodeTypes("light"))

    if _lights:
        for _light in _lights:
            try:
                #if cmds.objExists(_light):
                if cmds.referenceQuery(_light, isNodeReferenced=True) == False:
                    par = cmds.listRelatives(_light, p=True)
                    cmds.delete(par)
            except Exception as e:
                logger.warning(e)
示例#54
0
    def remove(self, container):
        """Remove an existing `container` from Maya scene

        Arguments:
            container (avalon-core:container-1.0): Which container
                to remove from scene.

        """
        from maya import cmds

        node = container["objectName"]

        # Get reference node from container members
        members = cmds.sets(node, query=True, nodesOnly=True)
        reference_node = self._get_reference_node(members)

        self.log.info("Removing '%s' from Maya.." % container["name"])

        namespace = cmds.referenceQuery(reference_node, namespace=True)
        fname = cmds.referenceQuery(reference_node, filename=True)
        cmds.file(fname, removeReference=True)

        try:
            cmds.delete(node)
        except ValueError:
            # Already implicitly deleted by Maya upon removing reference
            pass

        try:
            # If container is not automatically cleaned up by May (issue #118)
            cmds.namespace(removeNamespace=namespace,
                           deleteNamespaceContent=True)
        except RuntimeError:
            pass

        return True
示例#55
0
def _get_yeti_attr(nodeType, attrName, ignoreReference=True):
    pg_dict = {}
    _pgyetinodes = cmds.ls(type="pgYetiMaya")
    if _pgyetinodes:
        for _i in _pgyetinodes:
            if ignoreReference and cmds.referenceQuery(_i, inr=1):
                continue
            selnodes = cmds.pgYetiGraph(_i, listNodes=1, type=nodeType)
            for selnode in selnodes:
                attr_v = cmds.pgYetiGraph(_i,
                                          node=selnode,
                                          param=attrName,
                                          getParamValue=1)  # 查询param命令lsp = 1
                pg_dict["%s/%s" % (_i, selnode)] = attr_v
    return pg_dict
示例#56
0
def find(output_path=None, write=False):
    if not output_path:
        output_path = os.path.join(
            tempfile.gettempdir(), 'studio_maya_reference_data.txt')
    if os.path.isfile(output_path):
        try:
            os.chmod(output_path, 0777)
        except:
            pass
        try:
            os.remove(output_path)
        except Exception as error:
            print str(error)
    references = cmds.file(q=True, r=True)
    data = {}
    print "\nhttp://www.subins-toolkits.com", '\n', '-' * 41         
    print '\nReference informations'    
    for index, reference in enumerate(references):
        namespace = cmds.file(reference, q=True, ns=True).encode()
        source_path = cmds.referenceQuery(reference, filename=True, wcn=True)
        source_path = source_path.replace('\\', '/').encode()
        world_node = cmds.referenceQuery(reference, n=1)[0]
        current_data = {
            'source_path': source_path,
            'namespace': namespace,
            'top_dag_node': world_node
        }
        data.setdefault(index + 1, current_data)
        print index
        print '\tsource_path :', source_path
        print '\tnamespace :', namespace
        print '\tTop level dag object :', world_node, '\n'
    if write:
        with (open(output_path, 'w')) as content:
            content.write(json.dumps(data, indent=4))
    return data, output_path
示例#57
0
def _cleanupNamespace():
    '''
    find the reference, import it,
    finds the prefix of the reference and cleans up the namespace 
    '''
    for item in listCtrls():
        pre = str(listCtrls()[0])
        prefix = pre.rsplit(":")[0]

        print 'Cleaning up file : RIG is %s' % prefix
        ref = cmds.referenceQuery(item, filename=True)
        cmds.file(ref, importReference=True)
        cmds.namespace(mv=(prefix, ":"), force=True)
        cmds.namespace(rm=prefix)
        print "Cleaning up file : namespace deleted and cleaned up"
示例#58
0
文件: utils.py 项目: lazerdaze/lancer
def validateAnimationCurve(animationCurve):
    """
    Check if the parsed animation curve can be reduces. Set driven keyframes
    and referenced animation curves will be ignored.

    :param str animationCurve:
    :return: Validation state of the animation curve
    :rtype: bool
    """
    if cmds.listConnections("{}.input".format(animationCurve)):
        return False
    elif cmds.referenceQuery(animationCurve, isNodeReferenced=True):
        return False

    return True
示例#59
0
def getReferenceFile(node,withoutCopyNumber=True):
	'''
	Get the reference node associated with the given referenced object or reference node
	@param refNode: Reference node to query
	@type refNode: str
	'''
	# Check Reference/Referenced Node
	if not isReference(node) and not isReferenced(node):
		raise Exception('Object "'+node+'" is not a valid reference node or a node from a referenced file!')
	
	# Get Reference details
	refFile = mc.referenceQuery(node,filename=True,wcn=withoutCopyNumber)
	
	# Retrun Result
	return refFile
示例#60
0
def remove_ref():
    logger.info("Importing references ---------------------------------")

    try:
        mel.eval('RNdeleteUnused();')

        sorted_references = ns_sort(cmds.ls(type='reference'))

        for i in sorted_references:
            print i
            rFile = cmds.referenceQuery(i, f=True)
            cmds.file(rFile, importReference=True, mnr=True, f=True)
    except Exception, err:
        logger.info(err)
        logger.info("Import references failed")