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

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

项目:config    作者:mindbender-studio    | 项目源码 | 文件源码
def _maintained_selection_context():
    """Maintain selection during context

    Example:
        >>> scene = cmds.file(new=True, force=True)
        >>> node = cmds.createNode("transform", name="Test")
        >>> cmds.select("persp")
        >>> with maintained_selection():
        ...     cmds.select("Test", replace=True)
        >>> "Test" in cmds.ls(selection=True)
        False

    """

    previous_selection = cmds.ls(selection=True)
    try:
        yield
    finally:
        if previous_selection:
            cmds.select(previous_selection,
                        replace=True,
                        noExpand=True)
        else:
            cmds.select(deselect=True,
                        noExpand=True)
项目:config    作者:mindbender-studio    | 项目源码 | 文件源码
def _clone(worldspace=False):
    """Clone selected objects in viewport

    Arguments:
        worldspace (bool): Whether or not to append a transformGeometry to
            resulting clone.

    """

    clones = list()

    for node in cmds.ls(selection=True, long=True):
        shape = _find_shape(node)
        type = cmds.nodeType(shape)

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

        cloned = commands.clone(shape, worldspace=worldspace)
        clones.append(cloned)

    if not clones:
        return

    # Select newly created transform nodes in the viewport
    transforms = list()

    for clone in clones:
        transform = cmds.listRelatives(clone, parent=True, fullPath=True)[0]
        transforms.append(transform)

    cmds.select(transforms, replace=True)
项目:cmt    作者:chadmv    | 项目源码 | 文件源码
def make_planar(joints):
    for joint in joints:
        parent = cmds.listRelatives(joint, parent=True, path=True)
        if not parent:
            log.warning('Cannot make %s planar because it does not have a parent.', joint)
            continue
        children = _unparent_children(joint)
        if not children:
            log.warning('Cannot make %s planar because it does not have any children.', joint)
            continue
        cmds.delete(cmds.aimConstraint(children[0], joint, aim=(1, 0, 0), u=(0, 1, 0), worldUpType='object', worldUpObject=parent[0]))
        cmds.makeIdentity(joint, apply=True)
        _reparent_children(joint, children)

    if joints:
        cmds.select(joints)
项目:cmt    作者:chadmv    | 项目源码 | 文件源码
def make_position_planar(*args):
    sel = cmds.ls(sl=True, type='joint')
    if len(sel) <= 3:
        raise RuntimeError('Select 3 joints to make a plane and then additional joints to move onto that plane.')
    a, b, c = [get_position(sel[i]) for i in range(3)]
    ab = (b - a).normal()
    ac = (c - a).normal()
    normal = (ab ^ ac).normal()
    joints = sel[3:]
    for joint in joints:
        children = _unparent_children(joint)
        p = get_position(joint)
        pa = a - p
        dot = pa*normal
        p = p + (normal*dot)
        cmds.xform(joint, ws=True, t=(p.x, p.y, p.z))
        _reparent_children(joint, children)

    if sel:
        cmds.select(sel)
项目:cmt    作者:chadmv    | 项目源码 | 文件源码
def align_with_child(joints):
    """Aligns the up axis of the given joints with their respective child joint.

    @param joints: List of joints to orient.
    """
    for joint in joints:
        children = _unparent_children(joint)
        if children:
            cmds.delete(cmds.aimConstraint(children[0], joint, aim=(1, 0, 0), upVector=(0, 1, 0),
                                           worldUpType="objectrotation", worldUpVector=(0, 1, 0),
                                           worldUpObject=children[0]))
            cmds.makeIdentity(joint, apply=True)
        _reparent_children(joint, children)

    if joints:
        cmds.select(joints)
项目:cmt    作者:chadmv    | 项目源码 | 文件源码
def orient_to_world(joints):
    """Orients the given joints with the world.

    @param joints: Joints to orient.
    """
    for joint in joints:
        children = _unparent_children(joint)
        print children
        parent = cmds.listRelatives(joint, parent=True, path=True)
        orig_joint = joint.split('|')[-1]
        if parent:
            joint = cmds.parent(joint, world=True)[0]
        cmds.joint(joint, e=True, oj='none', zso=True)
        if parent:
            joint = cmds.parent(joint, parent)[0]
            print 'Renaming {0} to {1}'.format(joint, orig_joint)
            joint = cmds.rename(joint, orig_joint)
        _reparent_children(joint, children)

    if joints:
        cmds.select(joints)
项目:cmt    作者:chadmv    | 项目源码 | 文件源码
def create_selected(self):
        """Create the curves selected in the curve list."""
        curves = []
        sel = cmds.ls(sl=True)
        target = sel[0] if sel else None
        for item in self.control_list.selectedItems():
            text = item.text()
            control_file = os.path.join(CONTROLS_DIRECTORY, '{0}.json'.format(text))
            fh = open(control_file, 'r')
            data = json.load(fh)
            fh.close()
            curve = create_curve(data)
            if target:
                cmds.delete(cmds.parentConstraint(target, curve))
            curves.append(curve)
        if curves:
            cmds.select(curves)
项目:cmt    作者:chadmv    | 项目源码 | 文件源码
def setUp(self):
        self.group = cmds.createNode('transform', name='skeleton_grp')
        cmds.select(cl=True)
        j1 = cmds.joint(p=(0, 10, 0))
        cmds.joint(p=(1, 9, 0))
        cmds.joint(p=(2, 8, 0))
        j = cmds.joint(p=(3, 9, 0))
        cmds.joint(p=(4, 6, 0))
        cmds.joint(p=(5, 5, 0))
        cmds.joint(p=(6, 3, 0))
        self.cube = cmds.polyCube()[0]
        cmds.parent(self.cube, j)
        cmds.parent(j1, self.group)
        self.translates = [cmds.getAttr('{0}.t'.format(x))[0] for x in cmds.ls(type='joint')]
        self.rotates = [cmds.getAttr('{0}.r'.format(x))[0] for x in cmds.ls(type='joint')]
        self.orients = [cmds.getAttr('{0}.jo'.format(x))[0] for x in cmds.ls(type='joint')]
项目:maya_rotationDriver    作者:ryusas    | 项目源码 | 文件源码
def doit(radius=5., num=36):
    cmds.loadPlugin('rotationDriver', qt=True)
    node = cmds.createNode('composeRotate')
    node_or = node + '.outRotate'
    node_h = node + '.bendH'
    node_v = node + '.bendV'

    shiftX = radius * 1.25

    top0 = _plotBendHV(node_or, node_h, node_v, 'plotStereoProj', radius, num)
    cmds.setAttr(top0 + '.tx', -shiftX)

    cmds.setAttr(node + '.method', 1)
    top1 = _plotBendHV(node_or, node_h, node_v, 'plotExpmap', radius, num)
    cmds.setAttr(top1 + '.tx', shiftX)

    cmds.delete(node)

    cmds.select([top0, top1])
项目:SETools    作者:dtzxporter    | 项目源码 | 文件源码
def WeaponBinder():
    # Call of Duty specific
    for x in xrange(0, len(GUN_BASE_TAGS)):
        try:
            # Select both tags and parent them
            cmds.select(GUN_BASE_TAGS[x], replace = True)
            cmds.select(VIEW_HAND_TAGS[x], toggle = True)
            # Connect
            cmds.connectJoint(connectMode = True)
            # Parent
            mel.eval("parent " + GUN_BASE_TAGS[x] + " " + VIEW_HAND_TAGS[x])
            # Reset the positions of both bones
            cmds.setAttr(GUN_BASE_TAGS[x] + ".t", 0, 0, 0)
            cmds.setAttr(GUN_BASE_TAGS[x] + ".jo", 0, 0, 0)
            cmds.setAttr(GUN_BASE_TAGS[x] + ".rotate", 0, 0, 0)
            # Reset the rotation of the parent tag
            cmds.setAttr(VIEW_HAND_TAGS[x] + ".jo", 0, 0, 0)
            cmds.setAttr(VIEW_HAND_TAGS[x] + ".rotate", 0, 0, 0)
            # Remove
            cmds.select(clear = True)
        except:
            pass


# Place a notetrack
项目:SETools    作者:dtzxporter    | 项目源码 | 文件源码
def SelectKeyframes():
    # Clear current selection
    cmds.select(clear=True)
    # Get a list of bones
    boneList = cmds.ls(type = 'joint')
    # Iterate and select ones with frames on loc/rot/scale
    for bone in boneList:
        # Check for loc
        keysTranslate = cmds.keyframe(bone + ".translate", query=True, timeChange=True)
        keysRotate = cmds.keyframe(bone + ".rotate", query=True, timeChange=True)
        keysScale = cmds.keyframe(bone + ".scale", query=True, timeChange=True)
        # Check for frames
        if keysTranslate is not None:
            if len(keysTranslate) >= 1:
                cmds.select(bone, add=True)
        if keysRotate is not None:
            if len(keysRotate) >= 1:
                cmds.select(bone, add=True)
        if keysScale is not None:
            if len(keysScale) >= 1:
                cmds.select(bone, add=True)

# Cleans namespaces
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def populateCrvField(tfgKey="", *args):
    if tfgKey not in ["cntrPivTFBG", "cntrPiv2TFBG", "upLoc2TFBG", "upLocTFBG"]:
        sel = cmds.ls(sl=True)
        if sel and len(sel)!=1:
            cmds.warning("only select the curve you want to rig up!")
        else:
            if rig.isType(sel[0], "nurbsCurve"):
                cmds.textFieldButtonGrp(widgets[tfgKey], e=True, tx=sel[0])
            else:
                cmds.warning("That's not a curve!")
    else:
        sel = cmds.ls(sl=True)
        if sel and len(sel)!=1:
            cmds.warning("only select the object you want to rig up!")
        else:
            cmds.textFieldButtonGrp(widgets[tfgKey], e=True, tx=sel[0])
            if tfgKey == "upLocTFBG":
                cmds.textFieldButtonGrp(widgets["upLoc2TFBG"], e=True, tx=sel[0])
            if tfgKey == "cntrPivTFBG":
                cmds.textFieldButtonGrp(widgets["cntrPiv2TFBG"], e=True, tx=sel[0])
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def scale_the_objects(scaleVal, *args):
    """
    does the scaling bits
    """
    sel = cmds.ls(sl=True, type="transform")
    if sel:
        for obj in sel:
            if (rig.isType(obj, "nurbsSurface")) or (rig.isType(obj, "nurbsCurve")):
                piv = cmds.xform(obj, q=True, ws=True, rp=True)
                cvs = cmds.select((obj + ".cv[*]"))
                cmds.scale(scaleVal, scaleVal, scaleVal, cvs, pivot=piv)
            elif rig.isType(obj, "mesh"):
                piv = cmds.xform(obj, q=True, ws=True, rp=True)
                vs = cmds.select((obj + ".vtx[*]"))
                cmds.scale(scaleVal, scaleVal, scaleVal, vs, pivot=piv)
            else:
                cmds.warning("{0} isn't a nurbs or poly object, so it was skipped".format(obj))
    # clear and reselect all
    if sel:
        cmds.select(cl=True)
        cmds.select(sel)
        return (True)

    return (False)
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def reparameter(*args):
    """
    reparameterizes curves to be from 0-1
    Args:
    Returns:
    """
    sel = cmds.ls(sl=True, exactType = "transform")

    check = False
    newCrvs = []

    if sel:
        for x in sel:
            check = rig.isType(x, "nurbsCurve")
            if check:
                crv = x
                newCrv = cmds.rebuildCurve(crv, constructionHistory=False, rebuildType = 0, keepControlPoints=True,  keepRange = 0, replaceOriginal=True, name = "{0}_RB".format(crv))[0]

            # reconnect parents and children of orig curve

            else:
                cmds.warning("{0} is not a nurbsCurve object. Skipping!".format(x))

    cmds.select(sel, r=True)
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def align_along_curve(*args):
    """
    aligns and objet along a curve at given param
    Args:
        *args:
    Returns:
        void
    """
    sel = cmds.ls(sl=True, type="transform")
    if len(sel) != 2:
        cmds.warning("You need to select curve then object to align!")
        return()
    crv = sel[0]
    obj = sel[1]
    if not rig.isType(crv, "nurbsCurve"):
        cmds.warning("select curve first, THEN object")
        return()

    param = cmds.floatFieldGrp(widgets["alExFFG"], q=True, v1=True)

    rig.align_to_curve(crv, obj, param)
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def preciseRemovePercent(keepNum, *args):
    """selects the exact amount of things to remove and randomly selects which from the selection list"""

    sel = cmds.ls(sl=True, fl=True)

    remNum = (100.0-keepNum)/100.0
    remCount = int(remNum*len(sel))

    count = 0
    ch = []

    if sel:
        while len(ch)<remCount:
            x = random.choice(sel)
            if x not in ch:
                ch.append(x)

    newSel = [g for g in sel if g not in ch]
    cmds.select(newSel, r=True)
    print len(newSel), "objects remaining"
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def selectComponents(*args):
    sel = cmds.ls(sl=True)

    if sel:

        for obj in sel:
            shape = cmds.listRelatives(obj, s=True)[0]

            if cmds.objectType(shape) == "nurbsCurve":
                cmds.select(cmds.ls("{}.cv[*]".format(obj), fl=True))

            elif cmds.objectType(shape) == "mesh":
                cmds.select(cmds.ls("{}.vtx[*]".format(obj), fl=True))

            else:
                return
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def capReplace(*args):
    sel = cmds.ls(sl=True, type="transform")

    if sel < 2:
        cmds.warning("You don't have two things selected (cap and one ctrl minimum)!")
        return

    newCap = sel[0]
    ctrls = sel[1:]
    for ctrl in ctrls:
        oldCap = cmds.connectionInfo("{0}.capRig".format(ctrl), sfd=True).partition(".")[0]
        dupe = rig.swapDupe(newCap, oldCap, delete=True, name=oldCap)
        cmds.connectAttr("{0}.rotateCap".format(ctrl), "{0}.rotateY".format(dupe))
        cmds.connectAttr("{0}.message".format(dupe), "{0}.capRig".format(ctrl))
        cmds.setAttr("{0}.v".format(dupe), 1)

    # if not already, parent cap replace obj in folder and hide
    par = cmds.listRelatives(newCap, p=True)
    if not par or par[0] != "pastaRigSetupComponents_Grp":
        cmds.parent(newCap, "pastaRigSetupComponents_Grp")

    cmds.setAttr("{0}.v".format(newCap), 0)
    cmds.select(ctrls, r=True)
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def addBaseCap(*args):
    sel = cmds.ls(sl=True, type="transform")

    if sel < 2:
        cmds.warning("You don't have two things selected (cap and one ctrl minimum)!")
        return

    newCap = sel[0]
    ctrls = sel[1:]

    for ctrl in ctrls:
        tempCap = cmds.connectionInfo("{0}.tempBaseCap".format(ctrl), sfd=True).partition(".")[0]

        dupe = rig.swapDupe(newCap, tempCap, delete=True, name="{0}_baseCap".format(ctrl))
        cmds.setAttr("{0}.v".format(dupe), 1)
        cmds.connectAttr("{0}.rotateBaseCap".format(ctrl), "{0}.rotateY".format(dupe))
        cmds.connectAttr("{0}.message".format(dupe), "{0}.tempBaseCap".format(ctrl))

    # if not already, parent cap replace obj in folder and hide
    par = cmds.listRelatives(newCap, p=True)
    if not par or par[0] != "pastaRigSetupComponents_Grp":
        cmds.parent(newCap, "pastaRigSetupComponents_Grp")

    cmds.setAttr("{0}.v".format(newCap), 0)
    cmds.select(ctrls, r=True)
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def groupOrient(target='none',orig='none', group="GRP"):
    """
    groups the second object and snaps the group to the second (point and orient). The group arg is to name the suffix you want the group to have (default is '_GRP')
    Arguments: target (to be constrained to), orig (obj to move), group (suffix for group)
    """
    if (target == "none"):
        sel = getTwoSelection()
        target = sel[0]
        orig = sel[1]

    cmds.select(orig)
    grpName = "%s_%s"%(orig,group)
    cmds.group(name=grpName)
    pc = cmds.pointConstraint(target, grpName)
    oc = cmds.orientConstraint(target, grpName)
    cmds.delete(pc)
    cmds.delete(oc)
    cmds.select(clear=True)

    return(grpName)
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def import_animation(*args):
    """imports the anim (from rand selection of list items) onto selected objs"""
    lo, hi = cmds.intFieldGrp(widgets["rangeIFG"], q=True, v=True)
    rand = cmds.radioButtonGrp(widgets["randRBG"], q=True, sl=True)
    clips = cmds.textScrollList(widgets["animTSL"], q=True, si=True)
    path = cmds.textFieldButtonGrp(widgets["impPathTFG"], q=True, tx=True)
    options = {"targetTime":3, "time": 1, "option":"insert", "connect":1}

    delKeys = cmds.checkBoxGrp(widgets["delCBG"], q=True, v1=True)
    sel = cmds.ls(sl=True)
    for obj in sel:
        startF = cmds.currentTime(q=True)
        if rand == 1:   
            startF = random.randint(lo, hi)
            cmds.currentTime(startF)
        if delKeys:
            delete_later_keys(obj, startF)
        cmds.select(obj, r=True)
        myClip = random.choice(clips)
        animPath = "{0}/{1}".format(path, myClip)
        cmds.file(animPath, i = True, type = "animImport", ignoreVersion = True, options = "targetTime={0};time={1};copies=1;option={2};pictures=0;connect={3};".format(options["targetTime"], startF, options["option"], options["connect"]), preserveReferences=True)

    cmds.select(sel, r=True)
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def follicleUI(*args):
    """UI for the script"""

    if cmds.window("folWin", exists=True):
        cmds.deleteUI("folWin")

    widgets["win"] = cmds.window("folWin", t="zbw_makeFollicle", w=300, h=100)
    widgets["mainCLO"] = cmds.columnLayout()
    # widgets["polyFrame"] = cmds.frameLayout(l="Polygon Vert(s) Follicle")
    # widgets["polyCLO"] = cmds.columnLayout()
    widgets["text"] = cmds.text("Select one or two vertices (2 will get avg position) and run")
    widgets["nameTFG"] = cmds.textFieldGrp(l="FollicleName:", cal=([1, "left"],[2,"left"]), cw=([1,100],[2,200]), tx="follicle")
    cmds.separator(h=10)
    widgets["button"] = cmds.button(w=300, h=50, bgc=(0.6,.8,.6), l="Add follicle to vert(s)", c=getUV)
    # cmds.setParent(widgets["mainCLO"])
    # widgets["nurbsFrame"] = cmds.frameLayout(l="Nurbs select")
    cmds.showWindow(widgets["win"])
    cmds.window(widgets["win"], e=True, w=300, h=100)
#-------could also select edit point????
#-------multiple selection and average uv position? Orrrr option to create multiple UV's, one on each vertex
#-------grab an edge and convert to 2 verts and get average. . .
#-------have option for distributed (select 2 verts and number of follicles, spread that num between the two uv positions)
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def addObjectsToScrollList(objs):
    """puts the list of things in the textScrollList"""

    clearScrollList()
    stringSearch = cmds.checkBox(widgets["stringMatchCB"], q=True, v=True)
    searchText = ""
    checkedObjs = []

    if stringSearch:
        searchText = getSearchText()

    if stringSearch and searchText:
        for obj in objs:
            # check if the string is in the name of obj
            if searchText.lower() in obj.lower():
                checkedObjs.append(obj)

    else:
        checkedObjs = objs

    for x in checkedObjs:
#---------------- here add rt click functions to select all shapes or select transform (if shape)
        cmds.textScrollList(widgets["resultsTSL"], e=True, a=x, doubleClickCommand=selectItemInList)
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def bevelEdges(*args):
    """select obj, this will randomly bevel some edges"""

    cutoffRaw = cmds.intSliderGrp(widgets["bpercISG"], q=True, v=True)
    cutoff = cutoffRaw/100.0

    sel = cmds.ls(sl=True)

    for obj in sel:

        edges = cmds.ls("%s.e[*]"%obj, fl=True)

        bevelList = []

        for edge in edges:
            rand = random.uniform(0,1)
            if rand <= cutoff:
                bevelList.append(edge)

        cmds.select(cl=True)
        cmds.select(bevelList, r=True)

        cmds.polyBevel(fraction = .5, offset = .05)
        cmds.select(sel, r=True)
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def getAttr(*args):
    """grabs the selected channel from the selected obj and puts the enum values into the list"""
    #--------here could require a channel of a specific name, then you could do it automagically (check for "follow", "spaces", "space", "ss", etc)
    obj = cmds.textFieldGrp(widgets["objTFG"], q=True, tx=True)
    cmds.select(obj, r=True)
    channels = cmds.channelBox ('mainChannelBox', query=True, selectedMainAttributes=True)
    print channels
    if (channels and (len(channels)==1)):
        if (cmds.attributeQuery(channels[0], node=obj, enum=True)):
            enumValue = cmds.attributeQuery(channels[0], node=obj, listEnum=True)
            values = enumValue[0].split(":")
            for value in values:
                cmds.textScrollList(widgets["spacesTSL"], e=True, append=value)
                #----------create a button for each one???
                #----------or have them be double clicked???
    else:
        cmds.warning("select only the enum space switch channel")
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def get_source_and_targets(*args):
    """
    checks current selection, first sel is source, remaining are targets
    args:
        None
    Return:
        list (string, list): [0] is the source, [1] is the list of targets
        or 
        None
    """
    sel = cmds.ls(sl=True)
    if sel and len(sel) > 1:
        src = sel[0]
        tgts = sel[1:]
        return (src, tgts)
    else:
        cmds.warning("You need to select at least two objects!")
        return (None, None)
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def locked_attr(*args):
    """
    creates a locked attr (I use as a separator). Uses the long name as the nice name (literal name in channel box)
    """
    attrName = cmds.textFieldButtonGrp(widgets["lockAttrTFBG"], q=True, tx=True)

    if attrName:
        sel = cmds.ls(sl=True)

        if sel:
            for obj in sel:
                try:
                    cmds.addAttr(obj, ln=attrName, nn=attrName, at="enum", en="-----", k=True)
                    cmds.setAttr("%s.%s" % (obj, attrName), l=True)
                except:
                    cmds.warning("Failed to add %s to %s, skipping!" % (attrName, obj))
        else:
            cmds.warning("Please select some objects to add attr to!")
    else:
        cmds.warning("Please enter a name for the attr!")
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def add_zero_one_attribute(attrType, *args):
    """
    adds an attribute with range of 0 to 1 to each selected obj
    :param attrType: either "short" or "float"
    :param args:
    :return:
    """
    sel = cmds.ls(sl=True)
    if not sel:
        cmds.warning("You need to select an object add attrs to!")
        return()
    attrName = cmds.textFieldGrp(widgets["newAttrTFG"], q=True, tx=True)
    if not attrName:
        cmds.warning("Please enter a name for the attribute in the field!")
        return()
    for obj in sel:
        try:
            cmds.addAttr(obj, ln=attrName, at=attrType, min=0, max=1, dv=0, k=True)
        except:
            cmds.warning("Couldn't add attr: {0} to object: {1}. Skipping.".format(attrName, obj))
项目:core    作者:getavalon    | 项目源码 | 文件源码
def maintained_selection():
    """Maintain selection during context

    Example:
        >>> scene = cmds.file(new=True, force=True)
        >>> node = cmds.createNode("transform", name="Test")
        >>> cmds.select("persp")
        >>> with maintained_selection():
        ...     cmds.select("Test", replace=True)
        >>> "Test" in cmds.ls(selection=True)
        False

    """

    previous_selection = cmds.ls(selection=True)
    try:
        yield
    finally:
        if previous_selection:
            cmds.select(previous_selection,
                        replace=True,
                        noExpand=True)
        else:
            cmds.select(deselect=True,
                        noExpand=True)
项目:gozbruh    作者:LumaPictures    | 项目源码 | 文件源码
def get_goz_objs():
    """Grab meshes from selection, filter out extraneous DAG objects and
    freeze transforms on objects.
    """
    objs = cmds.ls(selection=True, type='mesh', dag=True)
    if objs:
        xforms = cmds.listRelatives(objs, parent=True, fullPath=True)
        # freeze transform
        cmds.makeIdentity(xforms, apply=True, t=1, r=1, s=1, n=0)
        cmds.select(xforms)
        objs = cmds.ls(selection=True)
    return objs

#------------------------------------------------------------------------------
# Renaming
#------------------------------------------------------------------------------
项目: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 copySkinComponents(source, destinationVerts):

    if not mc.listRelatives(source, shapes=True):
        raise RuntimeError('Source object must be geometry.')

    sourceSkin = getSkinCluster(source)

    if not sourceSkin:
        raise RuntimeError("Source mesh doesn't have a skinCluster to copy from.")

    destMesh = mc.ls(destinationVerts[0], o=True)[0]
    destMesh = mc.listRelatives(destMesh, parent=True)[0]
    destSkin = copySkinInfluences(source, destMesh)

    tempSet = mc.sets(destinationVerts)

    mc.select(source, tempSet)

    mc.copySkinWeights(noMirror=True,
                       surfaceAssociation='closestPoint', 
                       influenceAssociation='closestJoint', 
                       normalize=True)    

    mc.delete(tempSet)
    mc.select(destinationVerts)
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def _populateSelectionField(self, channel, field, *args):

        selectedChannels = None
        if channel:
            selectedChannels = getSelectedChannels()
            if not selectedChannels:
                raise RuntimeError('Please select an attribute in the channelBox.')
            if len(selectedChannels) > 1:
                raise RuntimeError('Please select only one attribute.')

        sel = mc.ls(sl=True)
        if not sel:
            raise RuntimeError('Please select a node.')
        if len(sel) > 1:
            raise RuntimeError('Please select only one node.')

        selection = sel[0]
        if selectedChannels:
            selection = selection+'.'+selectedChannels[0]

        mc.textFieldButtonGrp(field, edit=True, text=selection)
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def _populateSelectionList(self, channel, control, *args):

        selectedChannels = None
        if channel:
            selectedChannels = getSelectedChannels()
            if not selectedChannels:
                raise RuntimeError('Please select an attribute in the channelBox.')
            if len(selectedChannels) > 1:
                raise RuntimeError('Please select only one attribute.')

        sel = mc.ls(sl=True)
        if not sel:
            raise RuntimeError('Please select a node.')
        if len(sel) > 1:
            raise RuntimeError('Please select only one node.')

        selection = sel[0]
        if selectedChannels:
            selection = selection+'.'+selectedChannels[0]

        mc.textScrollList(control, edit=True, append=[selection])
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def copySingle(source=None, destination=None, pasteMethod='replace', offset=0, addToLayer=False, rotateOrder=True):
    '''
    Copy animation from a source node and paste it to a destination node
    '''

    start, end = _getStartAndEnd()

    if not source and not destination:
        sel = mc.ls(sl=True)
        if len(sel) != 2:
            OpenMaya.MGlobal.displayWarning('Please select exactly 2 objects.')
            return

        source = sel[0]
        destination = sel[1]

    layer = None
    if addToLayer:
        layer = utl.createAnimLayer(destination, namePrefix='ml_cp')

    copyAnimation(source=source, destination=destination, pasteMethod=pasteMethod, offset=offset, start=start, end=end, layer=layer, rotateOrder=rotateOrder)

    #if sel:
        #mc.select(sel)
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def toLocators(bakeOnOnes=False, space='world', spaceInt=None, constrainSource=False):
    '''
    Creates locators, and bakes their position to selection.
    Creates connections to the source objects, so they can 
    be found later to bake back.
    '''

    if spaceInt and 0 <= spaceInt <= 2:
        space = ['world', 'camera', 'last'][spaceInt]

    sel = mc.ls(sl=True)
    parent = None
    if space == 'camera':
        parent = utl.getCurrentCamera()
    elif space == 'last':
        parent = sel[-1]
        sel = sel[:-1]

    mc.select(sel)
    matchBakeLocators(parent=parent, bakeOnOnes=bakeOnOnes, constrainSource=constrainSource)
项目:ChainMaker    作者:XJZeng    | 项目源码 | 文件源码
def run_command(self, *args):
        curve_sel = self.curve_name()
        vert_sel_list = cmds.ls(sl=True, fl = True)
        if '.' in vert_sel_list[0]:
            dummy_item_index = vert_sel_list[0].index('.')
            self.geo_name = vert_sel_list[0][0:dummy_item_index]

        Chain_Constrain(curve_sel, vert_sel_list, self.geo_name)
        Spline_Rig_Chain(curve_sel, vert_sel_list)

        self.chain_list = cmds.listRelatives(str(self.geo_name + '_geo_grp'))

        joint_list = cmds.ls(type = 'joint')

        for dummy_geo in self.chain_list:
            cmds.select(dummy_geo, add = True)

        for dummy_joint in joint_list:
            if 'ikHandle' in dummy_joint:
                pass
            elif curve_sel in dummy_joint:
                 cmds.select(dummy_joint, add=True)
        cmds.select('ikHandle*', d = True)          
        mel.eval('newBindSkin " -byClosestPoint -toSkeleton";')
项目:PythonForMayaSamples    作者:dgovil    | 项目源码 | 文件源码
def makeTeeth(self, teeth=10, length=0.3):
        # The logic here is exactly the same as in the makeTeeth function we created
        cmds.select(clear=True)
        faces = self.getTeethFaces(teeth)
        for face in faces:
            cmds.select('%s.%s' % (self.transform, face), add=True)

        # Instead of returning a value, lets just store the extrude node onto the class as a class variable
        self.extrude = cmds.polyExtrudeFacet(localTranslateZ=length)[0]
        cmds.select(clear=True)
项目:config    作者:mindbender-studio    | 项目源码 | 文件源码
def _maintained_selection_decorator(func):
    """Function decorator to maintain the selection once called

    Example:
        >>> @_maintained_selection
        ... def my_function():
        ...    # Modify selection
        ...    cmds.select(clear=True)
        ...
        >>> # Selection restored

    """

    def wrapper(*args, **kwargs):
        previous_selection = cmds.ls(selection=True)
        try:
            return func(*args, **kwargs)
        finally:
            if previous_selection:
                cmds.select(previous_selection,
                            replace=True,
                            noExpand=True)
            else:
                cmds.select(deselect=True,
                            noExpand=True)

    return wrapper
项目:config    作者:mindbender-studio    | 项目源码 | 文件源码
def parent_group(source, transferTransform=True):
    """Create and transfer transforms to parent group"""
    assert cmds.objExists(source), "%s does not exist" % source
    assert cmds.nodeType(source) == "transform", (
        "%s must be transform" % source)

    parent = cmds.listRelatives(source, parent=True)

    if transferTransform:
        group = cmds.createNode("transform", n="%s_parent" % source)
        match_transform(group, source)

        try:
            cmds.parent(source, group)
        except Exception:
            cmds.warning("Failed to parent child under new parent")
            cmds.delete(group)

        if parent:
            cmds.parent(group, parent[0])

    else:
        cmds.select(source)
        group = cmds.group(n="%s_parent" % source)

    return group
项目:config    作者:mindbender-studio    | 项目源码 | 文件源码
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))
项目:config    作者:mindbender-studio    | 项目源码 | 文件源码
def process(self, context, plugin):
        from maya import cmds
        cmds.select(plugin.assemblies)
项目:config    作者:mindbender-studio    | 项目源码 | 文件源码
def process(self, instance):
        import os
        import polly
        from maya import cmds
        from avalon import maya

        dirname = polly.format_staging_dir(
            root=instance.context.data["workspaceDir"],
            time=instance.context.data["time"],
            name=instance.data["name"])

        try:
            os.makedirs(dirname)
        except OSError:
            pass

        filename = "{name}.ma".format(**instance.data)

        path = os.path.join(dirname, filename)

        # Perform extraction
        self.log.info("Performing extraction..")
        with maya.maintained_selection(), maya.without_extension():
            cmds.select(instance, noExpand=True)
            cmds.file(path,
                      force=True,
                      typ="mayaAscii",
                      exportSelected=True,
                      preserveReferences=False,
                      constructionHistory=True)

        # Store reference for integration
        if "files" not in instance.data:
            instance.data["files"] = list()

        instance.data["files"].append(filename)
        instance.data["stagingDir"] = dirname

        self.log.info("Extracted {instance} to {path}".format(**locals()))
项目:cmt    作者:chadmv    | 项目源码 | 文件源码
def zero_orient(joints):
    for joint in joints:
        children = _unparent_children(joint)
        cmds.setAttr('{0}.jointOrient'.format(joint), 0, 0, 0)
        _reparent_children(joint, children)

    if joints:
        cmds.select(joints)
项目:cmt    作者:chadmv    | 项目源码 | 文件源码
def template_joints(joints=None, reorient_children=True, reset_orientation=True):
    if joints is None:
        joints = cmds.ls(sl=True, type='joint')
    if not joints:
        raise RuntimeError('No joint selected to orient.')

    if reorient_children:
        children = cmds.listRelatives(fullPath=True, allDescendents=True, type='joint')
        joints.extend(children)

    red, green, blue = create_shaders()

    orient_group = cmds.createNode('transform', name=ORIENT_GROUP)
    manips = []
    for joint in joints:
        if reset_orientation:
            cmds.makeIdentity(joint, apply=True)
            cmds.joint(joint, edit=True, orientJoint='xyz', secondaryAxisOrient='yup', children=False, zeroScaleOrient=True)
        if not cmds.listRelatives(joint, children=True):
            zero_orient([joint])
            continue
        group, manip = create_orient_manipulator(joint, blue)
        manips.append(manip)
        cmds.parent(group, orient_group)
        cmds.parentConstraint(joint, group)
        cmds.setAttr(joint + '.template', 1)
    cmds.select(manips)
项目:cmt    作者:chadmv    | 项目源码 | 文件源码
def create_orient_manipulator(joint, material):
    joint_scale = cmds.jointDisplayScale(query=True)
    joint_radius = cmds.getAttr('{0}.radius'.format(joint))
    radius = joint_scale * joint_radius
    children = cmds.listRelatives(joint, children=True, path=True)
    if children:
        p1 = cmds.xform(joint, q=True, ws=True, t=True)
        p1 = OpenMaya.MPoint(*p1)
        p2 = cmds.xform(children[0], q=True, ws=True, t=True)
        p2 = OpenMaya.MPoint(*p2)
        radius = p1.distanceTo(p2)
    arrow_cvs = [[-1, 0, 0], [-1, 2, 0], [-2, 2, 0], [0, 4, 0], [2, 2, 0], [1, 2, 0], [1, 0, 0], [-1, 0, 0]]
    arrow_cvs = [[x[0]*radius, x[1]*radius, x[2]*radius] for x in arrow_cvs]
    shape = cmds.curve(name='{0}_zForward'.format(joint), degree=1, point=arrow_cvs)
    # shape = cmds.sphere(n='{0}_zForward'.format(joint), p=(0, 0, 0), ax=(0, 0, -1), ssw=0, esw=180, r=radius, d=3, ut=0, tol=0.01, s=8, nsp=4, ch=0)[0]
    # cmds.setAttr('{0}.sz'.format(shape), 0)
    # cmds.select(shape)
    # cmds.hyperShade(assign=material)
    group = cmds.createNode('transform', name='{0}_grp'.format(shape))
    cmds.parent(shape, group)
    cmds.makeIdentity(shape, apply=True)
    cmds.addAttr(shape, longName=MESSAGE_ATTRIBUTE, attributeType='message')
    cmds.connectAttr('{0}.message'.format(joint), '{0}.{1}'.format(shape, MESSAGE_ATTRIBUTE))
    for attr in ['tx', 'ty', 'tz', 'ry', 'rz', 'v']:
        cmds.setAttr('{0}.{1}'.format(shape, attr), lock=True, keyable=False)
    return group, shape
项目:cmt    作者:chadmv    | 项目源码 | 文件源码
def dump(curves=None, stack=False):
    """Get a data dictionary representing all the given curves.

    :param curves: Optional list of curves.
    :return: A json serializable list of dictionaries containing the data required to recreate the curves.
    """
    if curves is None:
        curves = cmds.ls(sl=True) or []
    data = []
    for node in curves:
        shape = shortcuts.get_shape(node)
        if cmds.nodeType(shape) == 'nurbsCurve':
            control = {
                'name': node,
                'cvs': cmds.getAttr('{0}.cv[*]'.format(node)),
                'degree': cmds.getAttr('{0}.degree'.format(node)),
                'form': cmds.getAttr('{0}.form'.format(node)),
                'xform': cmds.xform(node, q=True, ws=True, matrix=True),
                'knots': get_knots(node),
                'pivot': cmds.xform(node, q=True, rp=True),
                'overrideEnabled': cmds.getAttr('{0}.overrideEnabled'.format(node)),
                'overrideRGBColors': cmds.getAttr('{0}.overrideRGBColors'.format(node)),
                'overrideColorRGB': cmds.getAttr('{0}.overrideColorRGB'.format(node))[0],
                'overrideColor': cmds.getAttr('{0}.overrideColor'.format(node)),
            }
            if stack:
                control['stack'] = get_stack_count(node)
                control['parent'] = get_stack_parent(node)
            data.append(control)
    if curves:
        cmds.select(curves)
    return data
项目:cmt    作者:chadmv    | 项目源码 | 文件源码
def test_duplicate_chain(self):
        for i in range(5):
            cmds.joint(p=(0, i, 0))
        cmds.select(cl=True)
        for i in range(5):
            cmds.joint(p=(i+1, 0, 0))
        cmds.parent('joint6', 'joint2')
        joints, original_joints = shortcuts.duplicate_chain('joint1', 'joint5',
                                                            search_for='joint', replace_with='dupejoint')
        self.assertEqual(5, len(joints))
        self.assertListEqual(['dupejoint{0}'.format(x) for x in range(1, 6)], joints)
        self.assertListEqual(['joint{0}'.format(x) for x in range(1, 6)], original_joints)
项目:surume    作者:tm8r    | 项目源码 | 文件源码
def _select(self, *args):
        selected = cmds.textScrollList(self.text_scroll, q=True, si=True)
        if not selected:
            return
        camera = selected[0]
        cmds.select(camera)
项目:surume    作者:tm8r    | 项目源码 | 文件源码
def _select_file_node(self, index):
        u"""index?????????????????

        :param index: TableView??????index
        :type index: QModelIndex
        """
        index = self.proxy_model.mapToSource(index)
        if not index.isValid():
            return
        model = self.model.items[index.row()]
        cmds.select(model.node)