Maya – Select 视口中的对象通过 Python

Maya – Select objects in viewport via Python

谁能帮帮我?是否可以使用 Python 制作脚本以自动 select Maya 视口中的每个对象?

可能吗?

你可以试试下面的脚本

import maya.OpenMaya as om
import maya.OpenMayaUI as omUI
view = omUI.M3dView.active3dView()
om.MGlobal.selectFromScreen( 0, 0, view.portWidth(), view.portHeight(),om.MGlobal.kReplaceList)

我在 https://forums.cgsociety.org/t/list-objects-in-viewport/1463426 上找到了这个片段,它似乎可以解决问题。您可以阅读讨论以获取更多信息

尽管您必须使用 Maya 的 api 才能做到这一点,但这是很有可能的。您可以使用 OpenMayaUI.MDrawTraversal 收集相机平截头体内的所有对象。

这似乎比使用 OpenMaya.MGlobal.selectFromScreen 更冗长,但它给您带来了一些好处:

  1. 您可以在任何相机上执行此操作,尽管它未用作活动视图。
  2. 您可以在内存中执行任何需要做的事情,而无需 selecting 和强制重绘。
  3. OpenMaya.MGlobal.selectFromScreen 将依赖于接口,这意味着它不可能在 Maya 批处理作业上执行。这将适用于任何一种情况。

也就是说,这是一个示例,它会创建一堆随机框,创建一个注视它们的相机,然后 select 相机视野内的所有框:

import random

import maya.cmds as cmds
import maya.OpenMaya as OpenMaya
import maya.OpenMayaUI as OpenMayaUI


# Create a new camera.
cam, cam_shape = cmds.camera()
cmds.move(15, 10, 15, cam)
cmds.rotate(-25, 45, 0, cam)
cmds.setAttr("{}.focalLength".format(cam), 70)
cmds.setAttr("{}.displayCameraFrustum".format(cam), True)

# Create a bunch of boxes at random positions.
val = 10
for i in range(50):
    new_cube, _ = cmds.polyCube()
    cmds.move(random.uniform(-val, val), random.uniform(-val, val), random.uniform(-val, val), new_cube)

# Add camera to MDagPath.
mdag_path = OpenMaya.MDagPath()
sel = OpenMaya.MSelectionList()
sel.add(cam)
sel.getDagPath(0, mdag_path)

# Create frustum object with camera.
draw_traversal = OpenMayaUI.MDrawTraversal()
draw_traversal.setFrustum(mdag_path, cmds.getAttr("defaultResolution.width"), cmds.getAttr("defaultResolution.height"))  # Use render's resolution.
draw_traversal.traverse()  # Traverse scene to get all objects in the camera's view.

frustum_objs = []

# Loop through objects within frustum.
for i in range(draw_traversal.numberOfItems()):
    # It will return shapes at first, so we need to fetch its transform.
    shape_dag_path = OpenMaya.MDagPath()
    draw_traversal.itemPath(i, shape_dag_path)
    transform_dag_path = OpenMaya.MDagPath()
    OpenMaya.MDagPath.getAPathTo(shape_dag_path.transform(), transform_dag_path)

    # Get object's long name and make sure it's a valid transform.
    obj = transform_dag_path.fullPathName()
    if cmds.objExists(obj):
        frustum_objs.append(obj)


# At this point we have a list of objects that we can filter by type and do whatever we want.
# In this case just select them.
cmds.select(frustum_objs)

希望能给你一个更好的方向。