Search code examples
copenglrotationglutglm-math

OpenGL triangle rotates wrong


I want to rotate my triangle around his own axis, but It´s rotating around the camera. I have to code from a tutorial, the only differenc is, that I´m using C instead of C++. So I have to use the "cglm"-lib instead of the "glm"-lib. (I´m also using glut and glad)

globally defined:

mat4  model;
mat4 projection;
mat4 view;
mat4 modelViewProj;

In the main:

glm_mat4_identity(model); //Einheitsmatrix
glm_mat4_identity(view);
glm_scale(model, (vec3) {1.2f, 1.2f, 1.2f});

glm_perspective(glm_rad(45.0f), 4.0f/3.0f, 0.1f, 100.0f, projection);

glm_translate(view, (vec3) {0, 0, -5.0f});

glm_mat4_mul(model, projection, modelViewProj);
glm_mat4_mul(modelViewProj, view, modelViewProj);

modelMatrixLocation = glGetUniformLocation(shader1.shaderId, "u_modelViewProj");

In the loop:

//In the void display()
glUniformMatrix4fv(modelMatrixLocation,1, GL_FALSE, &modelViewProj[0][0]); 

//In the void update() ->glutTimerFunc()
glm_rotate(model, 0.08f, (vec3){0, 1, 0});

glm_mat4_mul(model, projection, modelViewProj);
glm_mat4_mul(modelViewProj, view, modelViewProj);

Solution

  • The order of the matrix multiplications is wrong.

    It has to be:

    modelViewProj = projection * view * model;
    

    In C:

    glm_mat4_mul(view, model, modelViewProj);
    glm_mat4_mul(projection, modelViewProj, modelViewProj);
    

    Note, void glm_mat4_mul(mat4 m1, mat4 m2, mat4 dest) computes:

    dest = m1 * m2;
    

    Matrix multiplication is not Commutative (in compare to Arithmetic Multiplication). The order matters.