Search code examples
c++arraysopenglshadercompute-shader

What is wrong with my compute shader array indexing?


I'm currently having a problem with my compute shader failing to properly get an element at a certain index of an input array.

I've read the buffers manually using NVidia NSight and it seems to be input properly, the problem seems to be with indexing.

It's supposed to be drawing voxels on a grid, take this case as an example (What is supposed to be drawn is highlighted in red while blue is what I am getting):

Rendered frame

And here is the SSBO buffer capture in NSight transposed:

SSBO

This is the compute shader I'm currently using:

#version 430
layout(local_size_x = 1, local_size_y = 1) in;
layout(rgba32f, binding = 0) uniform image2D img_output;

layout(std430) buffer;

layout(binding = 0) buffer Input0 {
    ivec2 mapSize;
};

layout(binding = 1) buffer Input1 {
    bool mapGrid[];
};

void main() {
  // base pixel colour for image
  vec4 pixel = vec4(1, 1, 1, 1);
  // get index in global work group i.e x,y position
  ivec2 pixel_coords = ivec2(gl_GlobalInvocationID.xy);
  vec2 normalizedPixCoords = vec2(gl_GlobalInvocationID.xy) / gl_NumWorkGroups.xy;
  ivec2 voxel = ivec2(int(normalizedPixCoords.x * mapSize.x), int(normalizedPixCoords.y * mapSize.y));
  
  float distanceFromMiddle = length(normalizedPixCoords - vec2(0.5, 0.5));

  pixel = vec4(0, 0, mapGrid[voxel.x * mapSize.x + voxel.y], 1); // <--- Where I'm having the problem
  // I index the voxels the same exact way on the CPU code and it works fine

  // output to a specific pixel in the image
  //imageStore(img_output, pixel_coords, pixel * vec4(vignettecolor, 1) * imageLoad(img_output, pixel_coords));
  imageStore(img_output, pixel_coords, pixel);
}

NSight doc file: https://ufile.io/wmrcy1l4


Solution

  • I was able to fix the problem by completely ditching SSBOs and using a texture buffer, turns out the problem was that OpenGL treated each value as a 4-byte value and stepped 4 bytes instead of one for each index.

    Based on this post: Shader storage buffer object with bytes