Jerry Feng
Jerry Feng

Reputation: 275

Why android.Matrix.setRotateM returns a matrix whose rotation direction is the opposite of the expected rotation matrix?

For example, if I give the following parameters:

float[] rotateMatrix = identityMatrix.clone();
Matrix.setRotateM(rotateMatrix, 0, 90, 0, 0, 1);

I expect a matrix which rotates 90 degrees counter clockwise, which should be:

0       -1.0     
1.0    0

but actually the returned rotateMatrix is:

0       1.0    
-1.0    0

And curiously, the rendered output is correct, the image is rotated 90 degrees counter clockwise(rather than clockwise). Why?

Upvotes: 2

Views: 268

Answers (1)

Rabbid76
Rabbid76

Reputation: 210878

It is because OpenGL (ES) matrices are specified by vectors in column major order.

See android.opengl.Matrix:

Matrix math utilities. These methods operate on OpenGL ES format matrices and vectors stored in float arrays.

Matrices are 4 x 4 column-vector matrices stored in column-major order:

m[offset +  0] m[offset +  4] m[offset +  8] m[offset + 12]
m[offset +  1] m[offset +  5] m[offset +  9] m[offset + 13]
m[offset +  2] m[offset +  6] m[offset + 10] m[offset + 14]
m[offset +  3] m[offset +  7] m[offset + 11] m[offset + 15]

See OpenGL ES Shading Language 3.20 Specification, 5.4.2 Vector and Matrix Constructors, page 110:

To initialize a matrix by specifying vectors or scalars, the components are assigned to the matrix elements in column-major order .

mat4(float, float, float, float,  // first column
     float, float, float, float,  // second column
     float, float, float, float,  // third column
     float, float, float, float); // fourth column

So a GLSL mat4 can be set by the 4 vectors for the axis and the translation:

mat4 m44 = mat4(
    vec4( Xx, Xy, Xz, 0.0),
    vec4( Yx, Xy, Yz, 0.0),
    vec4( Zx  Zy  Zz, 0.0),
    vec4( Tx, Ty, Tz, 1.0) );

After a mathematical rotation to the right (counter clockwise) around the z-axis (0, 0, 1), the x axis is (0, 1, 0) and the y-axis is (-1, 0, 0), which leads to the matrix:

 0  1  0  0   // x axis vector
-1  0  0  0   // y axis vector
 0  0  1  0   // z axis vector
 0  0  0  1   // translation vector

Upvotes: 1

Related Questions