Posts Tagged ‘ Maya

Uninstance all instances in a Maya scene

From over on my mel wiki:

Maya makes it easy to create an instance of a node, but I’ve found no built-in way to query what nodes in the scene are instanced.  Poking around a bit in the API however, it only takes a few lines of code:

# Python code
import maya.cmds as mc
import maya.OpenMaya as om

def getInstances():
    instances = []
    iterDag = om.MItDag(om.MItDag.kBreadthFirst)
    while not iterDag.isDone():
        instanced = om.MItDag.isInstanced(iterDag)
        if instanced:
            instances.append(iterDag.fullPathName())
        iterDag.next()
    return instances

This function will return a list of all the instances in the scene, nice! I have yet to find any other function that can do this via mel.

But how would you actually uninstance them? I worked on this problem quite a bit: If you simply have a bunch of leaf nodes that are instanced, it’s not hard to do. But if you have a say ten spheres all instanced, then you make two groups of five, then instance those groups, and parent all the groups, then instance that parent… very quickly things get hairy:  You try and uninstance a leaf by duplicating it, and now the duplicate appears in every other parental instance!
Like I just mentioned, most solutions I’ve found explain you can just ‘duplicate the instance’ to solve this problem, and this works on an individual instance that has no parent node that is an instance.  But when you have the situation I list above, the solution I found is this:  You can actually duplicate the instances parent, then delete the original parent, which will (via a loop) cleanly uninstance everything in the scene.  And since the getInstances() function returns a list parent-first, this works out great:

def uninstance():
    instances = getInstances()
    while len(instances):
        parent = mc.listRelatives(instances[0], parent=True, fullPath=True)[0]
        mc.duplicate(parent, renameChildren=True)
        mc.delete(parent)
        instances = getInstances()

lambda and map in Maya

Starting using a couple shorthand techniques today via map and lambda to save on screen real estate when authoring Python modules in Maya.  I often times will troll the scene for info and want to print stuff:

Here, I find the transform name for all mesh in the scene, then print them all with tabs in front:

import sys
import maya.cmds as mc
# Get transform for each mesh:
shapes = mc.ls(type='mesh')
transforms = map(lambda x: mc.listRelatives(x, parent=True)[0], shapes)
# print with tab in front:
map(lambda x: sys.stdout.write('\t%s\n'%x), transforms)

By using our map / lambda combo, I’m able to side-step the need to write any loops. Here’s how it would look otherwise:

import maya.cmds as mc
# Get transform for each mesh:
shapes = mc.ls(type='mesh')
transforms = []
for s in shapes:
    transforms.append(mc.listRelatives(s, parent=True)[0])
# print with tab in front:
for tran in transforms:
    print '\t', tran

Not counting imports and comments, I halved the number of lines of code. One could argue the bottom example is possibly more readable however.

Find Euler rotation values of Maya matrix

Sparse posting lately:  New home + new job = very busy :)

From over on my Mel Wiki, I’ve finally figure out (thanks to this post) how to extract Euler rotation values from a Maya matrix via the OpenMaya Python API.  Not sure why I’ve wanted to know how to do this, but I’m glad I now can.

Note: Below is all updated bloggin’ goodness (as of 2011-02-18)  from the original post, since I’ve learned some new tricks:

—-

After learning more from the API, I realized the differences between the MMatrix class and the MTransformationMatrix class:  MMatrix purely holds matrix data, not unlike a MVector storing vector data and nothing else. the MTransformationMatrix does everything a MMatrix does, but it has knowledge of how Maya wants it, so provides many convenience methods for accessing the data and interaction with a Maya transform node..

The big takeaway I found is this:  MTransformationMatrix objects will keep track of rotations past 360 degrees & rotation order of the node, while MMatrix objects will not. It makes sense: A matrix itself stores orientations as vectors, which have no concept how how far they’ve been ‘rotated’, so the MMatrix object doesn’t track this data. But behind the scenes, the MTransformationMatrix does track this info, which the below examples illustrate.

One more very important piece of data: When extracting a MTransformationMatrixfrom a node via a MFnTransform function, what you’re actually getting is the local transformation matrix of that node (since the MTransformationMatrix appears to track transformations specific to that node, relative to its parent).  So if you were expecting the world-space matrix, prepare to be disappointed. You can build a MTransformationMatrix out of a worldspace-acquired MMatrix, but at that point ‘rotations past 360’ would be lost.

# Python code
import math
import maya.cmds as mc
import maya.OpenMaya as om

# Define a node to pull a matrix from.
node = 'pCube1'
# Set some rotation values for comparison later:
mc.setAttr('%s.rotate'%node, 15, -45, 1000)
mc.setAttr('%s.scale'%node, 3, 3, 3)
# Change the rot order, to make sure returned euler values are correct:
mc.setAttr('%s.rotateOrder'%node, 3)

Method A: Using MTransformationMatrix

This, in my opinion, is the best solution. Via the API, you get an MDagPath object for your node, wrapper it in a MFnTransform object, and then directly extract a MTransformationMatrix object from it. This object tracks the rotation order (so you don’t have to), and rotation values past 360.

#-------------------------------------------
# Part 1: Get a MTransformationMatrix from an object for the sake of the example.
# You can use your own MTransformationMatrix if it already exists of course.

# get a MDagPath for our node:
selList = om.MSelectionList() # make a sel list # MSelectionList
selList.add(node) # add our node by name
mDagPath = om.MDagPath() # create an empty dag path # MDagPath
selList.getDagPath(0, mDagPath) # fill the dag path with our node

# Create a MFnTransform object for our MDagPath,
# and extract a MTransformationMatrix from it:
transformFunc = om.MFnTransform(mDagPath) # MFnTransform
mTransformMtx = transformFunc.transformation() # MTransformationMatrix

#-------------------------------------------
# Part 2, get the euler values
# Get an MEulerRotation object
eulerRot = mTransformMtx.eulerRotation() # MEulerRotation
# note, we *don't* have to set the rot order here...

# Convert from radians to degrees:
angles = [math.degrees(angle) for angle in (eulerRot.x, eulerRot.y, eulerRot.z)]
print angles, "MTransformationMatrix"

Method B: Using MMatrix

While this method works well, it doesn’t track rotation values past 360: We create a MMatrix object directly from the worldMatrixattr queried on our node. We then convert that to a MTransformationMatrix object so we can extract the MEulerRotation object. However, the MMatrix doesn’t pass along the rotation order of the node, and has no knowledge of rotations past 360, so the resultant MTransformationMatrix won’t know that stuff either. To get accurate rotation values, we have to save the rotation order value ahead of time, and then apply it back before retrieving values from our MEulreRotation object.

#-------------------------------------------
# Part 1:  Get a MMatrix from an object for the sake of the example.
# You can use your own MMatrix if it already exists of course.

# Get the node's rotate order value:
rotOrder = mc.getAttr('%s.rotateOrder'%node)
# Get the world matrix as a list
matrixList = mc.getAttr('%s.worldMatrix'%node) # len(matrixList) = 16
# Create an empty MMatrix:
mMatrix = om.MMatrix() # MMatrix
# And populate the MMatrix object with the matrix list data:
om.MScriptUtil.createMatrixFromList(matrixList, mMatrix)

#-------------------------------------------
# Part 2, get the euler values
# Convert to MTransformationMatrix to extract rotations:
mTransformMtx = om.MTransformationMatrix(mMatrix)
# Get an MEulerRotation object
eulerRot = mTransformMtx.eulerRotation() # MEulerRotation
# Update rotate order to match original object, since the orig MMatrix has
# no knoweldge of it:
eulerRot.reorderIt(rotOrder)

# Convert from radians to degrees:
angles = [math.degrees(angle) for angle in (eulerRot.x, eulerRot.y, eulerRot.z)]
print angles, "MMatrix"

Running the above code prints (and I reformatted the float precision issues, just so it’s easier to compare to the above values):

[15, -45, 1000] MTransformationMatrix
[15, -45, -80] MMatrix

As you can see, the MTransformationMatrix stores the rotation values past 360 deg, while the MMatrix doesn’t.

Sparse posting…

…for a bit.  I just moved (one mile south), and work is busy.  Just got cable hooked up, and still can’t find my router (in a box somewhere).  Two van-loads to Good Will, and one to the dump, and we still have more stuff than we should.  Kind of creepy how much one can acquire over time…

In the meantime, Maya 2011 new features!

http://area.autodesk.com/blogs/cory/what_s_new_in_2011

Pickling Python data to Maya attributes

Recently I made the connection that A:  It’s really easy to serialize (pickle) data in Python, and B: You can make string attributes on nodes in Maya.  It’s not that I was unaware of these topics, it’s just that they’d never occurred in the same mental conversation simultaneously before.  But when they did, it was sort of an ‘eureka moment’, and I wrote two functions to make use of this new-found power.

Making use of the cPickle module, I pickle the Python data to a string object and store to a string attr on a Maya node.  To retrieve the data, I unpickle the string attributes value back to Python data.
http://docs.python.org/library/pickle.html
http://docs.python.org/library/pickle.html#module-cPickle

import cPickle
import maya.cmds as mc

def pyToAttr(objAttr, data):
    """
    Write (pickle) Python data to the given Maya obj.attr.  This data can
    later be read back (unpickled) via attrToPy().

    Arguments:
    objAttr : string : a valid object.attribute name in the scene.  If the
        object exists, but the attribute doesn't, the attribute will be added.
        The if the attribute already exists, it must be of type 'string', so
        the Python data can be written to it.
    data : some Python data :  Data that will be pickled to the attribute
        in question.
    """
    obj, attr = objAttr.split('.')
    # Add the attr if it doesn't exist:
    if not mc.objExists(objAttr):
        mc.addAttr(obj, longName=attr, dataType='string')
    # Make sure it is the correct type before modifing:
    if mc.getAttr(objAttr, type=True) != 'string':
        raise Exception("Object '%s' already has an attribute called '%s', but it isn't type 'string'"%(obj,attr))

    # Pickle the data and return the coresponding string value:
    stringData = cPickle.dumps(data)
    # Make sure attr is unlocked before edit:
    mc.setAttr(objAttr, edit=True, lock=False)
    # Set attr to string value:
    mc.setAttr(objAttr, stringData, type='string')
    # And lock it for safety:
    mc.setAttr(objAttr, edit=True, lock=True)

def attrToPy(objAttr):
    """
    Take previously stored (pickled) data on a Maya attribute (put there via
    pyToAttr() ) and read it back (unpickle) to valid Python values.

    Arguments:
    objAttr : string : A valid object.attribute name in the scene.  And of course,
        it must have already had valid Python data pickled to it.

    Return : some Python data :  The reconstituted, unpickled Python data.
    """
    # Get the string representation of the pickled data.  Maya attrs return
    # unicode vals, and cPickle wants string, so we convert:
    stringAttrData = str(mc.getAttr(objAttr))
    # Un-pickle the string data:
    loadedData = cPickle.loads(stringAttrData)

    return loadedData

And here is some sample usage:

# Make some really special Python data you want to store to a Maya node:
specialData = {'red':52, 'green':63.3, 'blue':"ASDF"}
print "Python data to store to Maya obj.attr:"
print specialData
#Python data to store to Maya obj.attr:
#{'blue': 'ASDF', 'green': 63.299999999999997, 'red': 52}

# Define our node and attr name based on the selected object:
node = mc.ls(selection=True)[0]
objAttr = '%s.pyPickle'%node

# Store data to our node:
pyToAttr(objAttr, specialData)

# Later, get data back:
storedData = attrToPy(objAttr)
print "Restored Python Data:"
print storedData
#Restored Python Data:
#{'blue': 'ASDF', 'green': 63.299999999999997, 'red': 52}