2

I know how to perform the math to convert between a 4x4 matrix, quaternion, and euler angles given a rotation in any other form. I was just hoping in PyMEL that there would be built-in ways to convert. None have really worked for me so far. Anyone out there know the best way, or a commonly-used library for this?

Thanks!

Steve Middleton
  • 181
  • 4
  • 13

1 Answers1

3

Pymel has wrapper classes for quaterions and matrices and euler rotations

hence:

import pymel.core.datatypes as dt
quat = dt.Quaternion(.707, 0, 0, .707)
print quat.asEulerRotation()
# dt.EulerRotation([1.57079632679, -0.0, 0.0], unit='radians')
print quat.asMatrix()
# dt.Matrix([[1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, -1.0, 0.0, 0.0], [0.0, 0.0, 0.0, 1.0]])

You can also get direct access to the underlying API classes without Pymel, though it's kind of annoying because you need the icky MScriptUtil to provide double values

def APIQuat(*iterable):
    '''
    return an iterable as an OpenMaya MQuaternion
    '''
    opt = None
    if isinstance(iterable, OpenMaya.MQuaternion):
        opt = iterable
    else:
        assert len(iterable) == 4, "argument to APIQuat must have 3  or 4 entries"
        it = list(copy(iterable))
        v_util = OpenMaya.MScriptUtil()
        v_util.createFromDouble(it[0], it[1], it[2], it[3])
        opt = OpenMaya.MQuaternion(v_util.asDoublePtr())
        opt.normalizeIt()
    return opt

Update

This is all much easier nowadays using the 2.0 version of the api:

from maya.api.OpenMaya import MQuaternion, MEulerRotation
import math

q = MQuaternion (.707, 0, .707, 0)
q.normalizeIt() # to normalize
print q
print q.asEulerRotation()
# (0.707107, 0, 0.707107, 0)
# (-3.14159, -1.5708, 0, kXYZ)

# note that EulerAngles are in radians! 
e = MEulerRotation (math.radians(45) ,math.radians(60), math.radians(90), MEulerRotation.kXYZ)
print e
print e.asQuaternion()
# (0.785398, 1.0472, 1.5708, kXYZ)
# (-0.092296, 0.560986, 0.430459, 0.701057)
theodox
  • 12,028
  • 3
  • 23
  • 36
  • If you convert the matrix into an [MTransformationMatrix](http://download.autodesk.com/us/maya/2010help/API/class_m_transformation_matrix.html), the `getRotationQuaternion()` method does that. – theodox Mar 15 '15 at 21:14
  • Yeah, that seems to be the only way I've found as well -- thanks! – Steve Middleton Mar 17 '15 at 03:38