Search code examples
c++openglsdlmingw-w64glm-math

OpenGL GLM matrix/vector not initializing properly


I'm attempting to use GLM in an SDL/OpenGL project using MinGW-w64 as a compiler, and am unable to set a value for any matrix or vector I attempt to initialize (all the values in the structure are being set to 0.)

I am not receiving any compiler errors or warnings and it seems like the memory is being allocated properly but the values just aren't being set.

#include "engine.hpp"
#include <GL/GLew.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>
#include <GL/GL.h>
#include <GL/glu.h>
#include <GL/glext.h>
#include <stdio.h>

...

void Engine::run(){
  ...
  GLuint shaderProg = renderer::loadShaders("shaders/vertShader.glsl", "shaders/fragShader.glsl");

  if(shaderProg==0)
    return;

  glm::mat4 projMat = glm::perspective(glm::radians(45.0f), float(SCREEN_WIDTH)/float(SCREEN_HEIGHT), 0.1f, 100.0f);
  //glm::mat4 projMat = glm::ortho(-10.0f, 10.0f, -10.0f, 10.0f, 0.0f, 100.0f);

  glm::mat4 viewMat = glm::lookAt(glm::vec3(4,3,3),
                                  glm::vec3(0,0,0),
                                  glm::vec3(0,1,0));

  glm::mat4 modelMat = glm::mat4(1.0f);

  glm::mat4 mvp = projMat*viewMat*modelMat;

  glm::vec4 test(1, 1.0f, 1.0f, 1.0f);

  GLuint mvpID = glGetUniformLocation(shaderProg, "MVP");
  glUniformMatrix4fv(mvpID, 1, GL_FALSE, &mvp[0][0]);

  for(int i = 0; i < 4; i++)
  {
    for(int j = 0; j < 4; j++)
    {
      printf("%f ", &projMat[i][j]);
    }
    printf("\n");
  }
  ...
}

Solution

  • glUniform* sets a value of the uniform in the default uniform block of the currently installed program. Hence the program has to be installed before by glUseProgram:

    GLuint mvpID = glGetUniformLocation(shaderProg, "MVP");
    
    glUseProgram(shaderProg);
    
    glUniformMatrix4fv(mvpID, 1, GL_FALSE, &mvp[0][0]);
    

    Since OpenGL version 4.1, glProgramUniform* is provided, which specify a value of a uniform variable for a specified program object:

    GLuint mvpID = glGetUniformLocation(shaderProg, "MVP");
    glProgramUniformMatrix4fv(shaderProg, mvpID, 1, GL_FALSE, &mvp[0][0]);