Python maya.cmds 模块,attributeQuery() 实例源码

我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用maya.cmds.attributeQuery()

项目:config    作者:mindbender-studio    | 项目源码 | 文件源码
def set_defaults(*args):
    """Set currently selected values from channel box to their default value

    If no channel is selected, default all keyable attributes.

    """

    for node in cmds.ls(selection=True):
        selected_channels = read_selected_channels()
        for channel in (selected_channels or
                        cmds.listAttr(node, keyable=True)):
            try:
                default = cmds.attributeQuery(channel,
                                              node=node,
                                              listDefault=True)[0]
            except Exception:
                continue

            else:
                cmds.setAttr(node + "." + channel, default)
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
def loadSelectedSet(self):
        selection = BT_GetSelectedSet()
        if not selection:
            return False

        if not cmds.attributeQuery('Blend_Node', ex = True, n = selection):
            cmds.warning('Blend_Node attribute not found! This set might not be connected to a BlendTransforms node yet.')
            return False

        self.ui.poseList.clear()
        self.ui.setEdit.setText(selection)

        poses = BT_GetPosesFromSet(selection)
        if not poses:
            return False

        self.ui.poseList.addItems(poses)
        return True
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
def loadSelectedSet(self):
        selection = BT_GetSelectedSet()
        if not selection:
            return False

        if not cmds.attributeQuery('Blend_Node', ex = True, n = selection):
            cmds.warning('Blend_Node attribute not found! This set might not be connected to a BlendTransforms node yet.')
            return False

        self.ui.poseList.clear()
        self.ui.setEdit.setText(selection)

        poses = BT_GetPosesFromSet(selection)
        if not poses:
            return False

        self.ui.poseList.addItems(poses)
        return True
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
def loadSelectedSet(self):
        selection = BT_GetSelectedSet()
        if not selection:
            return False

        if not cmds.attributeQuery('Blend_Node', ex = True, n = selection):
            cmds.warning('Blend_Node attribute not found! This set might not be connected to a BlendTransforms node yet.')
            return False

        self.ui.poseList.clear()
        self.ui.setEdit.setText(selection)

        poses = BT_GetPosesFromSet(selection)
        if not poses:
            return False

        self.ui.poseList.addItems(poses)
        return True
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def getObj(*args):
    #get selection and put it in the widgets["objTFG"]
    clearList()
    sel = cmds.ls(sl=True, type="transform")
    if (sel and (len(sel)==1)):
        cmds.textFieldGrp(widgets["objTFG"], e=True, tx=sel[0])
    else:
        cmds.warning("you must select one object with the \"follow\" attribute")

    #------------maybe add attr onto end of obj text, then you don't have to get it later if you needed to ???

    #now create a button for each value in the "follow" attr
    #channels = cmds.channelBox ('mainChannelBox', query=True, selectedMainAttributes=True)
    enumValueStr = cmds.attributeQuery("follow", node=sel[0], listEnum=True)[0]
    values = enumValueStr.split(":")

    for i in range(0,len(values)):
        #pick a random color?
        r = random.uniform(0.5,1)
        g = random.uniform(0.5,1)
        b = random.uniform(0.5,1)
        color = (r, g, b)

        #here create the button
        cmds.button(l=values[i], w=125, p=widgets["bottomRCLO"], bgc=color, h=50, c=partial(switchMatchSpace, i))
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def randomizeFloats(*args):
    sel = cmds.ls(sl=True)
    attrs = getChannels()

    minn = cmds.floatFieldGrp(widgets["floatFFG"], q=True, v1=True)
    maxx = cmds.floatFieldGrp(widgets["floatFFG"], q=True, v2=True)
    rel = cmds.checkBox(widgets["floatCB"], q=True, v=True)

    for obj in sel:
        for attr in attrs:
            if (cmds.attributeQuery(attr, node=obj, exists=True)):
                rand = getRandomFloat(minn, maxx)
                current = 0.0
                if rel:
                    current = cmds.getAttr("{0}.{1}".format(obj, attr))
                newVal = rand + current
                cmds.setAttr("{0}.{1}".format(obj, attr), newVal)
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def get_channel_attributes(obj, chnl):
    """
    gets and returns attributes of given channel on given object
    """
    attrType = cmds.attributeQuery(chnl, node=obj, at=True)
    hasMin = cmds.attributeQuery(chnl, node=obj, mne=True)
    hasMin = cmds.attributeQuery(chnl, node=obj, mne=True)
    hasMax = cmds.attributeQuery(chnl, node=obj, mxe=True)
    attrMin = None
    if hasMin:
        attrMin = cmds.attributeQuery(chnl, node=obj, min=True)
    attrMax = None
    if hasMax:
        attrMax = cmds.attributeQuery(chnl, node=obj, max=True)
    value = cmds.getAttr("{0}.{1}".format(obj, chnl))
    inConnection = cmds.listConnections("{0}.{1}".format(obj, chnl), plugs=True, destination=False, source=True)
    outConnection = cmds.listConnections("{0}.{1}".format(obj, chnl), plugs=True, destination=True, source=False)
    locked = cmds.getAttr("{0}.{1}".format(obj, chnl), lock=True)

    return (attrType, hasMin, attrMin, hasMax, attrMax, value, inConnection, outConnection, locked)
项目:gozbruh    作者:LumaPictures    | 项目源码 | 文件源码
def create(obj):
    """Tell ZBrush to treat `obj` as a new object.

    Under the hood this changes a gozbruhBrush ID to match object name.
    """
    # does not change selection:
    cmds.delete(obj, constructionHistory=True)
    shape = cmds.ls(obj, type='mesh', dag=True)[0]
    xform = cmds.listRelatives(shape, parent=True, fullPath=True)[0]
    goz_check_xform = cmds.attributeQuery(
        'gozbruhBrushID', node=xform, exists=True)
    goz_check_shape = cmds.attributeQuery(
        'gozbruhBrushID', node=shape, exists=True)

    if goz_check_shape:
        cmds.setAttr(shape + '.gozbruhBrushID', obj, type='string')
    if goz_check_xform:
        cmds.setAttr(xform + '.gozbruhBrushID', obj, type='string')
    return xform
项目:pw_mGeoExporter    作者:paulwinex    | 项目源码 | 文件源码
def getAttribFromNode(self, name, attr, aType, default=None):
        #name mast be shape
        transformOnly = ['visibility']
        fAttr = '.'.join([name, attr])
        value = default
        if cmds.attributeQuery( attr, node=name, exists=True ) and not attr.lower() in transformOnly:
            value = cmds.getAttr( fAttr )
        else:
            trnsfrm = self.getTransform(name)
            if trnsfrm:
                if cmds.attributeQuery( attr, node=trnsfrm, exists=True ):
                    fAttr = '.'.join([trnsfrm, attr])
                    value = cmds.getAttr( fAttr )
        if not value is None:
            if isinstance(value, list):
                if isinstance(value[0], tuple):
                    value = list(value[0])
            try:
                value = aType(value)
            except:
                pass
        return value
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def getRootAndCOM(node):
    '''
    Given either the root or COM, return root and COM based on connections.
    '''

    com = None
    root = None

    if mc.attributeQuery(COM_ATTR, node=node, exists=True):
        com = node
        messageCon = mc.listConnections(com+'.'+COM_ATTR, source=True, destination=False)
        if not messageCon:
            raise RuntimeError('Could not determine root from COM, please select root and run again.')
        root = messageCon[0]
    else:
        messageCon = mc.listConnections(node+'.message', source=False, destination=True, plugs=True)
        if messageCon:
            for each in messageCon:
                eachNode, attr = each.rsplit('.',1)
                if attr == COM_ATTR:
                    com = eachNode
                    root = node
                    break

    return root, com
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def isNodeVisible(node):
    '''
    Simply return whether or not the node can be seen.
    '''

    if not mc.attributeQuery('visibility', node=node, exists=True):
        return False
    if not mc.getAttr(node+'.v'):
        return False
    if mc.attributeQuery('intermediateObject', node=node, exists=True):
        if mc.getAttr(node+'.intermediateObject'):
            return False
    if not mc.getAttr(node+'.lodVisibility'):
        return False
    if mc.getAttr(node+'.overrideEnabled') and not mc.getAttr(node+'.overrideVisibility'):
        return False

    parent = mc.listRelatives(node, parent=True, pa=True)
    if parent:
        return isNodeVisible(parent[0])
    return True
项目:TACTIC-Handler    作者:listyque    | 项目源码 | 文件源码
def set_info_to_scene(search_key, context):
    # add info about particular scene
    skey_link = 'skey://{0}&context={1}'.format(search_key, context)
    if not cmds.attributeQuery('tacticHandler_skey', node='defaultObjectSet', exists=True):
        cmds.addAttr('defaultObjectSet', longName='tacticHandler_skey', dataType='string')
    cmds.setAttr('defaultObjectSet.tacticHandler_skey', skey_link, type='string')
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
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
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
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
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
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
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def doSpaceMatch(*args):

    #check for correct attrs
    obj = cmds.textFieldButtonGrp(widgets["objTFG"], q=True, tx=True)


   #look for message attr re: constraint
    if (cmds.attributeQuery("spaceConstraint", node=obj, exists=True)):
        constraint = cmds.listConnections("%s.spaceConstraint"%obj)
    else:
        cmds.warning("this object has no \"spaceConstraint\" message attribute and thus is not set up for this matching")

    #----------look for string attributes for weights of constraints



    #get ws pos of obj before
    ws1Pos = cmds.xform(obj, q=True, ws=True, t=True)
    ws1Rot = cmds.xform(obj, q=True, ws=True, ro=True)

    #pull the constraint info from the message and string attrs
    #attr = cmds.listAttr(sel,ud=True )

    #-----------here just key the space value!!!
    #switch the spaces, set up "cases", i.e. if world, then set all to 0 except world, etc
    cmds.setAttr("group1_parentConstraint1.pCube1W0", 0)
    cmds.setAttr("group1_parentConstraint1.pCube2W1", 1)

    #set ws pos, rot of obj after
    cmds.xform(obj, ws=True, t=ws1Pos)
    cmds.xform(obj, ws=True, ro=ws1Rot)

    #add in scriptjob?

    #-----------try this
    #set up constraints as normal, maybe DO NOT have to moniter them specifically, set them up as SDKs
    #constraint goes in as message mapped "spaceConstraint"
    #create string attrs for constraint, each space attrname = space , attrVal = constraintAttr(ie. nameW1)
    #Create one tab to set it up
    #creat one tab to do it - get spaces
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def multiplyFloats(*args):
    sel = cmds.ls(sl=True)
    attrs = getChannels()

    mult = cmds.floatFieldGrp(widgets["multFFG"], q=True, v1=True)

    for obj in sel:
        for attr in attrs:
            if (cmds.attributeQuery(attr, node=obj, exists=True)):
                current = cmds.getAttr("{0}.{1}".format(obj, attr))
                newVal = current * mult
                cmds.setAttr("{0}.{1}".format(obj, attr), newVal)
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def transfer_attrs(*args):
    """
    transfers attrs and connections from second obj to first object selected 
    """
    tgt, src = get_source_and_targets()
    if not tgt or len(src) > 1:
        cmds.warning("Select only one target then one source obj to transfer the attributes and connections!")
        return ()

    attrs = cmds.channelBox('mainChannelBox', q=True, selectedMainAttributes=True)
    if not attrs:
        cmds.warning("You have to select at least one attr on last object selected to transfer!")
        return ()
    for attr in attrs:
        attrType, hasMin, attrMin, hasMax, attrMax, value, inConnection, outConnection, locked = get_channel_attributes(
            src[0], attr)
        if not attrType == "enum":
            # create attribute
            if not cmds.attributeQuery(attr, node=tgt, exists=True):
                if hasMin and not hasMax:
                    cmds.addAttr(tgt, ln=attr, at=attrType, min=attrMin[0], dv=value, k=True)
                elif hasMax and not hasMin:
                    cmds.addAttr(tgt, ln=attr, at=attrType, max=attrMax[0], dv=value, k=True)
                elif hasMin and hasMax:
                    cmds.addAttr(tgt, ln=attr, at=attrType, min=attrMin[0], max=attrMax[0], dv=value, k=True)
                else:
                    cmds.addAttr(tgt, ln=attr, at=attrType, dv=value, k=True)
            else:
                cmds.warning("The attribute: {0} already exists. Skipping creation!".format(attr))
            # lock
            if locked:
                cmds.setAttr("{0}.{1}".format(tgt, attr), l=True)
        else:
            cmds.warning("I don't do enums at the moment!")

        # connect tgt attr to connection, forced
        if inConnection:
            cmds.connectAttr(inConnection[0], "{0}.{1}".format(tgt, attr))
        if outConnection:
            for conn in outConnection:
                cmds.connectAttr("{0}.{1}".format(tgt, attr), conn, force=True)
项目:gozbruh    作者:LumaPictures    | 项目源码 | 文件源码
def load(file_path, obj_name, parent_name):
    """Import a file exported from ZBrush.

    This is the command sent over the Maya command port from ZBrush.

    Parameters
    ----------
    file_path : str
        Path to the file that we are importing
    obj_name : str
        Name of the object being imported
    parent_name : str
        Name of the parent for the object being imported
    """
    file_name = utils.split_file_name(file_path)
    _cleanup(file_name)
    cmds.file(file_path, i=True,
              usingNamespaces=False,
              removeDuplicateNetworks=True)

    # Set smoothing options if necessary
    if cmds.optionVar(ex='gozbruh_smooth') and not cmds.optionVar(q='gozbruh_smooth'):
        cmds.displaySmoothness(obj_name, du=0, dv=0, pw=4, ps=1, po=1)

    if not cmds.attributeQuery("gozbruhParent", n=obj_name, ex=True):
        cmds.addAttr(obj_name, longName='gozbruhParent', dataType='string')
    cmds.setAttr(obj_name + '.gozbruhParent', parent_name, type='string')
项目:pw_mGeoExporter    作者:paulwinex    | 项目源码 | 文件源码
def getMaterialName(self, sg):
        mat = cmds.listConnections(sg + ".surfaceShader")
        if not mat:
            if cmds.attributeQuery("miMaterialShader",n=sg, ex=1):
                mat = cmds.listConnections(sg + ".miMaterialShader")
            if not mat:
                return 'noShader'
        if self.op['expgeogrp_mtl'][1]:
            tok = self.tokenPrefix(self.op['expgeogrp_mtl'][1])
            for t in tok:
                if t in mat[0]:
                    return mat[0]
            return self.textVariables['defShader']
        return mat[0]
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def getNodesOfTypeBelow(node, nodeType):
    nodes = []
    allKids = mc.listRelatives(node, ad=True, pa=True)
    for kid in allKids:
        if mc.attributeQuery(PUP_ID_PREFIX+nodeType, exists=True, node=kid):
            nodes.append(kid)
    return nodes
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def getTag(node, tag):

    ntAttr = PUP_ID_PREFIX+tag
    if mc.attributeQuery(ntAttr, exists=True, node=node):
        return mc.getAttr(node+'.'+ntAttr)
    return False
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def showAllControls(puppet, *args):

    elements = mc.listRelatives(puppet, pa=True)
    for element in elements:
        for visAttr in ('geoVisibility','controlVisibility','secondaryControlVisibility'):
            if mc.attributeQuery(visAttr, exists=True, node=element):
                mc.setAttr(element+'.'+visAttr, 1)
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def isNodePuppetControl(node):

    if mc.attributeQuery(PUP_ID_PREFIX+'nodeType', exists=True, node=node):
        return True
    if getNodeType(node) == 'control':
        return True
    return False
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def getSpaceSwitchData(node):

    data = {}

    attrs = mc.listAttr(node, userDefined=True, keyable=True)

    if not attrs:
        return data

    ssAttrs = [x for x in attrs if 'paceSwitch' in x]
    for attr in ssAttrs:
        enumValues = []
        spaceEnum = 'space'
        if attr == 'spaceSwitch':
            if not 'space' in attrs:
                spaceEnum = 'spaceSwitch'
            enumValues = mc.attributeQuery(spaceEnum, node=node, listEnum=True)
        elif 'SpaceSwitch' in attr:
            baseName = attr.replace('SpaceSwitch','')
            if baseName + 'Space' in attrs:
                spaceEnum = baseName+'Space'
            else:
                spaceEnum = attr
            if spaceEnum in attrs and mc.attributeQuery(spaceEnum, node=node, attributeType=True) == 'enum':
                enumValues = mc.attributeQuery(spaceEnum, node=node, listEnum=True)
        if not enumValues:
            continue
        data[attr] = {}
        data[attr]['enumValues'] = enumValues[0].split(':')
        data[attr]['currentValue'] = mc.getAttr(node+'.'+spaceEnum, asString=True)

    return data
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def getMirrorAxis(node):

    axis = []
    if mc.attributeQuery('mirrorAxis', exists=True, node=node):        
        mirrorAxis = mc.getAttr('{}.mirrorAxis'.format(node))
        if mirrorAxis and not hasFlippedParent(node):
            axis = mirrorAxis.split(',')
    return axis
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def copyPose(fromNode, toNode, flip=False):

    attrs = mc.listAttr(fromNode, keyable=True)
    if not attrs:
        return

    #if attributes are aliased, get the real names for mirroring axis
    aliases = mc.aliasAttr(fromNode, query=True)
    if aliases:
        for alias,real in zip(aliases[::2],aliases[1::2]):
            if alias in attrs:
                attrs.remove(alias)
                attrs.append(real)

    axis = getMirrorAxis(toNode)

    for attr in attrs:
        if attr == 'mirrorAxis':
            continue
        if not mc.attributeQuery(attr, node=toNode, exists=True):
            continue
        fromPlug = '{}.{}'.format(fromNode, attr)
        toPlug = '{}.{}'.format(toNode, attr)
        fromValue = mc.getAttr(fromPlug)
        toValue = mc.getAttr(toPlug)

        if attr in axis:
            fromValue *= -1.0
            toValue *= -1.0

        try:
            utl.setAnimValue(toPlug, fromValue)
        except:pass

        if flip:
            try:
                utl.setAnimValue(fromPlug, toValue)
            except:pass
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def editPivot(self, *args):
        sel = mc.ls(sl=True)

        if not sel:
            om.MGlobal.displayWarning('Nothing selected.')
            return

        if len(sel) > 1:
            om.MGlobal.displayWarning('Only works on one node at a time.')
            return

        if mc.attributeQuery('ml_pivot_handle', exists=True, node=sel[0]):
            #we have a pivot handle selected
            return

        self.node = sel[0]

        if is_pivot_connected(sel[0]):
            driverAttr = pivot_driver_attr(sel[0])
            if driverAttr:
                self.editPivotDriver(driverAttr)
            else:
                om.MGlobal.displayWarning('Pivot attribute is connected, unable to edit.') 
            return

        self.editPivotHandle()
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def editPivotDriver(self, driver):

        self.pivotDriver = driver

        #get driver range
        node,attr = driver.split('.',1)
        value = mc.getAttr(driver)

        minValue = mc.attributeQuery(attr, node=node, minimum=True)[0]
        maxValue = mc.attributeQuery(attr, node=node, maximum=True)[0]

        #create a ui with a slider
        self.pivotDriverWindow = 'ml_pivot_editPivotDriverUI'

        if mc.window(self.pivotDriverWindow, exists=True):
            mc.deleteUI(self.pivotDriverWindow)
        window = mc.window(self.pivotDriverWindow, width=1, height=1)
        mc.columnLayout()
        self.floatSlider = mc.floatSliderButtonGrp(label=attr, 
                                                   field=True, 
                                                   value=value, 
                                                   buttonLabel='Bake', 
                                                   minValue=minValue, 
                                                   maxValue=maxValue, 
                                                   buttonCommand=self.doEditPivotDriver )
        mc.showWindow( window )
        mc.window(self.pivotDriverWindow, edit=True, width=1, height=1)
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def channelBox(*args):

    channels = utl.getSelectedChannels()
    if not channels:
        return

    sel = mc.ls(sl=True)
    clear()
    for each in sel:
        for c in channels:
            if mc.attributeQuery(c, node=each, exists=True):
                mc.selectionConnection('graphEditor1FromOutliner', edit=True, select=each+'.'+c)
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def main(selectedChannels=True, transformsOnly=False, excludeChannels=None):
    '''
    Resets selected channels in the channel box to default, or if nothing's
    selected, resets all keyable channels to default.
    '''
    gChannelBoxName = mm.eval('$temp=$gChannelBoxName')

    sel = mc.ls(sl=True)
    if not sel:
        return

    if excludeChannels and not isinstance(excludeChannels, (list, tuple)):
        excludeChannels = [excludeChannels]

    chans = None
    if selectedChannels:
        chans = mc.channelBox(gChannelBoxName, query=True, sma=True)

    testList = ['translateX','translateY','translateZ','rotateX','rotateY','rotateZ','scaleX','scaleY','scaleZ',
                'tx','ty','yz','rx','ry','rz','sx','sy','sz']
    for obj in sel:
        attrs = chans
        if not chans:
            attrs = mc.listAttr(obj, keyable=True, unlocked=True)
            if excludeChannels:
                attrs = [x for x in attrs if x not in excludeChannels]
        if transformsOnly:
            attrs = [x for x in attrs if x in testList]
        if attrs:
            for attr in attrs:
                try:
                    default = mc.attributeQuery(attr, listDefault=True, node=obj)[0]
                    mc.setAttr(obj+'.'+attr, default)
                except StandardError:
                    pass

    utl.deselectChannels()
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
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
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
def BT_DeletePose(set = None, poseIndex = None):

    if not set or poseIndex is None:
        return False

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

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

    blendNode = cmds.getAttr(set +'.Blend_Node')

    if not cmds.objExists(blendNode) or not cmds.objExists(set):
        return False

    numTransforms = cmds.getAttr(blendNode +'.transforms', size = True)

    if not numTransforms:
        return False

    numPoses = cmds.getAttr(blendNode +'.transforms[0].poses', size = True) 
    allUserDefined = cmds.listAttr(set, ud = True)
    btUserDefined = [x for x in allUserDefined if x.startswith('BT_')]

    if poseIndex >= numPoses:
        return False

    connectionsToBreak = cmds.listConnections(set +'.' +btUserDefined[poseIndex], d = True, s = False, p = True)
    for ctb in connectionsToBreak:
        cmds.disconnectAttr(set +'.' +btUserDefined[poseIndex], ctb)
    cmds.deleteAttr(set +'.' +btUserDefined[poseIndex])

    for i in range(0, numTransforms):
        for p in range(poseIndex, numPoses-1):
            #get the next items vales
            matrix = cmds.getAttr(blendNode +'.transforms[' +str(i) +'].poses[' +str(p+1) +'].matrix')
            scale = cmds.getAttr(blendNode +'.transforms[' +str(i) +'].poses[' +str(p+1) +'].scale')[0]
            conn = cmds.listConnections(blendNode +'.transforms[' +str(i) +'].poses[' +str(p+1) +'].weight', s = True, d = False, p = True)[0]

            cmds.setAttr(blendNode +'.transforms[' +str(i) +'].poses[' +str(p) +'].matrix', matrix, type = 'matrix')
            cmds.setAttr(blendNode +'.transforms[' +str(i) +'].poses[' +str(p) +'].scale', scale[0], scale[1], scale[2], type = 'double3')
            cmds.connectAttr(conn, blendNode +'.transforms[' +str(i) +'].poses[' +str(p) +'].weight', force = True)
            cmds.disconnectAttr(conn, blendNode +'.transforms[' +str(i) +'].poses[' +str(p+1) +'].weight')

    return True
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
def BT_AddPose(set = None, poseName = '', index = None):

    prefixedPoseName = 'BT_' +poseName

    if not set:
        return False

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

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

    blendNode = cmds.getAttr(set +'.Blend_Node')

    if not cmds.objExists(blendNode) or not cmds.objExists(set):
        return False

    if cmds.attributeQuery(prefixedPoseName, ex = True, n = set):
        return False

    transforms = cmds.listConnections(set +'.dagSetMembers')

    numTransforms = len(transforms)
    poseIndex = cmds.getAttr(blendNode +'.transforms[0].poses', size = True) 

    if index is not None:
        poseIndex = index

    if index is None:
        cmds.addAttr(set, ln = prefixedPoseName, nn = poseName,  k = True, min = 0, max = 1.0, at = 'double')

    # print ('Num poses = ' +str(numPoses))
    for i in range(0, numTransforms):
        #get the base matrix
        baseScale = cmds.getAttr(blendNode +'.transforms[' +str(i) +'].baseScale')[0]
        baseMatrix = cmds.getAttr(blendNode +'.transforms[' +str(i) +'].baseMatrix')

        #store the scale and set it 
        transformScale = cmds.getAttr(transforms[i] +'.scale')[0]

        #set the scale back to 1.0
        cmds.setAttr(transforms[i] +'.scale', 1.0, 1.0, 1.0, type = 'double3')
        transformMatrix = cmds.xform(transforms[i], q = True, m = True)

        poseMatrix = [x-y for x, y in zip(transformMatrix, baseMatrix)]
        poseScale = [x-y for x, y in zip(transformScale, baseScale)]

        #set the scale back to what the user had it at
        cmds.setAttr(transforms[i] +'.scale', transformScale[0], transformScale[1], transformScale[2], type = 'double3')
        cmds.setAttr(blendNode +'.transforms[' +str(i) +'].poses[' +str(poseIndex) +'].matrix', poseMatrix, type = 'matrix')
        BT_Double3ValuesToNode(values = poseScale, node = blendNode, attr = 'transforms[' +str(i) +'].poses[' +str(poseIndex) +'].scale' )

        if index is None:
            cmds.connectAttr(set +'.' +prefixedPoseName, blendNode +'.transforms[' +str(i) +'].poses[' +str(poseIndex) +'].weight')

    return True
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
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
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
def BT_DeletePose(set = None, poseIndex = None):

    if not set or poseIndex is None:
        return False

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

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

    blendNode = cmds.getAttr(set +'.Blend_Node')

    if not cmds.objExists(blendNode) or not cmds.objExists(set):
        return False

    numTransforms = cmds.getAttr(blendNode +'.transforms', size = True)

    if not numTransforms:
        return False

    numPoses = cmds.getAttr(blendNode +'.transforms[0].poses', size = True) 
    allUserDefined = cmds.listAttr(set, ud = True)
    btUserDefined = [x for x in allUserDefined if x.startswith('BT_')]

    if poseIndex >= numPoses:
        return False

    connectionsToBreak = cmds.listConnections(set +'.' +btUserDefined[poseIndex], d = True, s = False, p = True)
    for ctb in connectionsToBreak:
        cmds.disconnectAttr(set +'.' +btUserDefined[poseIndex], ctb)
    cmds.deleteAttr(set +'.' +btUserDefined[poseIndex])

    for i in range(0, numTransforms):
        for p in range(poseIndex, numPoses-1):
            #get the next items vales
            matrix = cmds.getAttr(blendNode +'.transforms[' +str(i) +'].poses[' +str(p+1) +'].matrix')
            scale = cmds.getAttr(blendNode +'.transforms[' +str(i) +'].poses[' +str(p+1) +'].scale')[0]
            conn = cmds.listConnections(blendNode +'.transforms[' +str(i) +'].poses[' +str(p+1) +'].weight', s = True, d = False, p = True)[0]

            cmds.setAttr(blendNode +'.transforms[' +str(i) +'].poses[' +str(p) +'].matrix', matrix, type = 'matrix')
            cmds.setAttr(blendNode +'.transforms[' +str(i) +'].poses[' +str(p) +'].scale', scale[0], scale[1], scale[2], type = 'double3')
            cmds.connectAttr(conn, blendNode +'.transforms[' +str(i) +'].poses[' +str(p) +'].weight', force = True)
            cmds.disconnectAttr(conn, blendNode +'.transforms[' +str(i) +'].poses[' +str(p+1) +'].weight')

    return True
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
def BT_AddPose(set = None, poseName = '', index = None):

    prefixedPoseName = 'BT_' +poseName

    if not set:
        return False

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

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

    blendNode = cmds.getAttr(set +'.Blend_Node')

    if not cmds.objExists(blendNode) or not cmds.objExists(set):
        return False

    if cmds.attributeQuery(prefixedPoseName, ex = True, n = set):
        return False

    transforms = cmds.listConnections(set +'.dagSetMembers')

    numTransforms = len(transforms)
    poseIndex = cmds.getAttr(blendNode +'.transforms[0].poses', size = True) 

    if index is not None:
        poseIndex = index

    if index is None:
        cmds.addAttr(set, ln = prefixedPoseName, nn = poseName,  k = True, min = 0, max = 1.0, at = 'double')

    # print ('Num poses = ' +str(numPoses))
    for i in range(0, numTransforms):
        #get the base matrix
        baseScale = cmds.getAttr(blendNode +'.transforms[' +str(i) +'].baseScale')[0]
        baseMatrix = cmds.getAttr(blendNode +'.transforms[' +str(i) +'].baseMatrix')

        #store the scale and set it 
        transformScale = cmds.getAttr(transforms[i] +'.scale')[0]

        #set the scale back to 1.0
        cmds.setAttr(transforms[i] +'.scale', 1.0, 1.0, 1.0, type = 'double3')
        transformMatrix = cmds.xform(transforms[i], q = True, m = True)

        poseMatrix = [x-y for x, y in zip(transformMatrix, baseMatrix)]
        poseScale = [x-y for x, y in zip(transformScale, baseScale)]

        #set the scale back to what the user had it at
        cmds.setAttr(transforms[i] +'.scale', transformScale[0], transformScale[1], transformScale[2], type = 'double3')
        cmds.setAttr(blendNode +'.transforms[' +str(i) +'].poses[' +str(poseIndex) +'].matrix', poseMatrix, type = 'matrix')
        BT_Double3ValuesToNode(values = poseScale, node = blendNode, attr = 'transforms[' +str(i) +'].poses[' +str(poseIndex) +'].scale' )

        if index is None:
            cmds.connectAttr(set +'.' +prefixedPoseName, blendNode +'.transforms[' +str(i) +'].poses[' +str(poseIndex) +'].weight')

    return True
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
def BT_DeletePose(set = None, poseIndex = None):

    if not set or poseIndex is None:
        return False

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

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

    blendNode = cmds.getAttr(set +'.Blend_Node')

    if not cmds.objExists(blendNode) or not cmds.objExists(set):
        return False

    numTransforms = cmds.getAttr(blendNode +'.transforms', size = True)

    if not numTransforms:
        return False

    numPoses = cmds.getAttr(blendNode +'.transforms[0].poses', size = True) 
    allUserDefined = cmds.listAttr(set, ud = True)
    btUserDefined = [x for x in allUserDefined if x.startswith('BT_')]

    if poseIndex >= numPoses:
        return False

    connectionsToBreak = cmds.listConnections(set +'.' +btUserDefined[poseIndex], d = True, s = False, p = True)
    for ctb in connectionsToBreak:
        cmds.disconnectAttr(set +'.' +btUserDefined[poseIndex], ctb)
    cmds.deleteAttr(set +'.' +btUserDefined[poseIndex])

    for i in range(0, numTransforms):
        for p in range(poseIndex, numPoses-1):
            #get the next items vales
            matrix = cmds.getAttr(blendNode +'.transforms[' +str(i) +'].poses[' +str(p+1) +'].matrix')
            scale = cmds.getAttr(blendNode +'.transforms[' +str(i) +'].poses[' +str(p+1) +'].scale')[0]
            conn = cmds.listConnections(blendNode +'.transforms[' +str(i) +'].poses[' +str(p+1) +'].weight', s = True, d = False, p = True)[0]

            cmds.setAttr(blendNode +'.transforms[' +str(i) +'].poses[' +str(p) +'].matrix', matrix, type = 'matrix')
            cmds.setAttr(blendNode +'.transforms[' +str(i) +'].poses[' +str(p) +'].scale', scale[0], scale[1], scale[2], type = 'double3')
            cmds.connectAttr(conn, blendNode +'.transforms[' +str(i) +'].poses[' +str(p) +'].weight', force = True)
            cmds.disconnectAttr(conn, blendNode +'.transforms[' +str(i) +'].poses[' +str(p+1) +'].weight')

    return True
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
def BT_AddPose(set = None, poseName = '', index = None):

    prefixedPoseName = 'BT_' +poseName

    if not set:
        return False

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

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

    blendNode = cmds.getAttr(set +'.Blend_Node')

    if not cmds.objExists(blendNode) or not cmds.objExists(set):
        return False

    if cmds.attributeQuery(prefixedPoseName, ex = True, n = set):
        return False

    transforms = cmds.listConnections(set +'.dagSetMembers')

    numTransforms = len(transforms)
    poseIndex = cmds.getAttr(blendNode +'.transforms[0].poses', size = True) 

    if index is not None:
        poseIndex = index

    if index is None:
        cmds.addAttr(set, ln = prefixedPoseName, nn = poseName,  k = True, min = 0, max = 1.0, at = 'double')

    # print ('Num poses = ' +str(numPoses))
    for i in range(0, numTransforms):
        #get the base matrix
        baseScale = cmds.getAttr(blendNode +'.transforms[' +str(i) +'].baseScale')[0]
        baseMatrix = cmds.getAttr(blendNode +'.transforms[' +str(i) +'].baseMatrix')

        #store the scale and set it 
        transformScale = cmds.getAttr(transforms[i] +'.scale')[0]

        #set the scale back to 1.0
        cmds.setAttr(transforms[i] +'.scale', 1.0, 1.0, 1.0, type = 'double3')
        transformMatrix = cmds.xform(transforms[i], q = True, m = True)

        poseMatrix = [x-y for x, y in zip(transformMatrix, baseMatrix)]
        poseScale = [x-y for x, y in zip(transformScale, baseScale)]

        #set the scale back to what the user had it at
        cmds.setAttr(transforms[i] +'.scale', transformScale[0], transformScale[1], transformScale[2], type = 'double3')
        cmds.setAttr(blendNode +'.transforms[' +str(i) +'].poses[' +str(poseIndex) +'].matrix', poseMatrix, type = 'matrix')
        BT_Double3ValuesToNode(values = poseScale, node = blendNode, attr = 'transforms[' +str(i) +'].poses[' +str(poseIndex) +'].scale' )

        if index is None:
            cmds.connectAttr(set +'.' +prefixedPoseName, blendNode +'.transforms[' +str(i) +'].poses[' +str(poseIndex) +'].weight')

    return True
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
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
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
def BT_DeletePose(set = None, poseIndex = None):

    if not set or poseIndex is None:
        return False

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

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

    blendNode = cmds.getAttr(set +'.Blend_Node')

    if not cmds.objExists(blendNode) or not cmds.objExists(set):
        return False

    numTransforms = cmds.getAttr(blendNode +'.transforms', size = True)

    if not numTransforms:
        return False

    numPoses = cmds.getAttr(blendNode +'.transforms[0].poses', size = True) 
    allUserDefined = cmds.listAttr(set, ud = True)
    btUserDefined = [x for x in allUserDefined if x.startswith('BT_')]

    if poseIndex >= numPoses:
        return False

    connectionsToBreak = cmds.listConnections(set +'.' +btUserDefined[poseIndex], d = True, s = False, p = True)
    for ctb in connectionsToBreak:
        cmds.disconnectAttr(set +'.' +btUserDefined[poseIndex], ctb)
    cmds.deleteAttr(set +'.' +btUserDefined[poseIndex])

    for i in range(0, numTransforms):
        for p in range(poseIndex, numPoses-1):
            #get the next items vales
            matrix = cmds.getAttr(blendNode +'.transforms[' +str(i) +'].poses[' +str(p+1) +'].matrix')
            scale = cmds.getAttr(blendNode +'.transforms[' +str(i) +'].poses[' +str(p+1) +'].scale')[0]
            conn = cmds.listConnections(blendNode +'.transforms[' +str(i) +'].poses[' +str(p+1) +'].weight', s = True, d = False, p = True)[0]

            cmds.setAttr(blendNode +'.transforms[' +str(i) +'].poses[' +str(p) +'].matrix', matrix, type = 'matrix')
            cmds.setAttr(blendNode +'.transforms[' +str(i) +'].poses[' +str(p) +'].scale', scale[0], scale[1], scale[2], type = 'double3')
            cmds.connectAttr(conn, blendNode +'.transforms[' +str(i) +'].poses[' +str(p) +'].weight', force = True)
            cmds.disconnectAttr(conn, blendNode +'.transforms[' +str(i) +'].poses[' +str(p+1) +'].weight')

    return True
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
def BT_AddPose(set = None, poseName = '', index = None):

    prefixedPoseName = 'BT_' +poseName

    if not set:
        return False

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

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

    blendNode = cmds.getAttr(set +'.Blend_Node')

    if not cmds.objExists(blendNode) or not cmds.objExists(set):
        return False

    if cmds.attributeQuery(prefixedPoseName, ex = True, n = set):
        return False

    transforms = cmds.listConnections(set +'.dagSetMembers')

    numTransforms = len(transforms)
    poseIndex = cmds.getAttr(blendNode +'.transforms[0].poses', size = True) 

    if index is not None:
        poseIndex = index

    if index is None:
        cmds.addAttr(set, ln = prefixedPoseName, nn = poseName,  k = True, min = 0, max = 1.0, at = 'double')

    # print ('Num poses = ' +str(numPoses))
    for i in range(0, numTransforms):
        #get the base matrix
        baseScale = cmds.getAttr(blendNode +'.transforms[' +str(i) +'].baseScale')[0]
        baseMatrix = cmds.getAttr(blendNode +'.transforms[' +str(i) +'].baseMatrix')

        #store the scale and set it 
        transformScale = cmds.getAttr(transforms[i] +'.scale')[0]

        #set the scale back to 1.0
        cmds.setAttr(transforms[i] +'.scale', 1.0, 1.0, 1.0, type = 'double3')
        transformMatrix = cmds.xform(transforms[i], q = True, m = True)

        poseMatrix = [x-y for x, y in zip(transformMatrix, baseMatrix)]
        poseScale = [x-y for x, y in zip(transformScale, baseScale)]

        #set the scale back to what the user had it at
        cmds.setAttr(transforms[i] +'.scale', transformScale[0], transformScale[1], transformScale[2], type = 'double3')
        cmds.setAttr(blendNode +'.transforms[' +str(i) +'].poses[' +str(poseIndex) +'].matrix', poseMatrix, type = 'matrix')
        BT_Double3ValuesToNode(values = poseScale, node = blendNode, attr = 'transforms[' +str(i) +'].poses[' +str(poseIndex) +'].scale' )

        if index is None:
            cmds.connectAttr(set +'.' +prefixedPoseName, blendNode +'.transforms[' +str(i) +'].poses[' +str(poseIndex) +'].weight')

    return True
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def get_selected_channels(full=True, long=True, *args):
    """
    for ONE object selected, return all selected channels from channel box
    :param full: (boolean) return the full name of the object.attr?, if false then returns only the attr names
    ":param long: (boolean) whether we should get the long name of the attr. False will give us "short" names
    :return: list of full obj.channel names selected, or (if not "full") just the channnel names
    """
    cBox = mel.eval('$temp=$gChannelBoxName')

    sel = cmds.ls(sl=True, l=True)
    if len(sel) != 1:
        cmds.warning("You have to select ONE node!")
        return(None)

    obj = sel[0]

    channelsRaw = cmds.channelBox(cBox, q=True, selectedMainAttributes=True, selectedShapeAttributes=True,
                               selectedHistoryAttributes=True,
                               selectedOutputAttributes=True)

    channels = []
    if channelsRaw:
        if long:
            for ch in channelsRaw:
                newC = cmds.attributeQuery(ch, node=obj, longName=True)
                channels.append(newC)
        else:
            for ch in channelsRaw:
                newC = cmds.attributeQuery(ch, node=obj, shortName=True)
                channels.append(newC)
    else: return(None)

    returnList = []
    if channels:
        if full:
            for c in channels:
                full = "{0}.{1}".format(obj, c)
                returnList.append(full)
        else:
            returnList = channels

        return(returnList)
    else:
        cmds.warning("zbw_rig.get_selected_channels: I didn't detect any channels selected!")
        return(None)
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def zbw_mmConnectM(*args):
    """
    uses the items from the textFields to create message attrs in the base obj, and connects to those the objs from the rightmost fields of the UI
    """
    #check there's a base obj
    if (cmds.textFieldButtonGrp("zbw_tfbg_baseObj", q=True, tx=True)):
        #check there are any fields created
        if (cmds.rowColumnLayout("mmRCLayout", q=True, ca=True)):

            children = cmds.rowColumnLayout("mmRCLayout", q=True, ca=True)
            numObj = (len(children)/2)

            if numObj:
                for num in range(1, numObj+1):
                    attrTFG =  "attr" + str(num)
                    objTFBG = "obj" + str(num)
                    baseObj = cmds.textFieldButtonGrp("zbw_tfbg_baseObj", q=True, tx=True)
                    targetObj = cmds.textFieldButtonGrp(objTFBG, q=True, tx=True)
                    baseAttr = cmds.textFieldGrp(attrTFG, q=True, tx=True)
                    baseMAttr = baseObj + "." + baseAttr
                    objMAttr = targetObj + ".message"
                    #check to make sure there's something in each field, otherwise skip
                    if baseAttr and targetObj:
                        #check that attr doesnt' already exist with connection
                        if (cmds.attributeQuery(baseAttr, n=baseObj, ex=True)):
                            #delete the attr that exists, print note about it
                            cmds.deleteAttr(baseMAttr)
                            cmds.warning(baseMAttr + " already exists! Deleting for overwrite and reconnection")
                        cmds.addAttr(baseObj, at="message", ln=baseAttr)
                        cmds.connectAttr(objMAttr, baseMAttr, f=True)
                        #print confirmation of connection
                        print("Connected: "+ objMAttr +"--->"+ baseMAttr)

                    else:
                        cmds.warning("Line # " + str(num) + " was empty! Skipped that attr")
                #leave a text field saying that it's done
                zbw_mmDeleteConfirm()
                cmds.separator("mmConfirmSep", h=20, st="single", p="mmAddNewConnections")
                cmds.text("mmTextConfirm", l="MESSAGES MAPPED!", p="mmAddNewConnections")
        else:
            cmds.warning("Please create some attrs and objs to connect to base obj!")
    else:
        cmds.warning("Please choose a base object to add attrs to!")
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def zbw_mmListCurrentMessages(tfbg, *args):
    """
    lists the message attrs in the base obj and sets up rt-click menus to change them and a button to delete them
    """
    if (cmds.rowColumnLayout("mmRCListLayout", q=True, ex=True)):
        cmds.deleteUI("mmRCListLayout")
    cmds.rowColumnLayout("mmRCListLayout", w=600, nc=3, cw=[(1, 250),(2,250),(3,100)],p="existingMessages")
    #get the base object
    baseObj = cmds.textFieldButtonGrp(tfbg, q=True, tx=True)
    #find all attr of type message for base obj
    userAttrs = cmds.listAttr(baseObj, ud=True)
    #print(udAttrs)
    messageAttrs = []
    messageObjs = []
    if userAttrs:
        for attr in userAttrs:
            isMsg = cmds.attributeQuery(attr, n=baseObj, msg=True)
            if isMsg:
                fullMsgAttr = baseObj + "." + attr
                messageAttrs.append(fullMsgAttr)
                targetObj = cmds.listConnections(fullMsgAttr)
                if not targetObj:
                    targetObj = ["no Connection"]
                messageObjs.append(targetObj[0])

        sizeMsgs = len(messageObjs)
        for i in range(0, sizeMsgs):
            thisObj = messageObjs[i]
            thisAttr = messageAttrs[i]

            #create textField based on num already there, non-editable
            attrId = "listAttrTFG" + str(i)
            objId = "listObjTFG" + str(i)
            buttonId = "listButton" + str(i)

            cmds.separator(h=15, style="single")
            cmds.separator(h=15, style="single")
            cmds.separator(h=15, style="single")

            #create text field for attr
            cmds.textFieldGrp(attrId, p="mmRCListLayout", l=i, cw=[(1,10), (2,190)], ed=False, tx=thisAttr)
            #create popup for text field
            cmds.popupMenu(("attrPUM"+str(i)), b=3)
            cmds.menuItem(l="change attr name", p=("attrPUM"+str(i)), c=partial(zbw_mmChangeConnectAttrUI, baseObj, thisAttr, thisObj))

            #create textField obj based on num, non-editable
            cmds.textFieldGrp(objId, p="mmRCListLayout", w=200, ed=False, tx=thisObj)
            #create pop up
            cmds.popupMenu(("objPUM"+str(i)), b=3)
            cmds.menuItem(l="change obj", p=("objPUM"+str(i)), c=partial(zbw_mmChangeConnectObjUI, baseObj, thisAttr, thisObj))

            #create button to delete attr
            cmds.button(buttonId, l="delete", w=50, c=partial(zbw_mmDeleteMsgAttr, thisAttr))
    else:
        cmds.text("no message attributes on this object", p="mmRCListLayout")
项目:gozbruh    作者:LumaPictures    | 项目源码 | 文件源码
def _get_gozid_mismatches(objs):
    """Return objects from `objs` whose gozbruhBrushID does not match their name

    Checks object history for instances of gozbruhBrushID,
    returns a list ofgozbruhBrushID/name conflicts

    gozbruhBrushID is created by ZBrush on export and is used to track
    name changes that can occur in maya

    this function compares object current name against the ID
    and returns a list of conflicts

    this list is handled by the gui to allow for dialog boxes
    """
    goz_list = []

    for obj in objs:
        has_attr = cmds.attributeQuery(
            'gozbruhBrushID', node=obj, exists=True)

        if has_attr:
            # check for 'rename'
            goz_id = cmds.getAttr(obj + '.gozbruhBrushID')
            if obj != goz_id:
                goz_list.append((obj, goz_id))
        else:
            # check for old ID in history
            for old_obj in cmds.listHistory(obj):
                has_attr = cmds.attributeQuery('gozbruhBrushID',
                                               node=old_obj,
                                               exists=True)
                if has_attr:
                    goz_id = cmds.getAttr(old_obj + '.gozbruhBrushID')
                    if obj != goz_id:
                        goz_list.append((obj, goz_id))

    # resulting mismatches to be handled
    return goz_list

#------------------------------------------------------------------------------
# Sending / Exporting
#------------------------------------------------------------------------------
项目:gozbruh    作者:LumaPictures    | 项目源码 | 文件源码
def export(objs):
    """Save files.

    Checks for gozbruhParent attr.

    gozbruhParent is used to import objects in correct order in ZBrush
    gozbruhParent determines the top level tool in ZBrush

    If no instance exists, it is created

    Returns
    -------
    list of (str, str)
        list of object, parent pairs
    """
    parents = []

    for obj in objs:
        # export each file individually
        cmds.select(cl=True)
        cmds.select(obj)
        cmds.delete(ch=True)
        ascii_path = utils.make_maya_filepath(obj)
        cmds.file(ascii_path,
                  force=True,
                  options="v=0",
                  type="mayaAscii",
                  exportSelected=True)
        if cmds.attributeQuery('gozbruhParent', node=obj, exists=True):
            # object existed in zbrush, has 'parent' tool
            parent = cmds.getAttr(obj + '.gozbruhParent')
            # append to the end of parents
            parents.append((obj, parent))
        else:
            cmds.addAttr(obj, longName='gozbruhParent', dataType='string')
            cmds.setAttr(obj + '.gozbruhParent', obj, type='string')
            # prepend to the beginning of parents, we want these objects
            # imported first
            parents = [(obj, obj)] + parents

        # maya is often run as root, this makes sure osx can open/save
        # files not needed if maya is run un-privileged
        os.chmod(ascii_path, 0o777)
    return parents
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def swapAnimation(fromNode, toNode):

    if not mc.keyframe(fromNode, query=True, name=True):
        mc.cutKey(toNode, clear=True)
        return

    attrs = mc.listAttr(fromNode, keyable=True)
    if not attrs:
        return

    for attr in attrs:
        if not mc.attributeQuery(attr, node=toNode, exists=True):
            mc.cutKey(fromNode, attribute=attr, clear=True)
            continue

        fromPlug = '{}.{}'.format(fromNode, attr)
        toPlug = '{}.{}'.format(toNode, attr)

        srcCurve = mc.listConnections(fromPlug, source=True, destination=False, type='animCurve')
        dstCurve = mc.listConnections(toPlug, source=True, destination=False, type='animCurve')

        copySrc=None
        copyDst=None

        if srcCurve:
            copySrc = mc.duplicate(srcCurve[0])[0]

        if dstCurve:
            copyDst = mc.duplicate(dstCurve[0])[0]

        if copySrc:
            try:
                mc.cutKey(copySrc)
                mc.pasteKey(toNode, attribute=attr, option='replaceCompletely')
            except:pass
        if copyDst:
            try:
                mc.cutKey(copyDst)
                mc.pasteKey(fromNode, attribute=attr, option='replaceCompletely')
            except:pass

    for axis in getMirrorAxis(toNode):
        mc.scaleKey(toNode, attribute=axis, valueScale=-1)
        mc.scaleKey(fromNode, attribute=axis, valueScale=-1)
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def reset_pivot(*args):

    sel = mc.ls(sl=True)
    if not sel:
        om.MGlobal.displayWarning('Nothing selected.')
        return

    if len(sel) > 1:
        om.MGlobal.displayWarning('Only works on one node at a time.')
        return

    node = sel[0]
    driver = None
    driver_value = None
    driver_default = None

    if is_pivot_connected(node):
        driver = pivot_driver_attr(node)
        if driver:
            dNode,dAttr = driver.split('.',1)
            driver_value = mc.getAttr(driver)
            driver_default = mc.attributeQuery(dAttr, node=dNode, listDefault=True)[0]
            if driver_default == driver_value:
                return
        else:
            om.MGlobal.displayWarning('Pivot attribute is connected, unable to edit.')        
            return

    if not driver:
        pivotPosition = mc.getAttr(node+'.rotatePivot')[0]
        if pivotPosition  == (0.0,0.0,0.0):
            return

    tempPosition = mc.group(em=True)
    tempPivot = mc.group(em=True)
    tempPivot = mc.parent(tempPivot, node)[0]
    if driver:
        mc.setAttr(driver, driver_default)
        newRP = mc.getAttr(node+'.rotatePivot')[0]
        mc.setAttr(driver, driver_value)
        mc.setAttr(tempPivot+'.translate', *newRP)
    else:
        mc.setAttr(tempPivot+'.translate', 0,0,0)

    mc.setAttr(tempPivot+'.rotate', 0,0,0)

    utl.matchBake(source=[tempPivot], destination=[tempPosition], bakeOnOnes=True, maintainOffset=False, preserveTangentWeight=False, rotate=False)

    if driver:
        mc.setAttr(driver, driver_default)
    else:
        mc.setAttr(node+'.rotatePivot', 0,0,0)

    mc.refresh()
    utl.matchBake(source=[tempPosition], destination=[node], bakeOnOnes=True, maintainOffset=False, preserveTangentWeight=False, rotate=False)

    mc.delete(tempPosition,tempPivot)    

    mc.select(node)