Python maya.cmds.nodeType() Examples

The following are 30 code examples of maya.cmds.nodeType(). 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: sets.py    From SISideBar with MIT License 6 votes vote down vote up
def add_to_set_members():
    selection = cmds.ls(sl=True)
    
    if selection:
        setCount = 0
        for node in selection:
            if cmds.nodeType(node) != 'objectSet':
                continue
            for sel in selection:
                if sel == node:
                    continue
                try:
                    cmds.sets(sel, add=node)
                except Exception as e:
                    print e.message
            setCount += 1
        if setCount == 0:
            cmds.confirmDialog( title='Error',message='Please select set_node')

#選択セットのノード、コンポーネントを削除 
Example #2
Source File: skeleton.py    From cmt with MIT License 6 votes vote down vote up
def get_joint_data(node):
    """Get the serializable data of a node.

    :param node: Joint or transform name.
    :return: Data dictionary.
    """
    node_type = cmds.nodeType(node)
    shapes = cmds.listRelatives(node, children=True, shapes=True)
    if node_type not in ["joint", "transform"] or (shapes and node_type == "transform"):
        # Skip nodes that are not joints or transforms or if there are shapes below.
        return None

    parent = cmds.listRelatives(node, parent=True)
    parent = parent[0] if parent else None
    joint_data = {"nodeType": node_type, "name": node, "parent": parent}
    for attr in ATTRIBUTES:
        attribute = "{}.{}".format(node, attr)
        if not cmds.objExists(attribute):
            continue
        value = cmds.getAttr(attribute)
        if isinstance(value, list):
            value = list(value[0])
        joint_data[attr] = value
    return joint_data 
Example #3
Source File: skeleton.py    From cmt with MIT License 6 votes vote down vote up
def create(data_list):
    """Create the transform hierarchy.

    :param data_list: The list of transform/joint data generated from dumps.
    """
    for data in data_list:
        node = data["name"]
        if not cmds.objExists(node):
            node = cmds.createNode(data["nodeType"], name=node)
        parent = data["parent"]
        if parent and cmds.objExists(parent):
            cmds.parent(node, parent)
        for attr in ATTRIBUTES:
            attribute = "{}.{}".format(node, attr)
            if not cmds.objExists(attribute):
                continue
            value = data[attr]
            if isinstance(value, string_types):
                cmds.setAttr(attribute, value, type="string")
            elif isinstance(value, list):
                cmds.setAttr(attribute, *value)
            else:
                cmds.setAttr(attribute, value) 
Example #4
Source File: uExport.py    From uExport with zlib License 6 votes vote down vote up
def convertSkelSettingsToNN(delete=1):
        orig = 'SkeletonSettings_Cache'
        if cmds.objExists(orig):
            if cmds.nodeType(orig) == 'unknown':
                new = cmds.createNode('network')
                for att in cmds.listAttr(orig):
                    if not cmds.attributeQuery(att, node=new, exists=1):
                        typ = cmds.attributeQuery(att, node=orig, at=1)
                        if typ == 'typed':
                            cmds.addAttr(new, longName=att, dt='string')
                            if cmds.getAttr(orig + '.' + att):
                                cmds.setAttr(new + '.' + att, cmds.getAttr(orig + '.' + att), type='string')
                        elif typ == 'enum':
                            cmds.addAttr(new, longName=att, at='enum', enumName=cmds.attributeQuery(att, node=orig, listEnum=1)[0])
                cmds.delete(orig)
                cmds.rename(new, 'SkeletonSettings_Cache') 
Example #5
Source File: control.py    From cmt with MIT License 6 votes vote down vote up
def _set_from_curve(self, transform):
        """Store the parameters from an existing curve in the CurveShape object.

        :param transform: Transform
        """
        shape = shortcuts.get_shape(transform)
        if shape and cmds.nodeType(shape) == "nurbsCurve":
            create_attr = "{}.create".format(shape)
            connection = cmds.listConnections(create_attr, plugs=True, d=False)
            if connection:
                cmds.disconnectAttr(connection[0], create_attr)
            self.transform = transform
            self.cvs = cmds.getAttr("{}.cv[*]".format(shape))
            self.degree = cmds.getAttr("{}.degree".format(shape))
            self.form = cmds.getAttr("{}.form".format(shape))
            self.knots = get_knots(shape)
            if cmds.getAttr("{}.overrideEnabled".format(shape)):
                if cmds.getAttr("{}.overrideRGBColors".format(shape)):
                    self.color = cmds.getAttr("{}.overrideColorRGB".format(shape))[0]
                else:
                    self.color = cmds.getAttr("{}.overrideColor".format(shape))
            else:
                self.color = None
            if connection:
                cmds.connectAttr(connection[0], create_attr) 
Example #6
Source File: ui.py    From maya-skinning-tools with GNU General Public License v3.0 6 votes vote down vote up
def getInfluenceIcon(self):
        """
        Get the influence icon based on the node type of the influence. If
        the node type is not present in the INFLUENCE_ICONS variable the
        icon will be defaulted to a transform.

        :return: Icon
        :rtype: QIcon
        """
        # get influence node type
        nodeType = cmds.nodeType(self.influence)

        # get icon path
        path = INFLUENCE_ICONS.get(nodeType, ":/out_transform.png")
        return Qt.QIcon(path)

    # ------------------------------------------------------------------------ 
Example #7
Source File: rbf.py    From cmt with MIT License 6 votes vote down vote up
def input_transform(self, i):
        """Get the input transform at index

        :param i: Index
        :return: The transform driving the input at index i
        """
        input_count = cmds.getAttr("{}.inputQuatCount".format(self.name))
        if i >= input_count:
            raise RuntimeError("Invalid input index")
        # Traverse connections to the transform
        # inputQuat <- decomposeMatrix <- transform
        connection = cmds.listConnections(
            "{}.inputQuat[{}]".format(self.name, i), d=False
        )

        if not connection or cmds.nodeType(connection[0]) != "decomposeMatrix":
            return None
        connection = cmds.listConnections(
            "{}.inputMatrix".format(connection[0]), d=False
        )
        return connection[0] if connection else None 
Example #8
Source File: skin.py    From maya-skinning-tools with GNU General Public License v3.0 6 votes vote down vote up
def getSkinCluster(mesh):
    """
    Loop over an objects history and see if a skinCluster node is part of the
    history.

    :param str mesh:
    :return: skinCluster that is attached to the parsed mesh
    :rtype: str or None
    """
    skinClusters = [
        h
        for h in cmds.listHistory(mesh) or []
        if cmds.nodeType(h) == "skinCluster"
    ]

    if skinClusters:
        return skinClusters[0] 
Example #9
Source File: samplingFunc.py    From DeformationLearningSolver with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def blendShapeSampling(node, interval=1):
    """
    Args:
      node (str)
      interval (int)
    
    Returns:
      int
    """
    assert cmds.nodeType(node) == 'blendShape', \
        "node must be a blendShape type"
    start = cmds.currentTime(q=1)
    
    attrs = cmds.listAttr('%s.weight' % node, m=1)
    attrData = {node: [[attr, 0.0, 1.0] for attr in attrs]}
    
    currTime = attrsSampling(attrData, interval)

    end = currTime-1
    utils.trimTimeRange(start, end)
    cmds.currentTime(start)

#---------------------------------------------------------------------- 
Example #10
Source File: blendshape.py    From cmt with MIT License 6 votes vote down vote up
def get_blendshape_node(geometry):
    """Get the first blendshape node upstream from the given geometry.

    :param geometry: Name of the geometry
    :return: The blendShape node name
    """
    geometry = shortcuts.get_shape(geometry)
    history = cmds.listHistory(geometry, il=2, pdo=False) or []
    blendshapes = [
        x
        for x in history
        if cmds.nodeType(x) == "blendShape"
        and cmds.blendShape(x, q=True, g=True)[0] == geometry
    ]
    if blendshapes:
        return blendshapes[0]
    else:
        return None 
Example #11
Source File: utils.py    From maya2katana with GNU General Public License v3.0 6 votes vote down vote up
def node_attributes(node):
    """
    Get Maya node attributes
    """
    attributes = cmds.listAttr(node)
    attr = {}
    attr["node_name"] = node
    attr["node_type"] = cmds.nodeType(node)
    for attribute in attributes:
        if "." in attribute:
            continue
        try:
            val = cmds.getAttr(node + "." + attribute)
        except RuntimeError:
            continue
        attr[attribute] = val
    return attr 
Example #12
Source File: ml_pivot.py    From ml_tools with MIT License 6 votes vote down vote up
def pivot_driver_attr(node):
    '''
    Start with supporting pivots driven by remap value nodes, more support in the future as requested.
    '''
    #rpSrc = mc.listConnections(node+'.rotatePivot', source=True, destination=False, plugs=True)
    #if rpSrc and rpSrc[0].endswith('.translate') and mc.getAttr(rpSrc[0], keyable=True):
        #return rpSrc[0]

    for each in ('rotatePivotX', 'rotatePivotY', 'rotatePivotZ'):
        src = mc.listConnections(node+'.'+each, source=True, destination=False)
        if not src:
            continue
        srcType = mc.nodeType(src[0])
        if srcType == 'remapValue':
            src = mc.listConnections(src[0]+'.inputValue', source=True, destination=False, plugs=True)
            if src and mc.getAttr(src[0], keyable=True) and not mc.getAttr(src[0], lock=True):
                return src[0]
    return None 
Example #13
Source File: ml_utilities.py    From ml_tools with MIT License 6 votes vote down vote up
def getSkinCluster(mesh):
    '''
    Return the first skinCluster affecting this mesh.
    '''

    if mc.nodeType(mesh) in ('mesh','nurbsSurface','nurbsCurve'):
        shapes = [mesh]
    else:
        shapes = mc.listRelatives(mesh, shapes=True, path=True)

    for shape in shapes:
        history = mc.listHistory(shape, groupLevels=True, pruneDagObjects=True)
        if not history:
            continue
        skins = mc.ls(history, type='skinCluster')
        if skins:
            return skins[0]
    return None 
Example #14
Source File: transform.py    From SISideBar with MIT License 6 votes vote down vote up
def reset_actor():
    from . import sisidebar_sub
    sel = cmds.ls(sl=True, l=True)
    joints = cmds.ls(sl=True, l=True, type='joint')
    if not joints:
        joints = []
    for s in sel:
        if cmds.nodeType(s) == 'KTG_ModelRoot':
            child_joints = cmds.ls(cmds.listRelatives(s, ad=True, f=True), l=True, type='joint')
            if child_joints:
                joints += child_joints
    if not sel:
        joints = cmds.ls(l=True, type='joint')
    for j in joints:
        con_info = cmds.connectionInfo(j+'.bindPose', dfs=True)
        if not con_info:
            continue
        con_info = con_info[0]
        bind_info = con_info.replace('world', 'xform')
        pose = cmds.getAttr(bind_info)
        cmds.xform(j, m=pose)
    sisidebar_sub.get_matrix() 
Example #15
Source File: curve.py    From maya-spline-ik with GNU General Public License v3.0 6 votes vote down vote up
def convertToBezierCurve(curve):
    """
    Check if the parsed curve is a bezier curve, if this is not the case
    convert the curve to a bezier curve.
    
    :param str curve: Name of curve
    """
    # get shape
    curveShape = cmds.listRelatives(curve, s=True)[0]

    # convert to bezier curve
    if cmds.nodeType(curveShape) == "bezierCurve":
        return
        
    cmds.select(curve)
    cmds.nurbsCurveToBezier()


# ---------------------------------------------------------------------------- 
Example #16
Source File: shortcuts.py    From cmt with MIT License 5 votes vote down vote up
def get_shape(node, intermediate=False):
    """Get the shape node of a tranform

    This is useful if you don't want to have to check if a node is a shape node
    or transform.  You can pass in a shape node or transform and the function
    will return the shape node.

    :param node:  node The name of the node.
    :param intermediate:  intermediate True to get the intermediate shape
    :return: The name of the shape node.
    """
    if cmds.objectType(node, isAType="transform"):
        shapes = cmds.listRelatives(node, shapes=True, path=True)
        if not shapes:
            shapes = []
        for shape in shapes:
            is_intermediate = cmds.getAttr("{}.intermediateObject".format(shape))
            if (
                intermediate
                and is_intermediate
                and cmds.listConnections(shape, source=False)
            ):
                return shape
            elif not intermediate and not is_intermediate:
                return shape
        if shapes:
            return shapes[0]
    elif cmds.nodeType(node) in ["mesh", "nurbsCurve", "nurbsSurface"]:
        is_intermediate = cmds.getAttr("{}.intermediateObject".format(node))
        if is_intermediate and not intermediate:
            node = cmds.listRelatives(node, parent=True, path=True)[0]
            return get_shape(node)
        else:
            return node
    return None 
Example #17
Source File: ml_utilities.py    From ml_tools with MIT License 5 votes vote down vote up
def getChannelFromAnimCurve(curve, plugs=True):
    '''
    Finding the channel associated with a curve has gotten really complicated since animation layers.
    This is a recursive function which walks connections from a curve until an animated channel is found.
    '''


    #we need to save the attribute for later.
    attr = ''
    if '.' in curve:
        curve, attr = curve.split('.')

    nodeType = mc.nodeType(curve)
    if nodeType.startswith('animCurveT') or nodeType.startswith('animBlendNode'):
        source = mc.listConnections(curve+'.output', source=False, plugs=plugs)
        if not source and nodeType=='animBlendNodeAdditiveRotation':
            #if we haven't found a connection from .output, then it may be a node that uses outputX, outputY, etc.
            #get the proper attribute by using the last letter of the input attribute, which should be X, Y, etc.
            #if we're not returning plugs, then we wont have an attr suffix to use, so just use X.
            attrSuffix = 'X'
            if plugs:
                attrSuffix = attr[-1]

            source = mc.listConnections(curve+'.output'+attrSuffix, source=False, plugs=plugs)
        if source:
            nodeType = mc.nodeType(source[0])
            if nodeType.startswith('animCurveT') or nodeType.startswith('animBlendNode'):
                return getChannelFromAnimCurve(source[0], plugs=plugs)
            return source[0] 
Example #18
Source File: ml_utilities.py    From ml_tools with MIT License 5 votes vote down vote up
def getCurrentCamera():
    '''
    Returns the camera that you're currently looking through.
    If the current highlighted panel isn't a modelPanel,
    '''

    panel = mc.getPanel(withFocus=True)

    if mc.getPanel(typeOf=panel) != 'modelPanel':
        #just get the first visible model panel we find, hopefully the correct one.
        for p in mc.getPanel(visiblePanels=True):
            if mc.getPanel(typeOf=p) == 'modelPanel':
                panel = p
                mc.setFocus(panel)
                break

    if mc.getPanel(typeOf=panel) != 'modelPanel':
        OpenMaya.MGlobal.displayWarning('Please highlight a camera viewport.')
        return False

    camShape = mc.modelEditor(panel, query=True, camera=True)
    if not camShape:
        return False

    camNodeType = mc.nodeType(camShape)
    if mc.nodeType(camShape) == 'transform':
        return camShape
    elif mc.nodeType(camShape) in ['camera','stereoRigCamera']:
        return mc.listRelatives(camShape, parent=True, path=True)[0] 
Example #19
Source File: skinio.py    From cmt with MIT License 5 votes vote down vote up
def get_skin_clusters(nodes):
    """Get the skinClusters attached to the specified node and all nodes in descendents.

    :param nodes: List of dag nodes.
    @return A list of the skinClusters in the hierarchy of the specified root node.
    """
    if isinstance(nodes, string_types):
        nodes = [nodes]
    all_skins = []
    for node in nodes:
        relatives = cmds.listRelatives(node, ad=True, path=True) or []
        relatives.insert(0, node)
        relatives = [shortcuts.get_shape(node) for node in relatives]
        for relative in relatives:
            history = cmds.listHistory(relative, pruneDagObjects=True, il=2) or []
            skins = [x for x in history if cmds.nodeType(x) == "skinCluster"]
            if skins:
                all_skins.append(skins[0])
    return list(set(all_skins)) 
Example #20
Source File: common.py    From SIWeightEditor with MIT License 5 votes vote down vote up
def cutChildNode(self):
        # 処理ノードの親子を取得しておく
        nodeChildren = cmds.listRelatives(self.node, children=True, fullPath=True) or []
        for child in nodeChildren:
            # 子のノードがトランスフォームならダミーに親子付けして退避
            if cmds.nodeType(child) in self.node_list:
                cmds.parent(child, self.dummyParent)
                
    #フリーズトランスフォーム用に場合分け親子付け関数を用意
    #子を含むマルチ選択状態の場合は別のダミー親につけてフリーズ後のSRT状態を調整する 
Example #21
Source File: common.py    From SIWeightEditor with MIT License 5 votes vote down vote up
def customCutChildNode(self):
        nodeChildren = cmds.listRelatives(self.node, children=True, fullPath=True) or []
        for child in nodeChildren:
            if cmds.nodeType(child) in self.node_list:
                if child in self.preSelection:
                    #print 'parent to dummy'
                    cmds.parent(child, self.dummyParent)
                else:
                    #print 'parent to srt dummy'
                    cmds.parent(child, self.srtDummyParent) 
Example #22
Source File: common.py    From SIWeightEditor with MIT License 5 votes vote down vote up
def reparentNode(self):
        dummyChildren = cmds.listRelatives(self.dummyParent, children=True, fullPath=True) or []
        for child in dummyChildren:
            if cmds.nodeType(child) in self.node_list:
                cmds.parent(child, self.node) 
Example #23
Source File: utils.py    From maya-keyframe-reduction with MIT License 5 votes vote down vote up
def getSelectionAnimationCurves():
    """
    :return: Selection animation curves
    :rtype: list
    """
    # get selection
    animationCurves = set()
    selection = cmds.ls(sl=True) or []

    # loop selection
    for sel in selection:
        # add selection is an animation curve
        if cmds.nodeType(sel).startswith("animCurve"):
            animationCurves.add(sel)
            continue

        # check if any animation curves are connected to node
        for animationCurve in cmds.listConnections(
            sel,
            type="animCurve",
            source=True,
            destination=False,
            skipConversionNodes=True,
        ) or []:
            animationCurves.add(animationCurve)

    # convert animation curves to list
    animationCurves = list(animationCurves)
    return filterAnimationCurves(animationCurves) 
Example #24
Source File: common.py    From SISideBar with MIT License 5 votes vote down vote up
def cutChildNode(self):
        # 処理ノードの親子を取得しておく
        nodeChildren = cmds.listRelatives(self.node, children=True, fullPath=True) or []
        for child in nodeChildren:
            # 子のノードがトランスフォームならダミーに親子付けして退避
            if cmds.nodeType(child) in self.node_list:
                cmds.parent(child, self.dummyParent)
    #フリーズトランスフォーム用に場合分け親子付け関数を用意
    #子を含むマルチ選択状態の場合は別のダミー親につけてフリーズ後のSRT状態を調整する 
Example #25
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 #26
Source File: ui.py    From maya-spline-ik with GNU General Public License v3.0 5 votes vote down vote up
def getSelection(self):
        """
        Get the current selection and see if the shapes of the first instance
        of the selection are of type 'nurbsCurve' or 'bezierCurve', if the
        criteria are met the line edit of the curve selection widget is 
        updated. If the criteria are not met a ValueError will be raised.
        
        :raises ValueError: if the selection criteria are not met.
        """
        # get selection
        selection = cmds.ls(sl=True)
        if not selection:
            raise ValueError("No selection found!")
         
        # check shapes ( exist )
        shapes = cmds.listRelatives(selection[0], s=True) or []
        if not shapes:
            raise ValueError("No shapes found in selection!")
        
        # check shapes
        for shape in shapes:
            if cmds.nodeType(shape) not in ["nurbsCurve", "bezierCurve"]:
                raise ValueError(
                    "Shapes are not of type 'nurbsCurve' or 'bezierCurve'!"
                )

        # set text
        self.curve.setText(selection[0])
        
    # ------------------------------------------------------------------------ 
Example #27
Source File: utils.py    From maya-retarget-blendshape with GNU General Public License v3.0 5 votes vote down vote up
def getSelectedMeshes():
    """
    Get all selected meshes, the current selection will be looped and checked
    if any of the selected transforms contain a mesh node. If this is the case
    the transform will be added to the selection list.

    :return: Parents nodes of all selected meshes
    :rtype: list
    """
    # get selection
    selection = cmds.ls(sl=True, l=True)
    extendedSelection = []

    # extend selection
    for sel in selection:
        extendedSelection.extend(
            cmds.listRelatives(sel, s=True, ni=True, f=True)
        )

    # return parent of meshes
    return list(set([
        cmds.listRelatives(m, p=True, f=True)[0]
        for m in extendedSelection
        if cmds.nodeType(m) == "mesh"
    ]))


# ---------------------------------------------------------------------------- 
Example #28
Source File: transform.py    From SISideBar with MIT License 5 votes vote down vote up
def round_transform(mode='', digit=3):
    from . import sisidebar_sub
    sel = cmds.ls(sl=True, l=True)

    axis = ['X', 'Y', 'Z']
    if mode == 'all':
        mode_list = ['.translate', '.rotate', '.scale', '.jointOrient']
    else:
        mode_list = ['.' + mode]
    for s in sel:
        for a, m in itertools.product(axis, mode_list):
            #print cmds.nodeType(s) , m
            #print cmds.nodeType(s) != 'joint'
            if cmds.nodeType(s) != 'joint' and m == '.jointOrient':
                #print m == '.jointOrient'
                #print 'Node Type Error'
                continue
            try:
                v = cmds.getAttr(s+m+a)
                #print v
                v = round(v, digit)
                cmds.setAttr(s+m+a, v)
                #print v
            except Exception as e:
                print e.message
    sisidebar_sub.get_matrix() 
Example #29
Source File: texture.py    From SISideBar with MIT License 5 votes vote down vote up
def searchPlace2d(self, parentNode):
        #ノード接続のソース側のみ取得、dフラグで目的側は取得除外
        self.__nodeName.append(parentNode)#無限ループ回避リスト
        if cmds.nodeType(parentNode) == 'place2dTexture':#ノードタイプがplace2dなら
            self.place2dItems.append(parentNode)
            return
        connectNodes = cmds.listConnections(parentNode, s=True, d=False)
        if connectNodes is not None:
            for nextNode in connectNodes:
                recicleFlag = False#無限サイクル回避フラグ
                for nN in self.__nodeName:#既に処理済みのノードなら
                    if nN == nextNode:
                        recicleFlag = True#サイクルフラグをTrueに
                if recicleFlag is False:#処理済みでないノードであれば再帰的呼び出しする
                    self.searchPlace2d(nextNode) 
Example #30
Source File: util.py    From core with MIT License 5 votes vote down vote up
def shape_from_element(element):
    """Return shape of given 'element'

    Supports components, meshes, and surfaces

    """

    try:
        # Get either shape or transform, based on element-type
        node = cmds.ls(element, objectsOnly=True)[0]
    except:
        cmds.warning("Could not find node in %s" % element)
        return None

    if cmds.nodeType(node) == 'transform':
        try:
            return cmds.listRelatives(node, shapes=True)[0]
        except:
            cmds.warning("Could not find shape in %s" % element)
            return None

    else:
        return node