Wednesday, May 31, 2006

Rotation Matrix from Axis Vectors

Listening to : The Decemberists (various)

This is an oldie but a goodie, and I haven't posted it anywhere else, so here it is before I forget.

If you want to make a rotation matrix ( 4x4 ) so that you can make objects orient the same way as, say for example a normal and a tangent on a surface, so long as you have 2 of 3 of the desitnation "axes" then you can build a matrix directly from copying the values of those vectors. (if you do only have two, you get the third from doing a cross product).

I'm using row major notation here - so anyone who needs this column major, just transpose it.
I'm also assuming that the space of the sought rotation matrix is the same space that the vectors are in. (e.g. world space)
Lastly we're assuming that the normal and tangent and binormal are all normalized.

So, you have a normal and a tangent in (say) world space and you want a rotation matrix so you can apply the same orientation to other objects. This is the same as making a new coordinate system and transforming them into it without any rotation at all in that new coordinate space.

It helps to think of normal and tangent, and the 3rd vector called the 'binormal' (which is the cross product of the other two) as the axes of a space into which we're transforming.
It can be any order really, so lets pick :-
Normal = +Y axis
Tangent = +X axis
Binormal = +Z axis

So we have (for example)
+X vector is ( 0.670014, 0.541446, 0.507856 )
+Y vector is ( -0.609193 0.791979 -0.0406534 )
+Z vector is ( -0.424223 -0.282144 0.860482 )

So our 4x4 matrix will be
| Xx Xy Xz 0 |
| Yx Yy Yz 0 |
| Zx Zy Zz 0 |
| 0 0 0 1 |

which in our example gives us the following 4x4 rotation matrix !
| 0.670014 0.541446 0.507856 0 |
| -0.609193 0.791979 -0.0406534 0 |
| -0.424223 -0.282144 0.860482 0 |
| 0 0 0 1 |

So all that any rotation matrix consists of, is the three axes vectors that define it as a coordinate system.

To rotate a plane by -45 degress about X in MEL, you'd do this
// -45 degrees in X
xform -m 1.0 0.0 0.0 0.0 0 0.707107 -0.707107 0.0 0 0.707107 0.707107 0.0 0.0 0.0 0.0 1.0 pPlane1;

Where 0.707107 is of course 1/sqrt(2)

No comments: