Sweet, Sweet Matrices

Here’s a fun Maya Python problem I ran into recently. It took me a long time to figure out that it involved matrices, as it first seemed like a good candidate for, well, I wasn’t sure even where to begin, but I thought some vectors would be involved. After many dead-ends and dabbling in quaternions, I finally discovered the simplest solution (and only one I could find) uses matrix math!

I’m excited about this because linear algebra has haunted me since college. Back then, I mistakenly assumed “Elementary Linear Algebra” was a refresher course, or a well-deserved break from the ‘real’ math classes. I was wrong. It should’ve been called, “MATRICES OR DIE!

Here’s the actual problem: You’ve got a million identical polygonal objects, randomly translated and rotated about, then combined into one mesh. Write some code to replace each piece with an instance object/locator.

Why is this difficult? Because the original objects were combined into one mesh, they no longer have any object transform data. Now, the only thing to query that defines their translation, rotation, scale, and even shear is the vertex positions. So how can you determine the original transform data of those objects? And how can you even tell which vertices belonged to which original objects? AND, how can you do this in a way that doesn’t take 10 hours to process or crash Maya?

The first question to ask is, how can you do this for one object? My initial plan was to define some vectors with a few vertex locations of a ‘zeroed-out’ object, then compare those vectors to that of a transformed object. Even then, I wasn’t sure how to convert the results into a usable transform to apply to a locator. I could align the objects along ONE arbitrary vector, but struggled to complete the second rotation to make the alignment complete.

After a couple weeks dead-ending with vectors and quaternions, I finally discovered an example problem to use in the original course textbook from over 10 years ago.

The solution? Solve this equation for x: Ox = N, where O is the original vertex locations for one object, x is the transform matrix that’s been applied to them, and N is the new vertex locations. Just pick four consistent vert indices from each object, throw them into a column matrix, and solve the equation! The answer is the final transform matrix that was applied to the original objects, respectively. Apply that transform to an instance locator, and voila!

Now just do that a million times, and you’re done!