Jimmy
Jimmy

Reputation: 286

GLSL - Uniform Buffer Object weird behaviour

I have noticed strange behaviour of uniform buffer object when I change the order of struct members (the struct in the shader is the same as struct in cpp). This is my source code (the working version):

CPP:

struct Matrices {
    // vec3, mat4 - glm library
    mat4 projectionMatrix; 
    mat4 viewMatrix;
    vec3 eyePosition;
};

GLSL:

layout (std140) uniform matrices {
    mat4 projectionMatrix;
    mat4 viewMatrix;
    vec3 eyePosition;
};

CPP ubo generation:

GLuint tmpUBO[2];
glGenBuffers(2, tmpUBO);
uniformBlocks["matrices"].bindingPoint = MATRICES_BINDING_POINT;
uniformBlocks["matrices"].ubo = tmpUBO[0];
glBindBuffer(GL_UNIFORM_BUFFER, tmpUBO[0]);
glBufferData(GL_UNIFORM_BUFFER, sizeof(Matrices), &matrices, GL_DYNAMIC_DRAW);
glBindBuffer(GL_UNIFORM_BUFFER, 0);

CPP updating ubo data:

glBindBuffer(GL_UNIFORM_BUFFER, uniformBlocks["matrices"].ubo);
GLvoid *p = 
    glMapBufferRange(GL_UNIFORM_BUFFER, 0, sizeof(Matrices), 
    GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_RANGE_BIT);
memcpy(p, &matrices, sizeof(Matrices));
glUnmapBuffer(GL_UNIFORM_BUFFER);
glBindBuffer(GL_UNIFORM_BUFFER, 0);

CPP binding ubo to linked and active shader:

GLuint bi = glGetUniformBlockIndex(handle, name);
glBindBufferBase(GL_UNIFORM_BUFFER, bindingPoint, ubo);
glUniformBlockBinding(handle, bi, bindingPoint);

This version is working totally fine, but when I change the order of struct members (in both glsl and cpp), for example:

struct Matrices {
    vec3 eyePosition;
    mat4 projectionMatrix; 
    mat4 viewMatrix;
}

one or both of the matrices is not updated when I move the camera or change the perspective.

Does anybody have any idea what is causing this?

Upvotes: 0

Views: 434

Answers (1)

Jimmy
Jimmy

Reputation: 286

I have found the answer on this website http://www.opentk.com/node/2926. The problem was with alignment of struct variables in shader.

Upvotes: 2

Related Questions