Python源码示例:pymel.core.ls()

示例1
def freeze():
    cmds.selectMode(o=True)
    selection = cmds.ls(sl=True, type = 'transform')
    dummy = common.TemporaryReparent().main(mode='create')#モジュールでダミーの親作成
    clusterCopy = modeling.ClusterCopy()
    for sel in selection:
        allChildren = [sel] + cmds.listRelatives(sel, ad=True)#子供を取得して1つのリストにする
        polyMesh = common.search_polygon_mesh(allChildren)
        if polyMesh:
            for mesh in polyMesh:
                common.TemporaryReparent().main(mesh, dummyParent=dummy, mode='cut')
                defCls = clusterCopy.copy(mesh)
                cmds.bakePartialHistory(mesh,pc=True)
                if defCls:
                    clusterCopy.paste(mesh)
                common.TemporaryReparent().main(mesh, dummyParent=dummy, mode='parent')#コピーのおわったメッシュの子供を元に戻す
    common.TemporaryReparent().main(dummyParent=dummy, mode='delete')#ダミー親削除
    cmds.select(selection, r=True) 
示例2
def select_all_child_controls(control, *args):  # @unusedVariable
    """ Selects all child controls from the given control

    This function uses Maya's controller nodes and commands to find relevant
    dependencies between controls

    Args:
        control (str): parent animation control (transform node)
        *args: State of the menu item (if existing) send by mgear's dagmenu
    """

    # gets controller node from the given control. Returns if none is found
    tag = cmds.ls(cmds.listConnections(control), type="controller")
    if not tag:
        return

    # query child controls
    children = get_all_tag_children(tag)

    # adds to current selection the children elements
    cmds.select(children, add=True) 
示例3
def process(self, context, plugin):
        import pymel.core as pm

        # Get the errored instances
        failed = []
        for result in context.data["results"]:
            if (result["error"] is not None and result["instance"] is not None
               and result["instance"] not in failed):
                failed.append(result["instance"])

        # Apply pyblish.logic to get the instances for the plug-in
        instances = api.instances_by_plugin(failed, plugin)

        for instance in instances:
            for node in instance[0].members():
                io = pm.ls(node.getShapes(), intermediateObjects=True)
                pm.delete(io) 
示例4
def all_shots(self):
        """return all the shots connected to this sequencer
        """
        return pm.ls(self.shots.get(), typ='shot')

    # @extends(pm.nodetypes.Sequencer)
    # @all_shots.setter
    # def all_shots(self, shots):
    #     """setter for the all_shots property
    #     """
    #     # remove the current shots first
    #     # then append the new ones
    #     for s in self.all_shots:
    #         t = s // self.shots
    #
    #     for s in shots:
    #         t = s.message >> self.shots.next_available 
示例5
def rivet_per_face():
    """creates hair follicles per selected face
    """
    sel_list = pm.ls(sl=1, fl=1)

    follicles = []
    locators = []
    for face in sel_list:
        # use the center of the face as the follicle position
        p = reduce(lambda x, y: x + y, face.getPoints()) / face.numVertices()
        obj = pm.spaceLocator(p=p)
        locators.append(obj)
        shape = face.node()
        uv = face.getUVAtPoint(p, space='world')

        follicle_transform, follicle = create_follicle(shape, uv)

        pm.parent(obj, follicle_transform)
        follicles.append(follicle)

    return follicles, locators 
示例6
def check_sequence_name(self):
        """checks sequence name and asks the user to set one if maya is in UI
        mode and there is no sequence name set
        """
        sequencer = pm.ls(type='sequencer')[0]
        sequence_name = sequencer.getAttr('sequence_name')
        if sequence_name == '' and not pm.general.about(batch=1) \
           and not self.batch_mode:
            result = pm.promptDialog(
                title="Please enter a Sequence Name",
                message='Sequence Name:',
                button=['OK', 'Cancel'],
                defaultButton='OK',
                cancelButton='Cancel',
                dismissString='Cancel'
            )

            if result == 'OK':
                sequencer.setAttr(
                    'sequence_name',
                    pm.promptDialog(query=True, text=True)
                ) 
示例7
def setup_stretchy_spline_ik_curve(cls):
        """
        """
        selection = pm.ls(sl=1)
        curve = selection[0]
        curve_info = pm.createNode("curveInfo")
        mult_div = pm.createNode("multiplyDivide")
        curve_shape = pm.listRelatives(curve, s=1)

        curve_shape[0].worldSpace >> curve_info.ic
        curve_info.arcLength >> mult_div.input1X

        curve_length = curve_info.arcLength.get()
        mult_div.input2X.set(curve_length)
        mult_div.operation.set(2)
        pm.select(mult_div, curve_info, curve_shape[0], add=True) 
示例8
def reset_tweaks(cls):
        """Resets the tweaks on the selected deformed objects
        """
        for obj in pm.ls(sl=1):
            for tweak_node in pm.ls(obj.listHistory(), type=pm.nt.Tweak):

                try:
                    for i in tweak_node.pl[0].cp.get(mi=1):
                        tweak_node.pl[0].cv[i].vx.set(0)
                        tweak_node.pl[0].cv[i].vy.set(0)
                        tweak_node.pl[0].cv[i].vz.set(0)
                except TypeError:
                    try:
                        for i in tweak_node.vl[0].vt.get(mi=1):
                            tweak_node.vl[0].vt[i].vx.set(0)
                            tweak_node.vl[0].vt[i].vy.set(0)
                            tweak_node.vl[0].vt[i].vz.set(0)
                    except TypeError:
                        pass 
示例9
def get_pin_shader(self):
        """this creates or returns the existing pin shader
        """
        shaders = pm.ls("%s*" % self.pin_shader_prefix)
        if shaders:
            # try to find the shader with the same color
            for shader in shaders:
                if list(shader.color.get()) == self.color:
                    return shader

        # so we couldn't find a shader
        # lets create one
        shader = pm.shadingNode("lambert", asShader=1)
        shader.rename("%s#" % self.pin_shader_prefix)
        shader.color.set(self.color)

        # also create the related shadingEngine
        shading_engine = pm.nt.ShadingEngine()
        shading_engine.rename("%sSG#" % self.pin_shader_prefix)
        shader.outColor >> shading_engine.surfaceShader

        return shader 
示例10
def set_finalGatherHide(cls, value):
        """sets the finalGatherHide to on or off for the given list of objects
        """
        attr_name = "miFinalGatherHide"
        objects = pm.ls(sl=1)

        for obj in objects:

            shape = obj

            if isinstance(obj, pm.nt.Transform):
                shape = obj.getShape()

            if not isinstance(shape, (pm.nt.Mesh, pm.nt.NurbsSurface)):
                continue

            # add the attribute if it doesn't already exists
            if not shape.hasAttr(attr_name):
                pm.addAttr(shape, ln=attr_name, at="long", min=0, max=1, k=1)

            obj.setAttr(attr_name, value) 
示例11
def populateJoints(self, *args):
        """ This function is responsable to list all joints or only dpAR joints in the interface in order to use in skinning.
        """
        # get current jointType (all or just dpAutoRig joints):
        jntSelectedRadioButton = cmds.radioCollection(self.allUIs["jntCollection"], query=True, select=True)
        chooseJnt = cmds.radioButton(jntSelectedRadioButton, query=True, annotation=True)
        
        # list joints to be populated:
        jointList, sortedJointList = [], []
        allJointList = cmds.ls(selection=False, type="joint")
        if chooseJnt == "allJoints":
            jointList = allJointList
            cmds.checkBox(self.allUIs["_JntCB"], edit=True, enable=False)
            cmds.checkBox(self.allUIs["_JisCB"], edit=True, enable=False)
        elif chooseJnt == "dpARJoints":
            cmds.checkBox(self.allUIs["_JntCB"], edit=True, enable=True)
            cmds.checkBox(self.allUIs["_JisCB"], edit=True, enable=True)
            displayJnt = cmds.checkBox(self.allUIs["_JntCB"], query=True, value=True)
            displayJis = cmds.checkBox(self.allUIs["_JisCB"], query=True, value=True)
            for jointNode in allJointList:
                if cmds.objExists(jointNode+'.'+BASE_NAME+'joint'):
                    if displayJnt:
                        if "_Jnt" in jointNode:
                            jointList.append(jointNode)
                    if displayJis:
                        if "_Jis" in jointNode:
                            jointList.append(jointNode)
        
        # sort joints by name filter:
        jointName = cmds.textField(self.allUIs["jointNameTF"], query=True, text=True)
        if jointList:
            if jointName:
                sortedJointList = utils.filterName(jointName, jointList, " ")
            else:
                sortedJointList = jointList
        
        # populate the list:
        cmds.textScrollList( self.allUIs["jntTextScrollLayout"], edit=True, removeAll=True)
        cmds.textScrollList( self.allUIs["jntTextScrollLayout"], edit=True, append=sortedJointList)
        # atualize of footerB text:
        self.atualizeSkinFooter() 
示例12
def __init__(self):
        self.aDrivers = []  # List of parent in the system
        self.nDriven = None  # Base constrained objet (The constraint will no be set on this object
        self.nSwConst = None  # SpaceSwitch constraint for the system
        self.nSwConstRecept = None  # Constrained node
        self.aFreeIndex = []  # List of free index (Can only happen when a item is removed) in the parent constraint
        self.sSysName = "SpaceSwitcher_"  # Name of the system

        tempWorld = pymel.ls(self.WORLD_NODE_NAME)
        if tempWorld:
            self.worldNode = tempWorld[0]
        else:
            self.worldNode = None 
示例13
def get_all_ctrls():
    ctrls = pymel.ls('*_Ctrl')
    ctrls = filter(_is_ctrl, ctrls)
    return ctrls 
示例14
def get_all_ctrlsnapshots():
    snapshots = pymel.ls('*_CtrlSnapshot')
    snapshots = filter(_is_ctrl, snapshots)
    return snapshots 
示例15
def ls_ex(*args, **kwargs):
    return PyNodeChain(pymel.ls(*args, **kwargs))

# Wrapper for pymel.ls that return only objects without parents. 
示例16
def ls_root(*args, **kwargs):
    return PyNodeChain(filter(lambda x:x.getParent() is None, iter(pymel.ls(*args, **kwargs)))) 
示例17
def getNetworksByClass(_clsName):
    return [network for network in pymel.ls(type='network') if isNetworkInstanceOfClass(network, _clsName)]

# TODO: benchmark with sets 
示例18
def store_blend_shape(mesh):
    shapes = cmds.listRelatives(mesh, s=True, f=True)
    skin = cmds.ls(cmds.listHistory(shapes), type='skinCluster')
    if skin:
        connections = cmds.listConnections(skin, s=True, d=False)
    else:
        connections = cmds.listConnections(shapes, s=True, d=False)
    blend_shapes = cmds.ls(connections, l=True, type='blendShape')
    bs_dict = {}
    if blend_shapes:
        for bs in blend_shapes:
            shape_target = cmds.ls(cmds.listConnections(bs, s=True, d=False), l=True, type='transform')
            bs_dict[bs]=shape_target
        return bs_dict
    return 
示例19
def save_cluster(node):
    #ノードの中からスキンクラスタを取得してくる#inMesh直上がSkinClusterとは限らないので修正
    srcDeformerCluster = cmds.ls(cmds.listHistory(node),type='cluster')
    if not srcDeformerCluster:
        return#スキンクラスタがなかったら関数抜ける
    #スキンクラスタのパラメータ色々を取得しておく
    srcDeformerCluster = srcDeformerCluster[0]
    attributes = cmds.listAttr(srcDeformerCluster)
    weightList = cmds.getAttr(srcDeformerCluster+'.weightList[0]')
    envelope = cmds.getAttr(srcDeformerCluster+'.envelope')
    clusterMssage = cmds.getAttr(srcDeformerCluster+'.message')
    clusterWeight = cmds.getAttr(srcDeformerCluster+'.weightList[0].weights') 
示例20
def get_shading_engines(root_node=None):
    en_list = []
    if root_node is None:
        shapes = pm.ls(type="mesh")
    else:
        if isinstance(root_node, (str, unicode)):
            root_node = pm.PyNode(root_node)
        shapes = root_node.listRelatives(ad=True, type="mesh")
    file_nodes = []
    for i in shapes:
        shading_engines = i.shadingGroups()
        en_list+=shading_engines
    return list(set(en_list)) 
示例21
def copy(self, mesh):
        self.cluster_list = []
        self.point_dict = {}
        self.cls_weight_dict = {}
            
        dummy = common.TemporaryReparent().main(mode='create')
        common.TemporaryReparent().main(mesh, dummyParent=dummy, mode='cut')
        
        cluster = cmds.ls(cmds.listHistory(mesh), type='cluster', l=True)
        for cls in cluster:
            set_node = cmds.ls(cmds.listHistory(cls, f=True), type='objectSet', l=True)[0]
            cmds.select(set_node)
            vertices = cmds.ls(sl=True)
            vertices = cmds.filterExpand(vertices, sm=31)
            cmds.select(vertices, r=True)
            try:
                weights = cmds.percent(cls, q=True, v=True)
                print weights
            #値が取れないときアンドゥするとなぜか直ることがある
            except Exception as e:
                print e.message
                cmds.delete(cls)
                cmds.undo()
                set_node = cmds.ls(cmds.listHistory(cls, f=True), type='objectSet', l=True)[0]
                vertices = cmds.ls(sl=True)
                vertices = cmds.filterExpand(vertices, sm=31)
                cmds.select(vertices, r=True)
                weights = cmds.percent(cls, q=True, v=True)
            self.cluster_list.append(cls)
            self.cls_weight_dict[cls] = weights
            self.point_dict[cls] = vertices
        common.TemporaryReparent().main(mesh, dummyParent=dummy, mode='parent')#コピーのおわったメッシュの子供を元に戻す
        common.TemporaryReparent().main(dummyParent=dummy, mode='delete')#ダミー親削除
        return self.point_dict, self.cls_weight_dict 
示例22
def cehck_zero_poly_object(mesh=None, pop_msg=True):
    #mesh 入力メッシュ
    #pop_msg 探索結果を表示するかどうか
    if mesh == None:
        polyMeshes = common.search_polygon_mesh(cmds.ls(tr=True))
    else:
        polyMeshes = common.search_polygon_mesh(mesh)
    zeroPolyObj = []
    if polyMeshes == None:
        if pop_msg:
            cmds.confirmDialog( title="Check",message='Zero Polygon Object Count :  0')
        return zeroPolyObj
    for p in polyMeshes:
        vtx = cmds.polyListComponentConversion(p, tv=True)
        if vtx == []:
            zeroPolyObj.append(p)
    if not pop_msg:
        return zeroPolyObj
    if zeroPolyObj == []:
        cmds.confirmDialog( title="Check",message='Zero Polygon Object Count :  0')
    else:
        msg = 'Zero Polygon Object Count : '+str(len(zeroPolyObj))
        for p in zeroPolyObj:
            msg+='\n[ '+p+' ]'
        cmds.confirmDialog( title="Check",message=msg )
        cmds.select(zeroPolyObj, r=True)
    return zeroPolyObj
    
#スキニングを保ったままメッシュマージする関数 
示例23
def change_selection():
    #print '*+*+*+*+*+*+*+selection changed+*+*+*+*+*+*+* :', cmds.ls(sl=True)
    global bake_mode
    if bake_mode:
        return
    #return
    if group_mode:
        group_selection()
    #コンポーネント選択の時はアンドゥできなくなるのでヒストリ取得を無効にしてからマトリックス取得実行
    cmds.undoInfo(swf=False)
    get_matrix()
    cmds.undoInfo(swf=True)
    
    #コンテキストを切り替えてリアルタイム検出を有効にする。
    #restore_context_and_axis()
    #コンテキストのpodモードを選択タイプによって切り替える
    sb.chenge_manip_type()
    sb.change_selection_display()
    #オブジェクト変更があった場合はセンターをベイクして再度センターモードに入りなおす
    #print 'check center mode in culc :', center_mode
    if cmds.selectMode(q=True, o=True):
        if center_mode:
            #cmds.undoInfo(cn='cng_center', ock=True)
            sb.toggle_center_mode(mode=False, change=True)
            sb.toggle_center_mode(mode=True, change=True)
            #qt.Callback(sb.transform_center()
            sb.transform_center()
            #cmds.undoInfo(cn='cng_center', cck=True)
            return
    #COGモードチェックしておく
    sb.window.setup_object_center()
    #UIの変更を反映する
    sb.check_option_parm()
    
#コンテキストを切り替えてリアルタイム検出を有効にする。軸選択状態をサイドバーに復元する。
#選択タイプ検出時に直接実行するようになったので不要。 
示例24
def reset_selected_channels_value(objects=None, attributes=None):
    """Reset the the selected channels if not attribute is provided

    Args:
        objects (None, optional): The objects to reset the channels
        attribute (list, optional): The attribute to reset
    """
    if not objects:
        objects = cmds.ls(selection=True)
    if not attributes:
        attributes = getSelectedChannels()

    for obj in objects:
        for attr in attributes:
            set_default_value(obj, attr) 
示例25
def get_selected_channels_full_path():
    """Get the selected channels full path from channel box
    This function will collect channels from any area of the channel box. This
    include, Main, shape, input and output

    Returns:
        list: list of channels full path
    """
    attrs = []
    node = pm.ls(sl=True)
    if node:
        node = node[0]

        collect_attrs(
            node, attrs, pm.channelBox(get_channelBox(), q=True, sma=True))

        # if the attr is from shape node, we need to search in all shapes
        collect_attrs(node,
                      attrs,
                      pm.channelBox(get_channelBox(), q=True, ssa=True),
                      shapes=True)

        collect_attrs(
            node, attrs, pm.channelBox(get_channelBox(), q=True, sha=True))
        collect_attrs(
            node, attrs, pm.channelBox(get_channelBox(), q=True, soa=True))

    return attrs 
示例26
def getRootNode():
    """Returns the root node from a selected node

    Returns:
        PyNode: The root top node
    """

    root = None

    current = pm.ls(sl=True)
    if not current:
        raise RuntimeError("You need to select at least one rig node")

    if pm.objExists("{}.is_rig".format(current[0])):
        root = current[0]
    else:
        holder = current[0]
        while pm.listRelatives(holder, parent=True) and not root:
            if pm.objExists("{}.is_rig".format(holder)):
                root = holder
            else:
                holder = pm.listRelatives(holder, parent=True)[0]

    if not root:
        raise RuntimeError("Couldn't find root node from your selection")

    return root 
示例27
def quickSel(model, channel, mouse_button):
    """Select the object stored on the quick selection attributes

    Args:
        model (PyNode): The rig top node
        channel (str): The quick selection channel name
        mouse_button (QtSignal): Clicked mouse button

    Returns:
        None
    """
    qs_attr = model.attr("quicksel%s" % channel)

    if mouse_button == QtCore.Qt.LeftButton:  # Call Selection
        names = qs_attr.get().split(",")
        if not names:
            return
        pm.select(clear=True)
        for name in names:
            ctl = dag.findChild(model, name)
            if ctl:
                ctl.select(add=True)
    elif mouse_button == QtCore.Qt.MidButton:  # Save Selection
        names = [sel.name().split("|")[-1]
                 for sel in pm.ls(selection=True)
                 if sel.name().endswith("_ctl")]

        qs_attr.set(",".join(names))

    elif mouse_button == QtCore.Qt.RightButton:  # Key Selection
        names = qs_attr.get().split(",")
        if not names:
            return
        else:
            keyObj(model, names)


##################################################
# KEY
##################################################
# ================================================ 
示例28
def process(self, instance):
        import pymel.core as pm

        intermediate_objects = []
        for node in instance[0].members():
            io = pm.ls(node.getShapes(), intermediateObjects=True)
            intermediate_objects.extend(io)

        msg = "Intermediate objects present: %s" % intermediate_objects
        assert not intermediate_objects, msg 
示例29
def process(self, context, plugin):
        import pymel.core as pc

        for node in pc.ls(type="ftrackAssetNode"):
            if not node.assetLink.connections():
                pc.delete(node) 
示例30
def process(self, context):
        import pymel.core as pc

        for node in pc.ls(type="ftrackAssetNode"):
            msg = "Ftrack Asset link on \"{0}\" is broken.".format(node.name())
            assert node.assetLink.connections(), msg