09 April 2017

Math – Calculate a transformation matrix

Suppose you have a translation, a rotation and a scaling matrix; how do you combine them into one transformation matrix — also model matrix — used to render some object? The order in which they are combined is also important. The following method will first rotate and scale the object, then move it. Rotation is the most complex transformation, and is done with quaternions.

//"Position", "Scale" and "Rotation" are all Vector3's.
Quaternion rot = null;
if (Rotation != null)
{
    var rotX = new Quaternion(Rotation.X, 1, 0, 0);
    var rotY = new Quaternion(Rotation.Y, 0, 1, 0);
    var rotZ = new Quaternion(Rotation.Z, 0, 0, 1);
    rot = rotX * rotY * rotZ;
}

var model = new Matrix();
model.Rotate(rot);
model.Scale(Scale);
model.Translate(Position);

The Matrix class was also mentioned in the post about quaternions. You can find the Matrix.Rotate method there as well. Compared to that, translation and scaling are pretty simple:

//An overload of this method takes a Vector3, and checks it for NULL.
public void Translate(float x, float y, float z)
{
    M[0, 3] += x;
    M[1, 3] += y;
    M[2, 3] += z;
}

//Also has an overload that takes a Vector3.
public void Scale(float x, float y, float z)
{
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            M[i, j] *= x;
            M[i, j] *= y;
            M[i, j] *= z;
        }
    }
}