Python pymel.core.ls() Examples

The following are 30 code examples of pymel.core.ls(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pymel.core , or try the search function .
Example #1
Source File: rigging.py    From anima with MIT License 6 votes vote down vote up
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 
Example #2
Source File: render.py    From anima with MIT License 6 votes vote down vote up
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) 
Example #3
Source File: auxiliary.py    From anima with MIT License 6 votes vote down vote up
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 
Example #4
Source File: rigging.py    From anima with MIT License 6 votes vote down vote up
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 
Example #5
Source File: auxiliary.py    From anima with MIT License 6 votes vote down vote up
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)
                ) 
Example #6
Source File: anim_utils.py    From mgear_core with MIT License 6 votes vote down vote up
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) 
Example #7
Source File: rigging.py    From anima with MIT License 6 votes vote down vote up
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) 
Example #8
Source File: extension.py    From anima with MIT License 6 votes vote down vote up
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 
Example #9
Source File: validate_intermediate_shapes.py    From pyblish-bumpybox with GNU Lesser General Public License v3.0 6 votes vote down vote up
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) 
Example #10
Source File: freeze.py    From SISideBar with MIT License 6 votes vote down vote up
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) 
Example #11
Source File: render.py    From anima with MIT License 5 votes vote down vote up
def vertigo_delete(cls):
        """deletes the Vertigo setup for the selected camera
        """
        from anima.env.mayaEnv import vertigo
        cam = pm.ls(sl=1)[0]
        vertigo.delete(cam) 
Example #12
Source File: rigging.py    From anima with MIT License 5 votes vote down vote up
def replace_controller_shape(cls):
        selection = pm.ls(sl=1)
        if len(selection) < 2:
            return
        objects = selection[0]
        joints = selection[1]
        shape = pm.listRelatives(objects, s=True)
        joint_shape = pm.listRelatives(joints, s=True)
        parents = pm.listRelatives(objects, p=True)
        if len(parents):
            temp_list = pm.parent(objects, w=True)
            objects = temp_list
        temp_list = pm.parent(objects, joints)
        objects = temp_list[0]
        pm.makeIdentity(objects, apply=True, t=1, r=1, s=1, n=0)
        temp_list = pm.parent(objects, w=True)
        objects = temp_list[0]
        if len(joint_shape):
            pm.delete(joint_shape)
        for i in range(0, len(shape)):
            name = "%sShape%f" % (joints, (i + 1))
            shape[i] = pm.rename(shape[i], name)
            temp_list = pm.parent(shape[i], joints, r=True, s=True)
            shape[i] = temp_list[0]
        pm.delete(objects)
        pm.select(joints) 
Example #13
Source File: render.py    From anima with MIT License 5 votes vote down vote up
def standin_to_bbox(cls):
        """convert the selected stand-in nodes to bbox
        """
        [node.mode.set(0) for node in pm.ls(sl=1) if isinstance(node.getShape(), pm.nt.AiStandIn)] 
Example #14
Source File: rigging.py    From anima with MIT License 5 votes vote down vote up
def select_joints_deforming_object(cls):
        selection = pm.ls(sl=1)
        conn = pm.listHistory(selection[0])
        skin_cluster = ""
        for i in range(0, len(conn)):
            if conn[i].type() == "skinCluster":
                skin_cluster = conn[i]
                break
        conn = pm.listConnections(skin_cluster)
        joints = []
        for item in conn:
            if item.type() == "joint":
                joints.append(item)
        pm.select(joints) 
Example #15
Source File: render.py    From anima with MIT License 5 votes vote down vote up
def delete_render_layers(cls):
        """Deletes the render layers in the current scene
        """
        # switch to default render layer before deleting anything
        # this will prevent layers to be non-deletable
        from anima.env.mayaEnv import auxiliary
        auxiliary.switch_to_default_render_layer()
        pm.delete(pm.ls(type=['renderLayer'])) 
Example #16
Source File: render.py    From anima with MIT License 5 votes vote down vote up
def normalize_texture_paths(cls):
        """Expands the environment variables in texture paths
        """
        import os
        for node in pm.ls(type='file'):
            if node.hasAttr('colorSpace'):
                color_space = node.colorSpace.get()
            node.fileTextureName.set(
                os.path.expandvars(node.fileTextureName.get())
            )
            if node.hasAttr('colorSpace'):
                node.colorSpace.set(color_space) 
Example #17
Source File: render.py    From anima with MIT License 5 votes vote down vote up
def rsproxy_display_mode_toggle(cls, display_mode=0):
        """sets the display mode on selected proxies

        :param display_mode:

          0: Bounding Box
          1: Preview Mesh
          2: Linked Mesh
          3: Hide In Viewport
        :return:
        """
        for node in pm.ls(sl=1):
            hist = node.getShape().listHistory()
            proxy = hist[1]
            proxy.displayMode.set(display_mode) 
Example #18
Source File: render.py    From anima with MIT License 5 votes vote down vote up
def connect_facingRatio_to_vCoord(cls):
        selection = pm.ls(sl=1)
        for i in range(1, len(selection)):
            selection[0].facingRatio.connect((selection[i] + '.vCoord'),
                                             force=True) 
Example #19
Source File: rigging.py    From anima with MIT License 5 votes vote down vote up
def set_clusters_relative_state(cls, relative_state):
        selection = pm.ls(sl=1)
        cluster = ""
        for clusterHandle in selection:
            conn = pm.listConnections(clusterHandle)
            for i in range(0, len(conn)):
                if conn[i].type() == "cluster":
                    cluster = conn[i]
                    break
            cluster.relative.set(relative_state) 
Example #20
Source File: rigging.py    From anima with MIT License 5 votes vote down vote up
def create_axial_correction_group_for_clusters(cls):
        selection = pm.ls(sl=1)
        Rigging.axial_correction_group()
        pm.select(cl=1)
        for cluster_handle in selection:
            cluster_handle_shape = pm.listRelatives(cluster_handle, s=True)
            cluster_parent = pm.listRelatives(cluster_handle, p=True)
            trans = cluster_handle_shape[0].origin.get()
            cluster_parent[0].translate.set(trans[0], trans[1], trans[2])
        pm.select(selection) 
Example #21
Source File: rigging.py    From anima with MIT License 5 votes vote down vote up
def axial_correction_group(cls):
        selection = pm.ls(sl=1)
        for item in selection:
            auxiliary.axial_correction_group(item) 
Example #22
Source File: auxiliary.py    From anima with MIT License 5 votes vote down vote up
def export_blend_connections():
    """Exports the connection commands from selected objects to the blendShape
    of another object. The resulted text file contains all the MEL scripts to
    reconnect the objects to the blendShape node. So after exporting the
    connection commands you can export the blendShape targets as another maya
    file and delete them from the scene, thus your scene gets lite and loads
    much more quickly.
    """
    selection_list = pm.ls(tr=1, sl=1, l=1)

    dialog_return = pm.fileDialog2(cap="Save As", fm=0, ff='Text Files(*.txt)')

    filename = dialog_return[0]
    print(filename)

    print("\n\nFiles written:\n--------------------------------------------\n")

    with open(filename, 'w') as fileId:
        for i in range(0, len(selection_list)):
            shapes = pm.listRelatives(selection_list[i], s=True, f=True)

            main_shape = ""
            for j in range(0, len(shapes)):
                if pm.getAttr(shapes[j] + '.intermediateObject') == 0:
                    main_shape = shapes
                    break
            if main_shape == "":
                main_shape = shapes[0]

            con = pm.listConnections(main_shape, t="blendShape", c=1, s=1, p=1)

            cmd = "connectAttr -f %s.worldMesh[0] %s;" % (
                ''.join(map(str, main_shape)),
                ''.join(map(str, con[0].name()))
            )
            print("%s\n" % cmd)
            fileId.write("%s\n" % cmd)

    print("\n------------------------------------------------------\n")
    print("filename: %s     ...done\n" % filename) 
Example #23
Source File: auxiliary.py    From anima with MIT License 5 votes vote down vote up
def unsetup(self):
        """deletes the barn door setup
        """
        if self.light:
            try:
                pm.delete(
                    self.light.attr(self.message_storage_attr_name).inputs()
                )
            except AttributeError:
                pass
            pm.scriptJob(
                k=int(self.light.getAttr(self.custom_data_storage_attr_name))
            )
        else:
            # try to delete the by using the barndoor group
            found_light = False
            for node in pm.ls(sl=1, type='transform'):
                # list all lights and try to find the light that has this group
                for light in pm.ls(type=pm.nt.Light):
                    light_parent = light.getParent()
                    if light_parent.hasAttr(self.message_storage_attr_name):
                        if node in light_parent.attr(
                                self.message_storage_attr_name).inputs():
                            self.light = light_parent
                            found_light = True
                            self.unsetup()

                # if the code comes here than this node is not listed in any
                # lights, so delete it if it contains the string
                # "barndoor_preview_curves" in its name
                if not found_light \
                        and "barndoor_preview_curves" in node.name():
                    pm.delete(node) 
Example #24
Source File: auxiliary.py    From anima with MIT License 5 votes vote down vote up
def create_script_job(self):
        """creates the script job that disables the affected highlight
        """
        script_job_no = pm.scriptJob(
            e=["SelectionChanged",
                'if pm.ls(sl=1) and pm.ls(sl=1)[0].name() == "%s":\n'
                '    pm.displayPref(displayAffected=False)\n'
                'else:\n'
                '    pm.displayPref(displayAffected=True)' % self.light.name()
            ]
        )
        self.store_data('%s' % script_job_no) 
Example #25
Source File: auxiliary.py    From anima with MIT License 5 votes vote down vote up
def get_cacheable_nodes():
    """returns the cacheable nodes from the current scene

    :return:
    """
    from anima.ui.progress_dialog import ProgressDialogManager
    from anima.env.mayaEnv import MayaMainProgressBarWrapper
    wrp = MayaMainProgressBarWrapper()
    pdm = ProgressDialogManager(dialog=wrp)
    pdm.close()

    # list all cacheable nodes
    cacheable_nodes = []
    tr_list = pm.ls(tr=1, type='transform')
    caller = pdm.register(len(tr_list), 'Searching for Cacheable Nodes')
    for tr in tr_list:
        if tr.hasAttr('cacheable') and tr.getAttr('cacheable'):
            # check if any of its parents has a cacheable attribute
            has_cacheable_parent = False
            for parent in tr.getAllParents():
                if parent.hasAttr('cacheable'):
                    has_cacheable_parent = True
                    break

            if not has_cacheable_parent:
                # only include direct references
                ref = tr.referenceFile()
                if ref is not None and ref.parent() is None:
                    # skip cacheable nodes coming from layout
                    if ref.version and ref.version.task.type \
                            and ref.version.task.type.name.lower() == 'layout':
                        caller.step()
                        continue
                cacheable_nodes.append(tr)

        caller.step()

    return cacheable_nodes 
Example #26
Source File: auxiliary.py    From anima with MIT License 5 votes vote down vote up
def restore_user_options(self):
        """restores user options
        """
        active_panel = self.get_active_panel()
        for flag, value in self.user_view_options['display_flags'].items():
            try:
                pm.modelEditor(active_panel, **{'e': 1, flag: value})
            except TypeError:
                pass

        # reassign original hud display options
        for hud, value in self.user_view_options['huds'].items():
            if pm.headsUpDisplay(hud, q=1, ex=1):
                pm.headsUpDisplay(hud, e=1, vis=value)

        # reassign original camera options
        for camera in pm.ls(type='camera'):
            camera_name = camera.name()

            try:
                camera_flags = \
                    self.user_view_options['camera_flags'][camera_name]
            except KeyError:
                continue

            for attr, value in camera_flags.items():
                try:
                    camera.setAttr(attr, value)
                except RuntimeError:
                    pass

        self.remove_hud(self.hud_name) 
Example #27
Source File: auxiliary.py    From anima with MIT License 5 votes vote down vote up
def store_user_options(self):
        """stores user options
        """
        # query active model panel
        active_panel = self.get_active_panel()

        # store show/hide display options for active panel
        self.reset_user_view_options_storage()

        for flag in self.display_flags:
            try:
                val = pm.modelEditor(active_panel, **{'q': 1, flag: True})
                self.user_view_options['display_flags'][flag] = val
            except TypeError:
                pass

        # store hud display options
        hud_names = pm.headsUpDisplay(lh=1)
        for hud_name in hud_names:
            val = pm.headsUpDisplay(hud_name, q=1, vis=1)
            self.user_view_options['huds'][hud_name] = val

        for camera in pm.ls(type='camera'):
            camera_name = camera.name()
            per_camera_attr_dict = {}
            for attr in self.cam_attribute_names:
                per_camera_attr_dict[attr] = camera.getAttr(attr)
            self.user_view_options['camera_flags'][camera_name] = \
                per_camera_attr_dict 
Example #28
Source File: auxiliary.py    From anima with MIT License 5 votes vote down vote up
def get_audio_node(cls):
        """returns the audio node from the time slider
        """
        audio_node_name = pm.timeControl(
            pm.melGlobals['$gPlayBackSlider'],
            q=1,
            sound=1
        )
        nodes = pm.ls(audio_node_name)
        if nodes:
            return nodes[0]
        else:
            return None 
Example #29
Source File: auxiliary.py    From anima with MIT License 5 votes vote down vote up
def get_default_render_layer():
    """Returns the default render layer
    :return:
    """
    return pm.ls(type='renderLayer')[0].defaultRenderLayer() 
Example #30
Source File: auxiliary.py    From anima with MIT License 5 votes vote down vote up
def align_to_pole_vector():
    """aligns the object to the pole vector of the selected ikHandle
    """
    selection_list = pm.ls(sl=1)

    ik_handle = ""
    control_object = ""

    for obj in selection_list:
        if pm.nodeType(obj) == 'ikHandle':
            ik_handle = obj
        else:
            control_object = obj

    temp = pm.listConnections((ik_handle + '.startJoint'), s=1)
    start_joint = temp[0]
    start_joint_pos = pm.xform(start_joint, q=True, ws=True, t=True)

    temp = pm.listConnections((ik_handle + '.endEffector'), s=1)
    end_effector = temp[0]
    pm.xform(
        control_object,
        ws=True,
        t=(start_joint_pos[0], start_joint_pos[1], start_joint_pos[2])
    )

    pm.parent(control_object, end_effector)
    pm.setAttr(control_object + '.r', 0, 0, 0)

    pm.parent(control_object, w=True)