Search code examples
c++openglglm-math

How to convert a glm::vec4<float> to a GLfloat*?


I am trying to pass a glm::vec4<float> to gl::ImmediateMode::glColor4fv(GLfloat*):

std::vector<glm::vec4> colors;
colors.push_back(vec4(1.0f, 0.0f, 0.0f, 1.0f));
glColor4fv(colors[0]);

I receive the following error message:

error: not matching function call to 'ImmediateMode::glColor4fv(const vec4&) const'
[...]
candidate is: [...] void gl::ImmediateMode::glColor4fv(GLfloat*) const

Clearly I have to convert my glm::vec4 to a GLfloat array. I read through the GLSLanguage Specifications and could not find any way to access the data directly. The following attempt works:

GLfloat *c = new GLfloat[4];
c[0] = colors[0].r;
c[1] = colors[0].g;
c[2] = colors[0].b;
c[3] = colors[0].a;
glColor4fv(c);

But I would rather use something more elegant. So is there a way to access the data array in a glm::vec4 to allow access like following?

glColor4fv(reinterpret_cast<GLfloat*>(colors[0].data())); 
// .data() would hand me a pointer to the float array of the vec4

Solution

  • you can use glm::value_ptr. It works for both glm::mat and glm::vec and type safe.