Search code examples
c++opengl-3

segmentation fault when using glUniformMatrix in combination with an array


I get a segmentation fault when I use glUniformMatrix4fv to pass a matrix to a mat4 uniform.

My shader looks like this:

#version 330 core

layout(location = 0) in vec3 pos;

layout(std140) uniform ModelMatrixBuffer {
    mat4 ModelMatrix[2];
};

out vec3 color;

uniform mat4 ViewProj;

void main() {
    gl_Position = ViewProj * ModelMatrix[0] * vec4(pos, 1.f);
    color = vec3(1,1,0);
}

I want to pass a glm::mat4 to ViewProj. It works fine when I change the size of my ModelMatrix Array to one. Like this:

layout(std140) uniform ModelMatrixBuffer {
    mat4 ModelMatrix[1];
};

Then everything works fine!


Solution

  • The problem is that the index used for glGetActiveUniform is inconsistent with the actual location for the specific uniform.

    uniform int arr[3];
    uniform int arr2[3];
    uniform int i;
    

    Here, the indices will be 0,1,2, because glGetActiveUniform will only count the first element in an array, here it will be arr[0] and arr2[0]. The location however will increment for each element in an array. Thus, i will have the location 6 and not 2.

    My mistake was that I had a map with all the uniforms and I was saving the index instead of the location. Therefore I tried to put my ViewProj matrix into the second element of the ModelMatrix array. Why this ended in a segmentation fault, I don't know. They are both mat4.