Wednesday, March 13, 2013

Open MAYA API: Working with iterators (part 1)

Iterators are special classes which have methods to  navigate through objects or components.
MItSelectionList- navigate through selected objects
MItDependencyNodes - navigate through all maya nodes. Especially useful to navigate through specific type of maya objects. For example to traverse all cameras, or lights, or meshes.
MItMeshPolygonMItMeshVertexMItMeshEdgeMItMeshFaceVertex to navigate through specific components of the poly object.



There are many other iterators in maya api. You can find them in API class list. All of them start with MIt.
General syntax to work with iterators in python is following. For example let's navigate through all cameras in the current scene:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import maya.OpenMaya as om
def getCameras():
    # Create iterator traverse all camera nodes
    camera_iter = om.MItDependencyNodes(om.MFn.kCamera)
    # Loop though iterator objects
    while not camera_iter.isDone():
        # camera_iter.thisNode() points to current MObject in iterator
        camera_mObject = camera_iter.thisNode()
        # let's print all cameras names
        dagPath = om.MDagPath.getAPathTo(camera_mObject)
        print dagPath.fullPathName()
        # Takes next object in "while" loop.
        # Don't forget it, or you will get infinite loop.
        camera_iter.next()

getCameras()


Another example - iterating through selected object:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import maya.OpenMaya as om
def getSelection():
    # Create object named selection and type - SelectionList
    selection = om.MSelectionList()
    # Fill variable "selection" with list of selected objects
    om.MGlobal.getActiveSelectionList(selection)
    # Create iterator through list of selected object
    selection_iter = om.MItSelectionList(selection)
    obj = om.MObject()
    # Loop though iterator objects
    while not selection_iter.isDone():
        # Now we can do anything with each of selected objects.
        # In this example lets just print path to iterating objects. 
        selection_iter.getDependNode(obj)
        dagPath = om.MDagPath.getAPathTo(obj)
        print dagPath.fullPathName()
        selection_iter.next()

getSelection()



4 comments: