0
votes

I'm trying to multiply my cube's position by uniform model matrix but it's making my model invisible :(

There's my vertex shader:

#version 330 core

layout (location = 0) in vec3 aPos;
layout (location = 1) in vec2 aTex;

uniform mat4 model;

out vec2 aTexture;

void main() {
   gl_Position = model * vec4(aPos, 1.0f);
   aTexture = aTex;
}

And the cube render method:

void Cube::render(const GLSLShader& shader) const {

   shader.use();

   if (_texture != nullptr) {
      _texture->use();
   }

   glm::mat4 m  = glm::translate(m, glm::vec3(0.0f, 0.0f, 0.0f));
   shader.addMat4Uniform("model", m);

   glBindVertexArray(_vao);
   glDrawArrays(GL_TRIANGLES, 0, 36);
}

addMat4Uniform method:

void GLSLShader::addMat4Uniform(const std::string& name, glm::mat4 val) const {
   glUniformMatrix4fv(glGetUniformLocation(_shader_program, name.c_str()), 1,
                      GL_FALSE, glm::value_ptr(val));
}

When I'm multiplying by empty mat4 like:

glm::mat4 m;  //= glm::translate(m, glm::vec3(0.0f, 0.0f, 0.0f));
shader.addMat4Uniform("model", m);

Everything is fine, but when I uncomment the glm::translate function cube becames invisible :(

1
Damn man, thanks a lot! - Kacper Czyż

1 Answers

2
votes

In the line

glm::mat4 m = glm::translate(m, glm::vec3(0.0f, 0.0f, 0.0f));

the variable m is not initilized when it is used as a paramter for glm::translate.

Initialize the variable m first and then use it:

glm::mat4 m(1.0f); // identity matrix
m = glm::translate(m, glm::vec3(0.0f, 0.0f, 0.0f));


Further note, that an identity matrix should be initialized by the single parameter 1.0:

glm::mat4 m(1.0f);

See the glm API documentation which refers to The OpenGL Shading Language specification 4.20.

5.4.2 Vector and Matrix Constructors

If there is a single scalar parameter to a vector constructor, it is used to initialize all components of the constructed vector to that scalar’s value. If there is a single scalar parameter to a matrix constructor, it is used to initialize all the components on the matrix’s diagonal, with the remaining components initialized to 0.0.