Zelig
Zelig

Reputation: 1808

Using matrix to rotate a cube gives wrong result

For my OpenGL app, I have a cube defined by the following coordinates :

coords=new float [] {-0.5f,0.5f,0.5f,1f,
     -0.5f,-0.5f,0.5f,1f,
     0.5f,-0.5f,0.5f,1f,
     0.5f,0.5f,0.5f,1f,
     -0.5f,0.5f,-0.5f,1f,
     -0.5f,-0.5f,-0.5f,1f,
     0.5f,-0.5f,-0.5f,1f,
     0.5f,0.5f,-0.5f,1f};

which represents the following matrix :

-0.5  -0.5   0.5   0.5  -0.5  -0.5   0.5   0.5
 0.5  -0.5  -0.5   0.5   0.5  -0.5  -0.5   0.5
 0.5   0.5   0.5   0.5  -0.5  -0.5  -0.5  -0.5
 1     1     1     1     1     1     1     1

I define a rotation matrix with :

float [] matrix=new float[16];
Matrix.setRotateM(matrix,0,90,1,0,0);

So my matrix is :

1   0   0   0
0   0   -1  0
0   1   0   0
0   0   0   1

When I try to apply the rotation to the coordinates with Matrix.multiplyMM(coords,0,matrix,0,coords,0);, I get the following result :

    -0,5  -0,5   0,5   0,5  -0,5  -0,5   0,5   0,5
    -0,5  -0,5  -0,5  -0,5   0,5  -0,5  -0,5   0,5
     0,5  -0,5  -0,5   0,5  -0,5  -0,5  -0,5  -0,5
     1     1     1     1     1     1     1     1

For me, and according to my calculator as well, the 6th and the 7th elements of the second row are wrong (they should both be positive). Same thing for the 5th and the 8th element of the third row.

Can anyone tell me where the problem is?

Upvotes: 2

Views: 125

Answers (1)

BDL
BDL

Reputation: 22157

You misinterpreted what multiplyMM does. This function multiplies a 4x4 matrix by another 4x4 matrix. By calling

Matrix.multiplyMM(coords,0,matrix,0,coords,0);

the function takes the first 16 floats of coords as first matrix, the first 16 floats of matrix as the second matrix and stores everything in the first 16 floats of coordinates. Thus all elements after the 16th are never touched.

I guess you wanted to multiply each vector in coords by the matrix in matrix. For this multiplyMM is the completly wrong function since it does a matrix times matrix multiplication, not matrix times vector. To transform a set of vectors by a matrix you'll have to repeatedly call Matrix.multiplyMV with appropriate offsets:

for (int i = 0; i < 8; i++)
{
    Matrix.multiplyMV(coords, 4 * i, matrix, 0, coords, 4 * i);
}

Upvotes: 2

Related Questions