Search code examples
ciosopengl-esmatrixglkit

How is GLKit's GLKMatrix "Column Major"?


Premise A

When talking about "Column Major" matrices in linear memory, columns are specified one after another, such that the first 4 entries in memory correspond to the first column in the matrix. "Row Major" matrices, on the other hand, are understood to specify rows one after another, such that the first 4 entries in memory specify the first row of the matrix.


A GLKMatrix4 looks like this:

union _GLKMatrix4
{
    struct
    {
        float m00, m01, m02, m03;
        float m10, m11, m12, m13;
        float m20, m21, m22, m23;
        float m30, m31, m32, m33;
    };
    float m[16];
}
typedef union _GLKMatrix4 GLKMatrix4;

The documentation on the m member says:

A one-dimensional array of the matrix’s elements in column-major order.

Premise B

A "row" in a GLKMatrix4 is a set of 4 floats declared horizontally ([m00, m01, m02, m03] would be the first "row"). Thus, those entries can be interpreted as mRowCol (m12 would be the entry at row 1, column 2).


If we look at how those GLKMatrix struct members are laid out based on the order of the declarations, we see:

[m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, ...]

Where the first 4 entries clearly represent the first row of the matrix, not the first column.

Conclusion

m is not actually Column Major, and the docs are wrong.


Now, I should note that I don't actually believe the conclusion, but the two premises seem pretty reasonable. Really, I distrust premise B the most, but it seems strange to define a "row" to be vertical and a "column" to be horizontal. Can someone explain this?


Solution

  • The declaration is a bit confusing, but the matrix is in column major order. The four rows in the struct represent the columns in the matrix, with m0* being column 0 and m3* being column 3. This is easy to verify, just create a translation matrix and check values m30, m31 and m32 for the translation components.

    I am guessing your confusion is coming from the fact that the struct lays out the floats in rows, when they are in fact representing columns.