Search code examples
glslvulkanvertex-shader

GLSL SSBO memory alignment & padding


In my vertex shader, I have a SSBO Array that I use to access individual data parts for each object.

struct Object
{
    vec2 vertices[4];
    uint index;
    vec2 position;
};

layout(set = 0, binding = 0) buffer ObjectBuffer
{
    Object objects[];
};

I have no issues accessing the first two elements vertices and index. However, when I access position.x, it gives me the value in position.y, and when I access position.y, it gives me gibberish.

To fix this, I swapped the order of index and position in the Object struct.

Using my limited knowledge, I assume that due to memory alignment rules it took the largest data type in the struct which is vec2 (assuming float = 4 bytes, 4 * 2 = 8 bytes). Assuming uint is 4 bytes as well, it took the next 4 bytes beside it (which is position.x) as padding?

Whilst I was able to resolve this issue (for now) by switching the order, what else can I do to ensure proper memory alignment?


Solution

  • Can you confirm your physical memory layout in terms of byte offsets?

    I'd expect each object to be 8 byte aligned, containing:

    32 bytes (vec2 vertices[4])
     4 bytes (index)
     4 bytes (padding, as position needs to be 8 byte aligned)
     8 bytes (position)
    

    What else can I do to ensure proper memory alignment?

    Read the std430 layout rules very carefully (for storage buffers). Note that uniform buffers default to std140 layout, not std430.