python类listAttr()的实例源码

interactive.py 文件源码 项目:config 作者: mindbender-studio 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
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)
interactive.py 文件源码 项目:config 作者: mindbender-studio 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def clone_special(*args):
    """Clone in localspace, and preserve user-defined attributes"""

    for transform in cmds.ls(selection=True, long=True):
        if cmds.nodeType(transform) != "transform":
            cmds.warning("Skipping '%s', not a `transform`" % transform)
            continue

        shape = _find_shape(transform)
        type = cmds.nodeType(shape)

        if type not in ("mesh", "nurbsSurface", "nurbsCurve"):
            cmds.warning("Skipping '{transform}': cannot clone nodes "
                         "of type '{type}'".format(**locals()))
            continue

        cloned = commands.clone(shape, worldspace=False)
        new_transform = cmds.listRelatives(cloned,
                                           parent=True,
                                           fullPath=True)[0]

        new_transform = cmds.rename(new_transform,
                                    new_transform.rsplit(":", 1)[-1])

        for attr in cmds.listAttr(transform,
                                  userDefined=True) or list():
            try:
                cmds.addAttr(new_transform, longName=attr, dataType="string")
            except Exception:
                continue

            value = cmds.getAttr(transform + "." + attr)
            cmds.setAttr(new_transform + "." + attr, value, type="string")

        # Connect visibility
        cmds.connectAttr(transform + ".visibility",
                         new_transform + ".visibility")
control.py 文件源码 项目:cmt 作者: chadmv 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def get_stack_parent(node):
    """Get the parent of the transform stack belonging to the given node.

    :param node: Node to query.
    :return: The parent node or None if there is no parent.
    """
    previous_parent = cmds.listRelatives(node, parent=True, path=True)
    if not previous_parent:
        return None
    previous_parent = previous_parent[0]
    while previous_parent and STACK_ATTRIBUTE in (cmds.listAttr(previous_parent, ud=True) or []):
        parent = cmds.listRelatives(previous_parent, parent=True, path=True)
        if parent:
            parent = parent[0]
        previous_parent = parent
    return previous_parent
lib.py 文件源码 项目:pyblish-starter 作者: pyblish 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def read(node):
    """Return user-defined attributes from `node`

    """

    data = dict()

    for attr in cmds.listAttr(node, userDefined=True) or list():
        try:
            value = cmds.getAttr(node + "." + attr)
        except:
            # Some attributes cannot be read directly,
            # such as mesh and color attributes. These
            # are considered non-essential to this
            # particular publishing pipeline.
            value = None

        data[attr] = value

    return data
zbw_curveExtrude.py 文件源码 项目:zTools 作者: zethwillie 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def clearShaderConnections(ts="", geo="", *args):
    myShape = cmds.listRelatives(geo, s=True)[0]
    tsList = cmds.listAttr(ts, m=True, st=["*input*"])
    if tsList:
        # delete empty entries? ? 
        # for tsInput in tsList:
        #   shpList = cmds.connectionInfo("{0}.{1}.inShape".format(ts, tsInput), sfd=True)
        #   if not shpList:
        #       cmds.removeMultiInstance("blinn1_TripleSwitch.{0}".format(tsInput))         

        for tsInput in tsList:
            shpList = cmds.connectionInfo("{0}.{1}.inShape".format(ts, tsInput), sfd=True).partition(".")
            shp = ""
            if shpList:
                shp = shpList[0]
            if shp == myShape:
                # clear out the shape node
                cmds.disconnectAttr("{0}.instObjGroups[0]".format(shp), "{0}.{1}.inShape".format(ts, tsInput))
                # clear out the texture (delete if we can)
                txt = cmds.connectionInfo("{0}.{1}.inTriple".format(ts, tsInput), sfd=True).partition(".")[0]
                cmds.disconnectAttr("{0}.outColor".format(txt), "{0}.{1}.inTriple".format(ts, tsInput))
                p2d = cmds.connectionInfo("{0}.uvCoord".format(txt), sfd=True).partition(".")[0]
                cmds.delete(txt, p2d)
lib.py 文件源码 项目:core 作者: getavalon 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def read(node):
    """Return user-defined attributes from `node`"""

    data = dict()

    for attr in cmds.listAttr(node, userDefined=True) or list():
        try:
            value = cmds.getAttr(node + "." + attr)
        except ValueError:
            # Some attributes cannot be read directly,
            # such as mesh and color attributes. These
            # are considered non-essential to this
            # particular publishing pipeline.
            value = None

        data[attr] = value

    return data
clip.py 文件源码 项目:maya2katana 作者: ababak 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def getNodeAttributes(node):
    '''
    Get Maya node attributes
    '''
    attributes = cmds.listAttr(node)
    attr = {}
    attr['nodeName'] = node
    attr['nodeType'] = cmds.nodeType(node)
    for attribute in attributes:
        if '.' in attribute:
            continue
        try:
            val = cmds.getAttr(node + '.' + attribute)
        except RuntimeError:
            continue
        attr[attribute] = val
    return attr
ml_utilities.py 文件源码 项目:ml_tools 作者: morganloomis 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def channels(self):
        '''
        The keySelection's channels list.
        '''

        if not self._channels:

            if self._curves:
                for c in self._curves:
                    self._channels.append(getChannelFromAnimCurve(c))
            elif self._nodes:
                for obj in self._nodes:
                    keyable = mc.listAttr(obj, keyable=True, unlocked=True, hasData=True, settable=True)
                    if keyable:
                        for attr in keyable:
                            self._channels.append('.'.join((obj, attr)))

        return self._channels
commands.py 文件源码 项目:config 作者: mindbender-studio 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def connect_matching_attributes(source, target):
    """Connect matching attributes from source to target

    Arguments:
        source (str): Absolute path to node from which to connect
        target (str): Target node

    Example:
        >>> # Select two matching nodes
        >>> source = cmds.createNode("transform", name="source")
        >>> target = cmds.createNode("transform", name="target")
        >>> cmds.select([source, target], replace=True)
        >>> source, target = cmds.ls(selection=True)
        >>> connect_matching_attributes(source, target)

    """

    dsts = cmds.listAttr(target, keyable=True)
    for src in cmds.listAttr(source, keyable=True):
        if src not in dsts:
            continue

        try:
            src = "." + src
            cmds.connectAttr(source + src,
                             target + src,
                             force=True)
        except RuntimeError as e:
            cmds.warning("Could not connect %s: %s" % (src, e))
control.py 文件源码 项目:cmt 作者: chadmv 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def create_transform_stack(node, count=2):
    """Creates a transform stack above the given node.

    Any previous transform stack will be deleted.

    :param node: Node to parent into a transform stack.
    :param count: Number of transforms to add in the stack.
    :return: A list of the transform nodes created starting from top to bottom.
    """
    previous_parent = cmds.listRelatives(node, parent=True, path=True)
    if previous_parent:
        previous_parent = previous_parent[0]
        while previous_parent and STACK_ATTRIBUTE in (cmds.listAttr(previous_parent, ud=True) or []):
            parent = cmds.listRelatives(previous_parent, parent=True, path=True)
            if parent:
                cmds.parent(node, parent)
                parent = parent[0]
            else:
                cmds.parent(node, world=True)
            cmds.delete(previous_parent)
            previous_parent = parent

    nulls = []
    for i in reversed(range(count)):
        name = '_'.join(node.split('_')[:-1])
        name = '{0}_{1}nul'.format(name, i+1)
        null = cmds.createNode('transform', name=name)
        nulls.append(null)
        cmds.addAttr(null, ln=STACK_ATTRIBUTE, at='message')
        cmds.connectAttr('{0}.message'.format(node), '{0}.{1}'.format(null, STACK_ATTRIBUTE))
        cmds.delete(cmds.parentConstraint(node, null))
        if previous_parent:
            cmds.parent(null, previous_parent)
        previous_parent = null
    cmds.parent(node, previous_parent)
    return nulls
BlendTransforms.py 文件源码 项目:BlendTransforms 作者: duncanskertchly 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def BT_GetPosesFromSet(set = None):
    if not set:
        return False

    allUserDefined = cmds.listAttr(set, ud = True)
    if not allUserDefined:
        return ''

    btUserDefined = [x[3:] for x in allUserDefined if x.startswith('BT_')]

    if not btUserDefined:
        return ''

    return btUserDefined
BlendTransforms.py 文件源码 项目:BlendTransforms 作者: duncanskertchly 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def BT_GetPosesFromSet(set = None):
    if not set:
        return False

    allUserDefined = cmds.listAttr(set, ud = True)
    if not allUserDefined:
        return ''

    btUserDefined = [x[3:] for x in allUserDefined if x.startswith('BT_')]

    if not btUserDefined:
        return ''

    return btUserDefined
BlendTransforms.py 文件源码 项目:BlendTransforms 作者: duncanskertchly 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def BT_GetPosesFromSet(set = None):
    if not set:
        return False

    allUserDefined = cmds.listAttr(set, ud = True)
    if not allUserDefined:
        return ''

    btUserDefined = [x[3:] for x in allUserDefined if x.startswith('BT_')]

    if not btUserDefined:
        return ''

    return btUserDefined
BlendTransforms.py 文件源码 项目:BlendTransforms 作者: duncanskertchly 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def BT_GetPosesFromSet(set = None):
    if not set:
        return False

    allUserDefined = cmds.listAttr(set, ud = True)
    if not allUserDefined:
        return ''

    btUserDefined = [x[3:] for x in allUserDefined if x.startswith('BT_')]

    if not btUserDefined:
        return ''

    return btUserDefined
dependency.py 文件源码 项目:metan 作者: utatsuya 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def listAttrStr(self, *args, **kwds):
        _name = self.name()
        attrnames = []
        if args:
            attrnames = cmds.listAttr([_name+"."+attr.split(".")[-1] for attr in args], **kwds)
        else:
            attrnames = cmds.listAttr(_name, **kwds)

        if not attrnames:
            return []
        else:
            return attrnames
zbw_spaceMatch_overComplex.py 文件源码 项目:zTools 作者: zethwillie 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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
ml_puppet.py 文件源码 项目:ml_tools 作者: morganloomis 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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_puppet.py 文件源码 项目:ml_tools 作者: morganloomis 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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_utilities.py 文件源码 项目:ml_tools 作者: morganloomis 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def constrain(source, destination, translate=True, rotate=True, scale=False):
    '''
    Constrain two objects, even if they have some locked attributes.
    '''

    transAttr = None
    rotAttr = None
    scaleAttr = None

    if translate:
        transAttr = mc.listAttr(destination, keyable=True, unlocked=True, string='translate*')
    if rotate:
        rotAttr = mc.listAttr(destination, keyable=True, unlocked=True, string='rotate*')
    if scale:
        scaleAttr = mc.listAttr(destination, keyable=True, unlocked=True, string='scale*')

    rotSkip = list()
    transSkip = list()

    for axis in ['x','y','z']:
        if transAttr and not 'translate'+axis.upper() in transAttr:
            transSkip.append(axis)
        if rotAttr and not 'rotate'+axis.upper() in rotAttr:
            rotSkip.append(axis)

    if not transSkip:
        transSkip = 'none'
    if not rotSkip:
        rotSkip = 'none'

    constraints = list()
    if rotAttr and transAttr and rotSkip == 'none' and transSkip == 'none':
        constraints.append(mc.parentConstraint(source, destination))
    else:
        if transAttr:
            constraints.append(mc.pointConstraint(source, destination, skip=transSkip))
        if rotAttr:
            constraints.append(mc.orientConstraint(source, destination, skip=rotSkip))

    return constraints
ml_transferKeytimes.py 文件源码 项目:ml_tools 作者: morganloomis 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def transferKeytimes(source, destinations):

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

    attributes = mc.listAttr(source, keyable=True, unlocked=True)

    keytimes = dict()
    start = None
    end = None

    for a in attributes:
        currKeytimes = mc.keyframe(source, attribute=a, query=True, timeChange=True)
        if not currKeytimes:
            continue

        if start == None or currKeytimes[0] < start:
            start = currKeytimes[0]

        if end == None or currKeytimes[-1] > end:
            end = currKeytimes[-1]

        keytimes[a] = currKeytimes
        #allKeyTimes.extend(currKeytimes)

    if not keytimes:
        return

    with utl.IsolateViews():
        mc.bakeResults(destinations, time=(start,end), sampleBy=1, preserveOutsideKeys=True, simulation=True)

        #euler filter
        mc.filterCurve(mc.listConnections(destinations,type='animCurve'))

        #go through all keys and delete 
        for k in keytimes:
            for f in range(int(start), int(end)):
                if not f in keytimes[k]:
                    mc.cutKey(destinations, attribute=k, time=(f,))
ml_graphEditorMask.py 文件源码 项目:ml_tools 作者: morganloomis 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def showAll(*args):

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

    for each in sel:
        attrs = mc.listAttr(each, keyable=True, unlocked=True)
        if attrs:
            for a in attrs:
                mc.selectionConnection('graphEditor1FromOutliner', edit=True, select=each+'.'+a)
ml_resetChannels.py 文件源码 项目:ml_tools 作者: morganloomis 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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()
collect_instances.py 文件源码 项目:config 作者: mindbender-studio 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def process(self, context):
        from maya import cmds

        for objset in cmds.ls("*.id",
                              long=True,            # Produce full names
                              type="objectSet",     # Only consider objectSets
                              recursive=True,       # Include namespace
                              objectsOnly=True):    # Return objectSet, rather
                                                    # than its members

            is_empty = cmds.sets(objset, query=True) is None
            if is_empty:
                self.log.info("%s skipped, it was empty." % objset)
                continue

            if not cmds.objExists(objset + ".id"):
                continue

            if cmds.getAttr(objset + ".id") not in (
                    "pyblish.avalon.instance",

                    # Backwards compatibility
                    "pyblish.mindbender.instance"):

                continue

            # The developer is responsible for specifying
            # the family of each instance.
            assert cmds.objExists(objset + ".family"), (
                "\"%s\" was missing a family" % objset)

            data = dict()

            # Apply each user defined attribute as data
            for attr in cmds.listAttr(objset, userDefined=True) or list():
                try:
                    value = cmds.getAttr(objset + "." + attr)
                except Exception:
                    # Some attributes cannot be read directly,
                    # such as mesh and color attributes. These
                    # are considered non-essential to this
                    # particular publishing pipeline.
                    value = None

                data[attr] = value

            name = cmds.ls(objset, long=False)[0]  # Use short name
            instance = context.create_instance(data.get("name", name))
            instance[:] = cmds.sets(objset, query=True) or list()
            instance.data.update(data)

            # Produce diagnostic message for any graphical
            # user interface interested in visualising it.
            self.log.info("Found: \"%s\" " % instance.data["name"])
orientjoints.py 文件源码 项目:cmt 作者: chadmv 项目源码 文件源码 阅读 38 收藏 0 点赞 0 评论 0
def rebuild_joints(*args):
    if not cmds.objExists(ORIENT_GROUP):
        return
    nodes = cmds.listRelatives(ORIENT_GROUP, ad=True, path=True) or []

    joints = []
    for node in nodes:
        attrs = cmds.listAttr(node, ud=True) or []
        if MESSAGE_ATTRIBUTE not in attrs:
            continue
        joint = cmds.listConnections('{0}.{1}'.format(node, MESSAGE_ATTRIBUTE), d=False)[0]
        joints.append(joint)
        rotation = cmds.getAttr('{0}.rx'.format(node))

        children = cmds.listRelatives(joint, children=True, shapes=False, path=True)
        if children:
            # First unparent children so change in joint orient does not affect children
            children = [cmds.parent(child, world=True)[0] for child in children]

            # Add rotation offset to joint orient
            orient_x = cmds.getAttr('{0}.jointOrientX'.format(joint))
            orient_x += rotation
            while orient_x > 180.0:
                orient_x -= 360.0
            while orient_x < -180.0:
                orient_x += 360.0
            cmds.setAttr('{0}.jointOrientX'.format(joint), orient_x)

            # Reparent child
            for child in children:
                cmds.parent(child, joint)

        else:
            # tip joint, just zero out joint orient
            cmds.setAttr('%s.jointOrientX' % joint, 0)
            cmds.setAttr('%s.jointOrientY' % joint, 0)
            cmds.setAttr('%s.jointOrientZ' % joint, 0)

        # Untemplate
        cmds.setAttr('{0}.template'.format(joint), 0)

    # Delete arrow group
    cmds.delete(ORIENT_GROUP)
    cmds.select(joints)
BlendTransforms.py 文件源码 项目:BlendTransforms 作者: duncanskertchly 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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.py 文件源码 项目:BlendTransforms 作者: duncanskertchly 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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.py 文件源码 项目:BlendTransforms 作者: duncanskertchly 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
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
collect_instances.py 文件源码 项目:pyblish-starter 作者: pyblish 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def process(self, context):
        from maya import cmds

        try:
            # Assertion also made in pyblish_starter.install()
            # but as plug-ins can be used vanilla, the check
            # must also be made here.
            import pyblish_maya
            assert pyblish_maya.is_setup()

        except (ImportError, AssertionError):
            raise RuntimeError("pyblish-starter requires pyblish-maya "
                               "to have been setup.")

        for objset in cmds.ls("*.id",
                              long=True,            # Produce full names
                              type="objectSet",     # Only consider objectSets
                              recursive=True,       # Include namespace
                              objectsOnly=True):    # Return objectSet, rather
                                                    # than its members

            if not cmds.objExists(objset + ".id"):
                continue

            if not cmds.getAttr(objset + ".id") == "pyblish.starter.instance":
                continue

            # The developer is responsible for specifying
            # the family of each instance.
            assert cmds.objExists(objset + ".family"), (
                "\"%s\" was missing a family" % objset)

            name = cmds.ls(objset, long=False)[0]  # Use short name
            instance = context.create_instance(name)
            instance[:] = cmds.sets(objset, query=True) or list()

            # Apply each user defined attribute as data
            for attr in cmds.listAttr(objset, userDefined=True) or list():
                try:
                    value = cmds.getAttr(objset + "." + attr)
                except:
                    # Some attributes cannot be read directly,
                    # such as mesh and color attributes. These
                    # are considered non-essential to this
                    # particular publishing pipeline.
                    value = None

                instance.data[attr] = value

            # Produce diagnostic message for any graphical
            # user interface interested in visualising it.
            self.log.info("Found: \"%s\" " % instance.data["name"])
zbw_messageMapper.py 文件源码 项目:zTools 作者: zethwillie 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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")
zbw_spaceMatch_overComplex.py 文件源码 项目:zTools 作者: zethwillie 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def spaceMatchUI():
    if (cmds.window("spaceMatchWin", exists=True)):
        cmds.deleteUI("spaceMatchWin", window=True)

    widgets["window"] = cmds.window("spaceMatchWin", title="Space Matcher", w=250, h=300)
    widgets["mainLO"] = cmds.columnLayout()
    widgets["tabLO"] = cmds.tabLayout()
    widgets["getObjCLO"] = cmds.columnLayout()
    widgets["instruct"] = cmds.text("get obj, then attr, then space then do it")
    cmds.separator(h=10)

    #----------fill with selection automatically?
    widgets["objTFG"] = cmds.textFieldGrp(l="select obj", cw=([1,50],[2,150],[3,50]), cal=([1,"left"], [2,"left"],[3,"left"]), cc=clearList)
    widgets["matchObjButton"] = cmds.button(l="select object", c=partial(getObj, widgets["objTFG"]))
    cmds.separator(h=10)
    #-----------maybe here have it catch the selected obj by default
    #-----------and/or have a field for the attribute (default to "follow")
    widgets["getAttrButton"] = cmds.button(w=250, al="center", h=20, l="select enum space attr from obj", bgc= (.5, .5, 0), c=getAttr)
    #-----------when the attr is selected list the attrs automagically,
    widgets["spacesTSL"] = cmds.textScrollList(w=250, h=200, nr=8, ams=False, bgc=(.2, .2, .2))
    widgets["matchButton"] = cmds.button(w=250, al="center", h=40, bgc= (0,.5,0), l="space switch/match", c= doSpaceMatch)

    #tab for creation/setup of matching
    cmds.setParent(widgets["tabLO"])
    #----------in this tab, create frames. One (closable) to create constraint and fill items, check boxes for orient, position (with user selecting objects), one frame (maybe already filled out) (always open) for setting up attrs (message, strings)
    widgets["setupCLO"] = cmds.columnLayout()
    #frame layout for creating the constraints
    widgets["createFrameLO"] = cmds.frameLayout(l="create Constrants", collapsable=True, w=250)
    cmds.text("have em select for constraint")
    widgets["posRotCBG"] = cmds.checkBoxGrp(ncb=2, l1="translation", v1=True, l2="rotation", v2=True)
    #----------this button should just create the constraints on the objects in question, but then fill in what parts of the lower half it can
    widgets["createSetupButton"] = cmds.button(l="create constraints")

    cmds.setParent(widgets["setupCLO"])

    #frameLayout for setting up the attrs
    widgets["setupFrameLO"] = cmds.frameLayout(l="setup matching", collapsable=False, w=250, h=250)
    widgets["setupObjTFG"] = cmds.textFieldGrp(l="select ctrl obj", cw=([1,100],[2,150]), cal=([1,"left"], [2,"left"]))
    widgets["setupObjButton"] = cmds.button(l="get ctrl object", h=40, c= partial(getObj, widgets["setupObjTFG"]))

    widgets["setupConstrTFG"] = cmds.textFieldGrp(l="constraint", cw=([1,100],[2,150]), cal=([1,"left"], [2,"left"]))
    widgets["setupConstrButton"] = cmds.button(l="get constraint", h=40, c= partial(getObj, widgets["setupConstrTFG"]))

    #create list of attrs on constraint
    #attr = cmds.listAttr(sel,ud=True )
    #create list of spaces on obj attr

    cmds.tabLayout(widgets["tabLO"], e=True, tabLabel = ((widgets["getObjCLO"], "change spaces"),(widgets["setupCLO"], "setup matching")))

    cmds.showWindow(widgets["window"])
    cmds.window(widgets["window"], e=True, w=250, h=300)


问题


面经


文章

微信
公众号

扫码关注公众号