Python maya.cmds.objectType() Examples

The following are 25 code examples of maya.cmds.objectType(). 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: dpFacialControl.py    From dpAutoRigSystem with GNU General Public License v2.0 7 votes vote down vote up
def dpLoadBSNode(self, *args):
        """ Load selected object as blendShapeNode
        """
        selectedList = cmds.ls(selection=True)
        if selectedList:
            if cmds.objectType(selectedList[0]) == "blendShape":
                cmds.textField(self.bsNodeTextField, edit=True, text=selectedList[0])
                self.dpLoadBSTgtList(selectedList[0])
                self.bsNode = selectedList[0]
            elif cmds.objectType(selectedList[0]) == "transform":
                meshList = cmds.listRelatives(selectedList[0], children=True, shapes=True, noIntermediate=True, type="mesh")
                if meshList:
                    bsNodeList = cmds.listConnections(meshList[0], type="blendShape")
                    if bsNodeList:
                        self.dpLoadBSTgtList(bsNodeList[0])
                        self.bsNode = bsNodeList[0]
                    else:
                        mel.eval("warning \""+self.langDic[self.langName]["e018_selectBlendShape"]+"\";")
                else:
                    mel.eval("warning \""+self.langDic[self.langName]["e018_selectBlendShape"]+"\";")
            else:
                mel.eval("warning \""+self.langDic[self.langName]["e018_selectBlendShape"]+"\";")
        else:
            mel.eval("warning \""+self.langDic[self.langName]["e018_selectBlendShape"]+"\";") 
Example #2
Source File: dpFacialControl.py    From dpAutoRigSystem with GNU General Public License v2.0 6 votes vote down vote up
def dpLoadBSTgtList(self, bsNodeName, *args):
        """ Add target list found in the blendShape node to target textScroll list
        """
        if cmds.objExists(bsNodeName):
            if cmds.objectType(bsNodeName) == "blendShape":
                tgtList = cmds.blendShape(bsNodeName, query=True, target=True)
                if tgtList:
                    cmds.textScrollList(self.bsTargetScrollList, edit=True, removeAll=True)
                    cmds.textScrollList(self.bsTargetScrollList, edit=True, append=tgtList)
                    cmds.textField(self.bsNodeTextField, edit=True, text=bsNodeName)
                    self.bsNode = bsNodeName 
Example #3
Source File: dpCopySkin.py    From dpAutoRigSystem with GNU General Public License v2.0 6 votes vote down vote up
def dpCheckSkinCluster(self, shapeList, *args):
        """ Verify if there's a skinCluster node in the list of history of the shape.
            Return True if yes.
            Return False if no.
            Return -1 if there's another node with the same name.
        """
        for shapeNode in shapeList:
            if not shapeNode.endswith("Orig"):
                try:
                    histList = cmds.listHistory(shapeNode)
                    if histList:
                        for histItem in histList:
                            if cmds.objectType(histItem) == "skinCluster":
                                return True
                except:
                    return -1
        return False 
Example #4
Source File: dpRivet.py    From dpAutoRigSystem with GNU General Public License v2.0 6 votes vote down vote up
def dpCheckGeometry(self, item, *args):
        isGeometry = False
        if item:
            if cmds.objExists(item):
                childList = cmds.listRelatives(item, children=True)
                if childList:
                    self.itemType = cmds.objectType(childList[0])
                    if self.itemType == "mesh" or self.itemType == "nurbsSurface":
                        if self.itemType == "mesh":
                            self.meshNode = childList[0]
                        isGeometry = True
                    else:
                        mel.eval("warning \""+item+" is not a geometry.\";")
                else:
                    mel.eval("warning \"Select the transform node instead of "+item+" shape, please.\";")
            else:
                mel.eval("warning \""+item+" does not exists, maybe it was deleted, sorry.\";")
        else:
            mel.eval("warning \"Not found "+item+"\";")
        return isGeometry 
Example #5
Source File: dpLayoutClass.py    From dpAutoRigSystem with GNU General Public License v2.0 6 votes vote down vote up
def loadGeo(self, *args):
        """ Loads the selected node to geoTextField in selectedModuleLayout.
        """
        isGeometry = False
        selList = cmds.ls(selection=True)
        if selList:
            if cmds.objExists(selList[0]):
                childList = cmds.listRelatives(selList[0], children=True, allDescendents=True)
                if childList:
                    for item in childList:
                        itemType = cmds.objectType(item)
                        if itemType == "mesh" or itemType == "nurbsSurface":
                            isGeometry = True
        if isGeometry:
            cmds.textField(self.geoTF, edit=True, text=selList[0])
            cmds.setAttr(self.moduleGrp+".geo", selList[0], type='string') 
Example #6
Source File: dpControls.py    From dpAutoRigSystem with GNU General Public License v2.0 5 votes vote down vote up
def findHistory(self, objList, historyName, *args):
        """Search and return the especific history of the listed objects.
        """
        if objList:
            foundHistoryList = []
            for objName in objList:
                # find historyName in the object's history:
                histList = cmds.listHistory(objName)
                for hist in histList:
                    histType = cmds.objectType(hist)
                    if histType == historyName:
                        foundHistoryList.append(hist)
            return foundHistoryList 
Example #7
Source File: BlendTransforms.py    From BlendTransforms with The Unlicense 5 votes vote down vote up
def BT_Setup(set = None):
    
    if not set:
        return False

    transforms = cmds.listConnections(set +'.dagSetMembers')
    if not transforms:
        return False

    if not cmds.attributeQuery('Blend_Node', n = set, ex = True):
        cmds.addAttr(set, ln = 'Blend_Node', k = False, h = True, dt = 'string')
    else:
        return False

    btNode = cmds.createNode("BlendTransforms")
    cmds.setAttr(set +'.Blend_Node', btNode, type = "string")

    for i in range(0, len(transforms)):
        baseMatrix = cmds.xform(transforms[i], q = True, m = True)
        baseScale = cmds.getAttr(transforms[i] +'.scale')[0]
        baseRotOffset = [0.0, 0.0, 0.0]

        if cmds.objectType(transforms[i], isType = 'joint'):
            baseRotOffset = cmds.getAttr(transforms[i] +'.jointOrient')[0]

        btAttr = 'transforms[' +str(i) +'].baseMatrix'
        btScaleAttr = 'transforms[' +str(i) +'].baseScale'
        btRotOffsetAttr = 'transforms[' +str(i) +'].baseRotOffset'

        BT_MatrixValuesToNode(values = baseMatrix, node = btNode, attr = btAttr)
        BT_Double3ValuesToNode(values = baseScale, node = btNode, attr = btScaleAttr)
        BT_Double3ValuesToNode(values = baseRotOffset, node = btNode, attr = btRotOffsetAttr)
        BT_ConnectOutputs(index = i, node = btNode, transform = transforms[i])

    return True 
Example #8
Source File: BlendTransforms.py    From BlendTransforms with The Unlicense 5 votes vote down vote up
def BT_Setup(set = None):
    
    if not set:
        return False

    transforms = cmds.listConnections(set +'.dagSetMembers')
    if not transforms:
        return False

    if not cmds.attributeQuery('Blend_Node', n = set, ex = True):
        cmds.addAttr(set, ln = 'Blend_Node', k = False, h = True, dt = 'string')
    else:
        return False

    btNode = cmds.createNode("BlendTransforms")
    cmds.setAttr(set +'.Blend_Node', btNode, type = "string")

    for i in range(0, len(transforms)):
        baseMatrix = cmds.xform(transforms[i], q = True, m = True)
        baseScale = cmds.getAttr(transforms[i] +'.scale')[0]
        baseRotOffset = [0.0, 0.0, 0.0]

        if cmds.objectType(transforms[i], isType = 'joint'):
            baseRotOffset = cmds.getAttr(transforms[i] +'.jointOrient')[0]

        btAttr = 'transforms[' +str(i) +'].baseMatrix'
        btScaleAttr = 'transforms[' +str(i) +'].baseScale'
        btRotOffsetAttr = 'transforms[' +str(i) +'].baseRotOffset'

        BT_MatrixValuesToNode(values = baseMatrix, node = btNode, attr = btAttr)
        BT_Double3ValuesToNode(values = baseScale, node = btNode, attr = btScaleAttr)
        BT_Double3ValuesToNode(values = baseRotOffset, node = btNode, attr = btRotOffsetAttr)
        BT_ConnectOutputs(index = i, node = btNode, transform = transforms[i])

    return True 
Example #9
Source File: BlendTransforms.py    From BlendTransforms with The Unlicense 5 votes vote down vote up
def BT_Setup(set = None):
    
    if not set:
        return False

    transforms = cmds.listConnections(set +'.dagSetMembers')
    if not transforms:
        return False

    if not cmds.attributeQuery('Blend_Node', n = set, ex = True):
        cmds.addAttr(set, ln = 'Blend_Node', k = False, h = True, dt = 'string')
    else:
        return False

    btNode = cmds.createNode("BlendTransforms")
    cmds.setAttr(set +'.Blend_Node', btNode, type = "string")

    for i in range(0, len(transforms)):
        baseMatrix = cmds.xform(transforms[i], q = True, m = True)
        baseScale = cmds.getAttr(transforms[i] +'.scale')[0]
        baseRotOffset = [0.0, 0.0, 0.0]

        if cmds.objectType(transforms[i], isType = 'joint'):
            baseRotOffset = cmds.getAttr(transforms[i] +'.jointOrient')[0]

        btAttr = 'transforms[' +str(i) +'].baseMatrix'
        btScaleAttr = 'transforms[' +str(i) +'].baseScale'
        btRotOffsetAttr = 'transforms[' +str(i) +'].baseRotOffset'

        BT_MatrixValuesToNode(values = baseMatrix, node = btNode, attr = btAttr)
        BT_Double3ValuesToNode(values = baseScale, node = btNode, attr = btScaleAttr)
        BT_Double3ValuesToNode(values = baseRotOffset, node = btNode, attr = btRotOffsetAttr)
        BT_ConnectOutputs(index = i, node = btNode, transform = transforms[i])

    return True 
Example #10
Source File: utils.py    From DeformationLearningSolver with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def findRelatedSkinCluster(geometry):
    '''
    Return the skinCluster attached to the specified geometry
    
    Args:
      geometry (str): Geometry object/transform to query
    
    Returns:
      str
    '''
    # Check geometry
    if not cmds.objExists(geometry):
        om.MGlobal.displayError('Object '+geometry+' does not exist!')
        return
    
    # Check transform
    if cmds.objectType(geometry) == 'transform':
        try: geometry = cmds.listRelatives(geometry,s=True,ni=True,pa=True)[0]
        except:
            om.MGlobal.displayError('Object %s has no deformable geometry!' % geometry)
            return

    # Determine skinCluster
    skin = mel.eval('findRelatedSkinCluster \"%s\"' % geometry)
    if not skin: 
        skin = cmds.ls(cmds.listHistory(geometry, pdo=1, gl=1), type='skinCluster')
        if skin: skin = skin[0]
    if not skin: skin = None

    # Return result
    return skin

#---------------------------------------------------------------------- 
Example #11
Source File: gears2.py    From PythonForMayaSamples with GNU General Public License v3.0 5 votes vote down vote up
def createPipe(self, spans):
        # We set the transform and shape to the class variables
        self.transform, self.shape = cmds.polyPipe(subdivisionsAxis=spans)

        # I didn't like having to find the constructor from the extrude node
        # Lets just find it now and save it to the class because it won't change
        for node in cmds.listConnections('%s.inMesh' % self.transform):
            if cmds.objectType(node) == 'polyPipe':
                self.constructor = node
                break 
Example #12
Source File: manager.py    From spore with MIT License 5 votes vote down vote up
def get_spore_setups(self):
        """ return a dictionary with an entry for each target mesh
        and for each entry a list with all connected spore nodes """

        spore_nodes = cmds.ls(type='sporeNode', l=True)
        targets = collections.defaultdict(list)

        #  TODO - once this can be debugged this would be the way to go
        #  [targets[node_utils.get_connected_in_mesh(node)].append(node) for node in spore_nodes]

        for node in spore_nodes:
            target = node_utils.get_connected_in_mesh(node)
            if target:
                targets[target].append(node)

            else: # May help to debbug a situation wherfe target is sometime None
                target = cmds.getConnection('{}.inMesh'.format(node))
                target_shape = cmds.listRelatives(cmds.ls(target), s=True, f=True)

                if len(target_shape) == 1:
                    obj_type = cmds.objectType(target_shape[0])
                    self.logger.warning(
                        'Getting target mesh failed but spore has been able '
                        'to use fallback. target: {}, shape: {}, type: '
                        '{}'.format(target, target_shape[0], obj_type))
                    targets[target_shape] = node
                else:
                    obj_type = [cmds.objectType(s) for s in target_shape]
                    raise RuntimeError(
                        'Could not get target mesh and spore failed to use '
                        'fallback. target {}, shapes {}, types: {}'.format(
                            target, target_shape, obj_type)
                    )

        return targets 
Example #13
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 #14
Source File: dpControls.py    From dpAutoRigSystem with GNU General Public License v2.0 5 votes vote down vote up
def setNotRenderable(self, objList, *args):
        """Receive a list of objects, find its shapes if necessary and set all as not renderable.
        """
        # declare a list of attributes for render:
        renderAttrList = ["castsShadows", "receiveShadows", "motionBlur", "primaryVisibility", "smoothShading", "visibleInReflections", "visibleInRefractions", "doubleSided", "miTransparencyCast", "miTransparencyReceive", "miReflectionReceive", "miRefractionReceive", "miFinalGatherCast", "miFinalGatherReceive"]
        shapeTypeList = ['nurbsCurve', 'nurbsSurface', 'mesh', 'subdiv']
        # find all children shapes:
        if objList:
            for obj in objList:
                objType = cmds.objectType(obj)
                # verify if the object is the shape type:
                if objType in shapeTypeList:
                    # set attributes as not renderable:
                    for attr in renderAttrList:
                        try:
                            cmds.setAttr(obj+"."+attr, 0)
                        except:
                            #print "Error: Cannot set not renderable ", attr, "as zero for", obj
                            pass
                # verify if the object is a transform type:
                elif objType == "transform":
                    # find all shapes children of the transform object:
                    shapeList = cmds.listRelatives(obj, shapes=True, children=True)
                    if shapeList:
                        for shape in shapeList:
                            # set attributes as not renderable:
                            for attr in renderAttrList:
                                try:
                                    cmds.setAttr(shape+"."+attr, 0)
                                except:
                                    #print "Error: Cannot set not renderable ", attr, "as zero for", shape
                                    pass 
Example #15
Source File: dpTargetMirror.py    From dpAutoRigSystem with GNU General Public License v2.0 5 votes vote down vote up
def dpCheckGeometry(self, item, *args):
        isGeometry = False
        if item:
            if cmds.objExists(item):
                childList = cmds.listRelatives(item, children=True)
                if childList:
                    try:
                        itemType = cmds.objectType(childList[0])
                        if itemType == "mesh" or itemType == "nurbsSurface" or itemType == "subdiv":
                            if cmds.checkBox(self.checkHistoryCB, query=True, value=True):
                                historyList = cmds.listHistory(childList[0])
                                if len(historyList) > 1:
                                    dialogReturn = cmds.confirmDialog(title=self.langDic[self.langName]["i159_historyFound"], message=self.langDic[self.langName]["i160_historyDesc"]+"\n\n"+item+"\n\n"+self.langDic[self.langName]["i161_historyMessage"], button=['Yes','No'], defaultButton='Yes', cancelButton='No', dismissString='No')
                                    if dialogReturn == "Yes":
                                        isGeometry = True
                                else:
                                    isGeometry = True
                            else:
                                isGeometry = True
                        else:
                            mel.eval("warning \""+item+" "+self.langDic[self.langName]["i058_notGeo"]+"\";")
                    except:
                        mel.eval("warning \""+self.langDic[self.langName]["i163_sameName"]+" "+item+"\";")
                else:
                    mel.eval("warning \""+self.langDic[self.langName]["i059_selTransform"]+" "+item+" "+self.langDic[self.langName]["i060_shapePlease"]+"\";")
            else:
                mel.eval("warning \""+item+" "+self.langDic[self.langName]["i061_notExists"]+"\";")
        else:
            mel.eval("warning \""+self.langDic[self.langName]["i062_notFound"]+" "+item+"\";")
        return isGeometry 
Example #16
Source File: weight.py    From SIWeightEditor with MIT License 4 votes vote down vote up
def joint_label(object, visibility=False):
    '''
    ジョイントラベル設定関数
    object→オブジェクト、リスト形式可
    visibility→ラベルの可視性、省略可能。デフォルトFalse。
    '''
    #ラベリングルールをロードしておく
    left_list_list, right_list_list = load_joint_label_rules()
    
    # リストタイプじゃなかったらリストに変換する
    if not isinstance(object, list):
        temp = object
        object = []
        object.append(temp)
    for skinJoint in object:
        objTypeName = cmds.objectType(skinJoint)
        
        if objTypeName == 'joint':
            split_name = skinJoint.split('|')[-1]
            
            # スケルトン名にLRが含まれているかどうかを判定
            side = 0
            side_name = ''
            for i, (l_list, r_list) in enumerate(zip(left_list_list, right_list_list)):
                for j, lr_list in enumerate([l_list, r_list]):
                    for k, lr in enumerate(lr_list):
                        if i == 0:
                            if re.match(lr, split_name):
                                side = j + 1
                        if i == 1:
                            if re.search(lr, split_name):
                                side = j + 1
                        if i == 2:
                            if re.match(lr[::-1], split_name[::-1]):
                                side = j + 1
                        if side:#対象が見つかってたら全部抜ける
                            side_name = lr
                            break
                    if side:
                        break
                if side:
                    break
            #print 'joint setting :', split_name, side, side_name
            # 左右のラベルを設定、どちらでもないときは中央
            cmds.setAttr(skinJoint + '.side', side)
            # ラベルタイプを”その他”に設定
            cmds.setAttr(skinJoint + '.type', 18)
            new_joint_name = split_name.replace(side_name.replace('.', ''), '')
                
            # スケルトン名設定
            cmds.setAttr(skinJoint + '.otherType', new_joint_name, type='string')
            # 可視性設定
            cmds.setAttr(skinJoint + '.drawLabel', visibility)
        else:
            print(str(skinJoint) + ' : ' + str(objTypeName) + ' Skip Command')
            
#ウェイトのミュートをトグル 
Example #17
Source File: lib.py    From maya-capture-gui with MIT License 4 votes vote down vote up
def get_current_camera():
    """Returns the currently active camera.

    Searched in the order of:
        1. Active Panel
        2. Selected Camera Shape
        3. Selected Camera Transform

    Returns:
        str: name of active camera transform

    """

    # Get camera from active modelPanel  (if any)
    panel = cmds.getPanel(withFocus=True)
    if cmds.getPanel(typeOf=panel) == "modelPanel":
        cam = cmds.modelEditor(panel, query=True, camera=True)
        # In some cases above returns the shape, but most often it returns the
        # transform. Still we need to make sure we return the transform.
        if cam:
            if cmds.nodeType(cam) == "transform":
                return cam
            # camera shape is a shape type
            elif cmds.objectType(cam, isAType="shape"):
                parent = cmds.listRelatives(cam, parent=True, fullPath=True)
                if parent:
                    return parent[0]

    # Check if a camShape is selected (if so use that)
    cam_shapes = cmds.ls(selection=True, type="camera")
    if cam_shapes:
        return cmds.listRelatives(cam_shapes,
                                  parent=True,
                                  fullPath=True)[0]

    # Check if a transform of a camShape is selected
    # (return cam transform if any)
    transforms = cmds.ls(selection=True, type="transform")
    if transforms:
        cam_shapes = cmds.listRelatives(transforms, shapes=True, type="camera")
        if cam_shapes:
            return cmds.listRelatives(cam_shapes,
                                      parent=True,
                                      fullPath=True)[0] 
Example #18
Source File: BlendTransforms.py    From BlendTransforms with The Unlicense 4 votes vote down vote up
def BT_SetPose(set = None, index = None):
    if not set:
        return False

    if BT_IsSetupConnected(set = set):
        cmds.warning('Disconnect setup first!')
        return False

    if not cmds.attributeQuery('Blend_Node', ex = True, n = set):
        return False

    node = cmds.getAttr(set +'.Blend_Node')
    transforms = cmds.listConnections(set +'.dagSetMembers')
    if not transforms:
        return False

    unitResult = BT_SetUnits()
    if unitResult:
        QtGui.QMessageBox.warning(BT_GetMayaWindow(), "Blend Transforms", "Units set to centimetres.", "Okay")

    for i in range(0, len(transforms)):
        baseM = cmds.getAttr(node +'.transforms[' +str(i) +'].baseMatrix')
        baseS = cmds.getAttr(node +'.transforms[' +str(i) +'].baseScale')[0]
        baseRO = cmds.getAttr(node +'.transforms[' +str(i) +'].baseRotOffset')[0]

        poseM = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
        poseS = [0,0,0]

        if index is not None:
            numPoses = cmds.getAttr(node +'.transforms[0].poses', size = True)
            if not index < numPoses:
                return False 
            poseM = cmds.getAttr(node +'.transforms[' +str(i) +'].poses[' +str(index) +'].matrix')
            poseS = cmds.getAttr(node +'.transforms[' +str(i) +'].poses[' +str(index) +'].scale')[0]

        finalM = [x+y for x, y in zip(poseM, baseM)]
        finalS = [x+y for x, y in zip(poseS, baseS)]

        cmds.xform(transforms[i], m = finalM)
        cmds.setAttr(transforms[i] +'.scale', finalS[0], finalS[1], finalS[2], type = 'double3')
        #hack to fix joint orient stuff
        if cmds.objectType(transforms[i], isType = 'joint'):
            cmds.setAttr(transforms[i] +'.jointOrient', baseRO[0], baseRO[1], baseRO[2], type = 'double3')
            currentRot = cmds.getAttr(transforms[i] +'.rotate')[0]
            cmds.setAttr(transforms[i] +'.rotate', currentRot[0] - baseRO[0], currentRot[1] - baseRO[1], currentRot[2] - baseRO[2], type = 'double3')


    return True 
Example #19
Source File: BlendTransforms.py    From BlendTransforms with The Unlicense 4 votes vote down vote up
def BT_SetPose(set = None, index = None):
    if not set:
        return False

    if BT_IsSetupConnected(set = set):
        cmds.warning('Disconnect setup first!')
        return False

    if not cmds.attributeQuery('Blend_Node', ex = True, n = set):
        return False

    node = cmds.getAttr(set +'.Blend_Node')
    transforms = cmds.listConnections(set +'.dagSetMembers')
    if not transforms:
        return False

    unitResult = BT_SetUnits()
    if unitResult:
        QtGui.QMessageBox.warning(BT_GetMayaWindow(), "Blend Transforms", "Units set to centimetres.", "Okay")

    for i in range(0, len(transforms)):
        baseM = cmds.getAttr(node +'.transforms[' +str(i) +'].baseMatrix')
        baseS = cmds.getAttr(node +'.transforms[' +str(i) +'].baseScale')[0]
        baseRO = cmds.getAttr(node +'.transforms[' +str(i) +'].baseRotOffset')[0]

        poseM = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
        poseS = [0,0,0]

        if index is not None:
            numPoses = cmds.getAttr(node +'.transforms[0].poses', size = True)
            if not index < numPoses:
                return False 
            poseM = cmds.getAttr(node +'.transforms[' +str(i) +'].poses[' +str(index) +'].matrix')
            poseS = cmds.getAttr(node +'.transforms[' +str(i) +'].poses[' +str(index) +'].scale')[0]

        finalM = [x+y for x, y in zip(poseM, baseM)]
        finalS = [x+y for x, y in zip(poseS, baseS)]

        cmds.xform(transforms[i], m = finalM)
        cmds.setAttr(transforms[i] +'.scale', finalS[0], finalS[1], finalS[2], type = 'double3')
        #hack to fix joint orient stuff
        if cmds.objectType(transforms[i], isType = 'joint'):
            cmds.setAttr(transforms[i] +'.jointOrient', baseRO[0], baseRO[1], baseRO[2], type = 'double3')
            currentRot = cmds.getAttr(transforms[i] +'.rotate')[0]
            cmds.setAttr(transforms[i] +'.rotate', currentRot[0] - baseRO[0], currentRot[1] - baseRO[1], currentRot[2] - baseRO[2], type = 'double3')


    return True 
Example #20
Source File: BlendTransforms.py    From BlendTransforms with The Unlicense 4 votes vote down vote up
def BT_SetPose(set = None, index = None):
    if not set:
        return False

    if BT_IsSetupConnected(set = set):
        cmds.warning('Disconnect setup first!')
        return False

    if not cmds.attributeQuery('Blend_Node', ex = True, n = set):
        return False

    node = cmds.getAttr(set +'.Blend_Node')
    transforms = cmds.listConnections(set +'.dagSetMembers')
    if not transforms:
        return False

    unitResult = BT_SetUnits()
    if unitResult:
        QtGui.QMessageBox.warning(BT_GetMayaWindow(), "Blend Transforms", "Units set to centimetres.", "Okay")

    for i in range(0, len(transforms)):
        baseM = cmds.getAttr(node +'.transforms[' +str(i) +'].baseMatrix')
        baseS = cmds.getAttr(node +'.transforms[' +str(i) +'].baseScale')[0]
        baseRO = cmds.getAttr(node +'.transforms[' +str(i) +'].baseRotOffset')[0]

        poseM = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
        poseS = [0,0,0]

        if index is not None:
            numPoses = cmds.getAttr(node +'.transforms[0].poses', size = True)
            if not index < numPoses:
                return False 
            poseM = cmds.getAttr(node +'.transforms[' +str(i) +'].poses[' +str(index) +'].matrix')
            poseS = cmds.getAttr(node +'.transforms[' +str(i) +'].poses[' +str(index) +'].scale')[0]

        finalM = [x+y for x, y in zip(poseM, baseM)]
        finalS = [x+y for x, y in zip(poseS, baseS)]

        cmds.xform(transforms[i], m = finalM)
        cmds.setAttr(transforms[i] +'.scale', finalS[0], finalS[1], finalS[2], type = 'double3')
        #hack to fix joint orient stuff
        if cmds.objectType(transforms[i], isType = 'joint'):
            cmds.setAttr(transforms[i] +'.jointOrient', baseRO[0], baseRO[1], baseRO[2], type = 'double3')
            currentRot = cmds.getAttr(transforms[i] +'.rotate')[0]
            cmds.setAttr(transforms[i] +'.rotate', currentRot[0] - baseRO[0], currentRot[1] - baseRO[1], currentRot[2] - baseRO[2], type = 'double3')


    return True 
Example #21
Source File: BlendTransforms.py    From BlendTransforms with The Unlicense 4 votes vote down vote up
def BT_SetPose(set = None, index = None):
    if not set:
        return False

    if BT_IsSetupConnected(set = set):
        cmds.warning('Disconnect setup first!')
        return False

    if not cmds.attributeQuery('Blend_Node', ex = True, n = set):
        return False

    node = cmds.getAttr(set +'.Blend_Node')
    transforms = cmds.listConnections(set +'.dagSetMembers')
    if not transforms:
        return False

    unitResult = BT_SetUnits()
    if unitResult:
        QtGui.QMessageBox.warning(BT_GetMayaWindow(), "Blend Transforms", "Units set to centimetres.", "Okay")

    for i in range(0, len(transforms)):
        baseM = cmds.getAttr(node +'.transforms[' +str(i) +'].baseMatrix')
        baseS = cmds.getAttr(node +'.transforms[' +str(i) +'].baseScale')[0]
        baseRO = cmds.getAttr(node +'.transforms[' +str(i) +'].baseRotOffset')[0]

        poseM = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
        poseS = [0,0,0]

        if index is not None:
            numPoses = cmds.getAttr(node +'.transforms[0].poses', size = True)
            if not index < numPoses:
                return False 
            poseM = cmds.getAttr(node +'.transforms[' +str(i) +'].poses[' +str(index) +'].matrix')
            poseS = cmds.getAttr(node +'.transforms[' +str(i) +'].poses[' +str(index) +'].scale')[0]

        finalM = [x+y for x, y in zip(poseM, baseM)]
        finalS = [x+y for x, y in zip(poseS, baseS)]

        cmds.xform(transforms[i], m = finalM)
        cmds.setAttr(transforms[i] +'.scale', finalS[0], finalS[1], finalS[2], type = 'double3')
        #hack to fix joint orient stuff
        if cmds.objectType(transforms[i], isType = 'joint'):
            cmds.setAttr(transforms[i] +'.jointOrient', baseRO[0], baseRO[1], baseRO[2], type = 'double3')
            currentRot = cmds.getAttr(transforms[i] +'.rotate')[0]
            cmds.setAttr(transforms[i] +'.rotate', currentRot[0] - baseRO[0], currentRot[1] - baseRO[1], currentRot[2] - baseRO[2], type = 'double3')


    return True 
Example #22
Source File: weight.py    From SISideBar with MIT License 4 votes vote down vote up
def joint_label(object, visibility=False):
    '''
    ジョイントラベル設定関数
    object→オブジェクト、リスト形式可
    visibility→ラベルの可視性、省略可能。デフォルトFalse。
    '''
    #ラベリングルールをロードしておく
    left_list_list, right_list_list = load_joint_label_rules()
    
    # リストタイプじゃなかったらリストに変換する
    if not isinstance(object, list):
        temp = object
        object = []
        object.append(temp)
    for skinJoint in object:
        objTypeName = cmds.objectType(skinJoint)
        
        if objTypeName == 'joint':
            split_name = skinJoint.split('|')[-1]
            
            # スケルトン名にLRが含まれているかどうかを判定
            side = 0
            side_name = ''
            for i, (l_list, r_list) in enumerate(zip(left_list_list, right_list_list)):
                for j, lr_list in enumerate([l_list, r_list]):
                    for k, lr in enumerate(lr_list):
                        if i == 0:
                            if re.match(lr, split_name):
                                side = j + 1
                        if i == 1:
                            if re.search(lr, split_name):
                                side = j + 1
                        if i == 2:
                            if re.match(lr[::-1], split_name[::-1]):
                                side = j + 1
                        if side:#対象が見つかってたら全部抜ける
                            side_name = lr
                            break
                    if side:
                        break
                if side:
                    break
            #print 'joint setting :', split_name, side, side_name
            # 左右のラベルを設定、どちらでもないときは中央
            cmds.setAttr(skinJoint + '.side', side)
            # ラベルタイプを”その他”に設定
            cmds.setAttr(skinJoint + '.type', 18)
            new_joint_name = split_name.replace(side_name.replace('.', ''), '')
                
            # スケルトン名設定
            cmds.setAttr(skinJoint + '.otherType', new_joint_name, type='string')
            # 可視性設定
            cmds.setAttr(skinJoint + '.drawLabel', visibility)
        else:
            print(str(skinJoint) + ' : ' + str(objTypeName) + ' Skip Command')
            
#ウェイトのミュートをトグル 
Example #23
Source File: AEsporeNodeTemplate.py    From spore with MIT License 4 votes vote down vote up
def update_instance_list(self, *args):
        """ update the instance listi.
        1. try to get current node based on ae tab name. this failse if the
           nodename is not unique. if this happends...
        2. try to get the node based on last item in selection. this fails
           if not the item is not a spore shape or spore transform.
        this method fails when:
            - two spore locator are parented under the same transform.
            - the user reaches the node interface without selecting the node """

        found = False

        # get current ae tab name
        ae_tabs = mel.eval('$temp = $gAETabLayoutName;')
        tab_index = int(cmds.tabLayout(ae_tabs, q=1, st=1).replace('formTab', ''))
        current_tab = cmds.tabLayout(ae_tabs, q=1, tl=1)[tab_index]

        # try to get node based on selection
        selection = cmds.ls(sl=True, l=True)[-1]
        shapes = cmds.listRelatives(selection, s=True, f=True)

        # check if node name is unique or selection is node
        nodes = cmds.ls(current_tab, l=True)
        if len(nodes) == 1 or cmds.objectType(selection) == 'sporeNode':
            if cmds.objectType(selection) == 'sporeNode':
                self._node = selection
            else:
                self._node = nodes[0]
            found = True

        if len(nodes) > 1:
            if shapes:
                # note: this fails in case there are two spore nodes parented under
                # the same transform
                for i, shape in enumerate(shapes):
                    if cmds.objectType(shape) == 'sporeNode':
                        self._node = shape
                        found = True
            else:
                # TODO - we could also try to catch node based on instancer
                # ae tab name. this would also fail if the instancer name is
                # not unique
                pass

        cmds.textScrollList('instanceList', e=1, removeAll=True)
        if found:
            instanced_geo = node_utils.get_instanced_geo(self._node)
            instanced_geo = ['[{}]: {}'.format(i, name) for i, name in enumerate(instanced_geo)]

            cmds.textScrollList('instanceList', e=1, append=instanced_geo)
        else:
            msg = 'Could not update objects list. Node name "{}" not unique'.format(current_tab)
            self.logger.warn(msg)
            cmds.textScrollList('instanceList', e=1, append=msg.split('. ')) 
Example #24
Source File: dpControls.py    From dpAutoRigSystem with GNU General Public License v2.0 4 votes vote down vote up
def colorShape(self, objList, color, rgb=False, *args):
        """ Create a color override for all shapes from the objList.
        """
        if rgb:
            pass
        elif (dic_colors.has_key(color)):
            iColorIdx = dic_colors[color]
        else:
            iColorIdx = color

        # find shapes and apply the color override:
        shapeTypeList = ['nurbsCurve', 'nurbsSurface', 'mesh', 'subdiv']
        if objList:
            for objName in objList:
                objType = cmds.objectType(objName)
                # verify if the object is the shape type:
                if objType in shapeTypeList:
                    # set override as enable:
                    cmds.setAttr(objName+".overrideEnabled", 1)
                    # set color override:
                    if rgb:
                        cmds.setAttr(objName+".overrideRGBColors", 1)
                        cmds.setAttr(objName+".overrideColorR", color[0])
                        cmds.setAttr(objName+".overrideColorG", color[1])
                        cmds.setAttr(objName+".overrideColorB", color[2])
                    else:
                        cmds.setAttr(objName+".overrideRGBColors", 0)
                        cmds.setAttr(objName+".overrideColor", iColorIdx)
                # verify if the object is a transform type:
                elif objType == "transform":
                    # find all shapes children of the transform object:
                    shapeList = cmds.listRelatives(objName, shapes=True, children=True, fullPath=True)
                    if shapeList:
                        for shape in shapeList:
                            # set override as enable:
                            cmds.setAttr(shape+".overrideEnabled", 1)
                            # set color override:
                            if rgb:
                                cmds.setAttr(shape+".overrideRGBColors", 1)
                                cmds.setAttr(shape+".overrideColorR", color[0])
                                cmds.setAttr(shape+".overrideColorG", color[1])
                                cmds.setAttr(shape+".overrideColorB", color[2])
                            else:
                                cmds.setAttr(shape+".overrideRGBColors", 0)
                                cmds.setAttr(shape+".overrideColor", iColorIdx) 
Example #25
Source File: dpFacialControl.py    From dpAutoRigSystem with GNU General Public License v2.0 4 votes vote down vote up
def dpCreateRemapNode(self, fromNode, fromAttr, toNodeBaseName, toNode, toAttr, number, sizeFactor, oMin=0, oMax=1, iMin=0, iMax=1, *args):
        """ Creates the nodes to remap values and connect it to final output (toNode) item.
        """
        fromNodeName = utils.extractSuffix(fromNode)
        remap = cmds.createNode("remapValue", name=fromNodeName+"_"+fromAttr+"_"+str(number).zfill(2)+"_"+toAttr.upper()+"_RmV")
        outMaxAttr = toNodeBaseName+"_"+str(number).zfill(2)+"_"+toAttr.upper()
        if "t" in toAttr:
            if not cmds.objExists(fromNode+".sizeFactor"):
                cmds.addAttr(fromNode, longName="sizeFactor", attributeType="float", defaultValue=sizeFactor, keyable=False)
            cmds.addAttr(fromNode, longName=outMaxAttr, attributeType="float", defaultValue=oMax, keyable=False)
            md = cmds.createNode("multiplyDivide", name=fromNodeName+"_"+fromAttr+"_"+str(number).zfill(2)+"_"+toAttr.upper()+"_SizeFactor_MD")
            cmds.connectAttr(fromNode+"."+outMaxAttr, md+".input1X", force=True)
            cmds.connectAttr(fromNode+".sizeFactor", md+".input2X", force=True)
            cmds.connectAttr(md+".outputX", remap+".outputMax", force=True)
        else:
            cmds.addAttr(fromNode, longName=outMaxAttr, attributeType="float", defaultValue=oMax, keyable=False)
            cmds.connectAttr(fromNode+"."+outMaxAttr, remap+".outputMax", force=True)
        cmds.setAttr(remap+".inputMin", iMin)
        cmds.setAttr(remap+".inputMax", iMax)
        cmds.setAttr(remap+".outputMin", oMin)
        cmds.connectAttr(fromNode+"."+fromAttr, remap+".inputValue", force=True)
        # check if there's an input connection and create a plusMinusAverage if we don't have one to connect in:
        connectedList = cmds.listConnections(toNode+"."+toAttr, destination=False, source=True, plugs=False)
        if connectedList:
            if cmds.objectType(connectedList[0]) == "plusMinusAverage":
                inputList = cmds.listConnections(connectedList[0]+".input1D", destination=False, source=True, plugs=False)
                cmds.connectAttr(remap+".outValue", connectedList[0]+".input1D["+str(len(inputList))+"]", force=True)
            else:
                if cmds.objectType(connectedList[0]) == "unitConversion":
                    connectedAttr = cmds.listConnections(connectedList[0]+".input", destination=False, source=True, plugs=True)[0]
                else:
                    connectedAttr = cmds.listConnections(toNode+"."+toAttr, destination=False, source=True, plugs=True)[0]
                pma = cmds.createNode("plusMinusAverage", name=toNode+"_"+toAttr.upper()+"_PMA")
                cmds.connectAttr(connectedAttr, pma+".input1D[0]", force=True)
                cmds.connectAttr(remap+".outValue", pma+".input1D[1]", force=True)
                cmds.connectAttr(pma+".output1D", toNode+"."+toAttr, force=True)
                if cmds.objectType(connectedList[0]) == "unitConversion":
                    cmds.delete(connectedList[0])
        else:
            cmds.connectAttr(remap+".outValue", toNode+"."+toAttr, force=True)