Search code examples
c++openglglslshaderglm-math

OpenGL and GLM problem with cube rotation


I am learning OpenGL from http://learnopengl.com and I have a problem with transformation based on this chapter Coordinate Systems... I want to render something like this Movie but I have something like this Movie2 in 5 seconds its back on the screen. Sorry for many links but I think it's easier to show this by video. It's my render loop:

const auto projection = glm::perspectiveFov(glm::radians(45.0f), 800.0f, 600.0f, 0.1f, 100.0f);
const auto view = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, -3.0f));

while (!glfwWindowShouldClose(window))
{
    processInput(window);

    glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    flatColorShader->bind();
    flatColorShader->setMat4("u_Projection", projection);
    flatColorShader->setMat4("u_View", view);

    auto model = glm::mat4(1.0f);
    model = glm::rotate(model, static_cast<float>(glfwGetTime()) * glm::radians(50.0f), glm::vec3(0.5f, 1.0f, 0.0f));
    flatColorShader->setMat4("u_Model", model);
    glDrawArrays(GL_TRIANGLES, 0, 36);
    glBindVertexArray(vao);

    glfwSwapBuffers(window);
    glfwPollEvents();
}

Vaertex shader:

#version 460 core
layout (location = 0) in vec3 a_Pos;
layout (location = 1) in vec2 a_TexCoord;

out vec2 v_TexCoord;

uniform mat4 u_Projection;
uniform mat4 u_Model;
uniform mat4 u_View;

void main()
{
    v_TexCoord = vec2(a_TexCoord.x, 1.0f - a_TexCoord.y);
    gl_Position = u_Projection * u_Model * u_View * vec4(a_Pos, 1.0);
}

And Fragment shader:

#version 460 core

in vec2 v_TexCoord;

out vec4 color;

uniform sampler2D u_Texture;

void main()
{
    color = texture(u_Texture, v_TexCoord);
}

I suppose it is a problem with the model matrix, but I don't known what. Can somebody help me with that's problem?


Solution

  • The order of the vertex transformations in the vertex shader is incorrect:

    gl_Position = u_Projection * u_Model * u_View * vec4(a_Pos, 1.0);

    gl_Position = u_Projection * u_View * u_Model * vec4(a_Pos, 1.0);
    

    The order matters, because matrix multiplications are not commutative.