# OpenGL Uniform Standard Buffer Alignment confusion

Although i asked the same question over StackOverflow, i thought i can get more info from here too.

I have been reading about std140 Uniform block in OpenGL Superbible 6th edition, where in page 111 the following example is given :

layout(std140) uniform TransformBlock
{
//Member                        base alignment    offset  aligned offset
float scale ;                   // 4              0       0
vec3 translation;               // 16             4       16
float rotation[3];              // 16             28      32 (rotation[0])
//                        48 (rotation[1])
//                        64 (rotation[2])
mat4 projection_matrix;         // 16             80      80 (column 0)
//                        96 (column 1)
//                        112 (column 2)
//                        128 (column 3)
}


I am having hard time understanding the alignments, even using the rules that have described earlier in that page, it still don't make sense.To be specific thing that confuses me is :

1. What is the Offset and what is aligned offset, why 2 different offset?

2. Why is the rotation[0] offset starts at 28, and why aligned offset is 32?

Hopefully someone can clear my confusions.I would highly appreciate. Thanks

Offset refers to the offset you would have in your original data without adjustment, basically all the sizes added up.

Aligned offset is the actual result on the opengl side.

So in this case vec3 has to be aligned to 16. So the first available spot is actually 16 instead of 0.

GLint viewPosLoc = glGetUniformLocation(shader.program, "ViewPos");

glUniform3f(viewPosLoc, cameraView.position.x, cameraView.position.y, cameraView.position.z);

glUniform1i(lightCountLoc, pls.length());
glUniform1i(dLightCountLoc, dls.length());

glUniform1f(materialShininessLoc, material.shininess);


That is a little example code of setting the normals. If you set them one at a time then everything shall work properly and you do not have to worry too much about alignment.

Where this really comes in is when you use a UBO to set a data block all at once. That is because the format of your data in C++ will not necessarily line up to the same positions as your data in OGL and then you get garbage on the other end.

The easiest solution to this is to make sure that your data structures in C++ have the same memory alignments as those in OGL. How to set this is compiler specific but you can always add padding data to get the right result.

For example a vec3 is 12 bytes in C++ because it is 3 floats. In OGL it is aligned to 16. You can either align it to 16 in C++ as well by padding it with an extra float, or by declaring it to be aligned to 16 in your compiler.

Then you can safely use a UBO to fill the whole thing at once.

Here is a basic tutorial on UBOs and buffer blocks: