Python maya.cmds.referenceQuery() Examples

The following are 9 code examples of maya.cmds.referenceQuery(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module maya.cmds , or try the search function .
Example #1
Source File: utils.py    From maya-keyframe-reduction with MIT License 7 votes vote down vote up
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


# ---------------------------------------------------------------------------- 
Example #2
Source File: compat.py    From core with MIT License 5 votes vote down vote up
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 
Example #3
Source File: mayascenemodel.py    From cross3d with MIT License 5 votes vote down vote up
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 
Example #4
Source File: mayascenemodel.py    From cross3d with MIT License 5 votes vote down vote up
def _referenceNodeName(self):
		filename = self.userProps().get('reference')
		if filename:
			return cmds.referenceQuery(filename, referenceNode=True)
		return None

# register the symbol 
Example #5
Source File: mayascene.py    From cross3d with MIT License 5 votes vote down vote up
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 
Example #6
Source File: ml_centerOfMass.py    From ml_tools with MIT License 5 votes vote down vote up
def meshesFromReference(control):
    '''
    Get meshes from the referenced file. This is faster and more accurate in most
    cases than traversing history, but only works if the rig is referenced.
    '''

    if not mc.referenceQuery(control, isNodeReferenced=True):
        return []

    ref = mc.referenceQuery(control, referenceNode=True)
    nodes = mc.referenceQuery(ref, nodes=True)

    meshes = mc.ls(nodes, type='mesh')

    return [x for x in meshes if isNodeVisible(x)] 
Example #7
Source File: ml_utilities.py    From ml_tools with MIT License 5 votes vote down vote up
def curves(self):
        '''
        The keySelections's animation curve list.
        '''

        # if self._curves is False or None, then it has been initialized and curves haven't been found.
        if self._curves == []:

            #find anim curves connected to channels or nodes
            for each in (self._channels, self._nodes):
                if not each:
                    continue
                # this will only return time based keyframes, not driven keys
                self._curves = mc.keyframe(each, time=(':',), query=True, name=True)

                if self._curves:
                    self._curvesCulled = False
                    break
            if not self._curves:
                self._curves = False

        # need to remove curves which are unkeyable
        # supposedly referenced keys are keyable in 2013, I'll need to test that and update
        if self._curves and not self._curvesCulled:
            remove = list()
            for c in self._curves:
                if mc.referenceQuery(c, isNodeReferenced=True):
                    remove.append(c)
                else:
                    plug = mc.listConnections('.'.join((c,'output')), source=False, plugs=True)
                    if plug:
                        if not mc.getAttr(plug, keyable=True) and not mc.getAttr(plug, settable=True):
                            remove.append(c)
            if remove:
                for r in remove:
                    self._curves.remove(r)
            self._curvesCulled = True

        return self._curves 
Example #8
Source File: maya_warpper.py    From pipeline with MIT License 4 votes vote down vote up
def clean_up_file():
    pass
    # import references
    """
    refs = cmds.ls(type='reference')
    for i in refs:
        rFile = cmds.referenceQuery(i, f=True)
        cmds.file(rFile, importReference=True, mnr=True)    
        
    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) 
	
    # remove ngSkinTools custom nodes
    from ngSkinTools.layerUtils import LayerUtils 
    LayerUtils.deleteCustomNodes()
    
    # remove RRM proxies
    if cmds.objExists("RRM_MAIN"):
        cmds.select("RRM_MAIN",hi=True)
        proxies = cmds.ls(sl=True)
        cmds.lockNode(proxies,lock=False)
        cmds.delete(proxies)
        
        if cmds.objExists("RRM_ProxiesLayer"):
            cmds.delete("RRM_ProxiesLayer")""" 
Example #9
Source File: ml_worldBake.py    From ml_tools with MIT License 4 votes vote down vote up
def parentBake(objs, parent=None, bakeOnOnes=False):

    #check objects can be parented
    parentReferenced = mc.referenceQuery(parent, isNodeReferenced=True) if parent else False

    culledObjs = []
    for each in objs:
        eachParent = mc.listRelatives(each, parent=True)
        if mc.referenceQuery(each, isNodeReferenced=True):
            if parentReferenced:
                OpenMaya.MGlobal.displayWarning("Child and parent are both referenced, skipping: {} > {}".format(each, parent))
                continue
            if eachParent and mc.referenceQuery(eachParent[0], isNodeReferenced=True):
                OpenMaya.MGlobal.displayWarning("Node is referenced and can't be reparented, skipping: {}".format(each))
                continue
        if not parent and not eachParent:
            OpenMaya.MGlobal.displayWarning("Node is already child of the world, skipping: {}".format(each))
            continue
        culledObjs.append(each)

    if not culledObjs:
        OpenMaya.MGlobal.displayWarning("No nodes could be reparented.")
        return

    source = []
    destination = []
    for each in culledObjs:
        source.append(mc.duplicate(each, parentOnly=True)[0])
        mc.copyKey(each)
        mc.pasteKey(source[-1], option='replaceCompletely')
        try:
            if parent:
                destination.append(mc.parent(each, parent)[0])
            else:
                destination.append(mc.parent(each, world=True)[0])
        except RuntimeError as err:
            mc.delete(source)
            raise err

    utl.matchBake(source=source, destination=destination, bakeOnOnes=bakeOnOnes)

    mc.delete(source)