Jonathan Woollett-light
Jonathan Woollett-light

Reputation: 3243

What approaches can be used to handle 2d arrays with GLSL?

My specific case being a compute shader for doing a matrix multiplication between a n by m matrix and a n legnth vector (where n and m are not known at compile time).

Upvotes: 2

Views: 1818

Answers (1)

Rabbid76
Rabbid76

Reputation: 210938

Either use a 2 dimensional image (see glsl - 8.12. Image Functions):

layout(r32f) uniform image2D matrixImage;

void main()
{
    // [...]

    ivec2 size = ivec2(imageSize(matrixImage));
    int n = size.x;
    int m = size.y;
    for (int j = 0; j < m; j ++)
    {
        for (int i = 0; i < n; i ++)
        {
            float val = imageLoad(matrixImage, ivec2(i, j)).x;
 
            // [...]
        }
    }

    // [...]
}

Or write the data to a 1 dimensional open sized array in a Shader Storage Buffer Object:

layout(std430) buffer TMatrix
{
  int n;
  int m;
  float data[];
} matrix;

layout(r32f) uniform image2D matrixImage;

void main()
{
    // [...]

    for (int j = 0; j < matrix.m; j ++)
    {
        for (int i = 0; i < matrix.n; i ++)
        {
            int index = j * matrix.n + i;  
            float val = matrix.data[index];
            
            // [...]
        }
    }

    // [...]
}

If you know the size at compile time, it is not necessary to use an open sized array (see GLSL - 4.1.9. Arrays):

const int n = 10;
const int m = 10;

layout(std430) buffer TMatrix
{
  float data[n][m];
} matrix;

void main()
{
    // [...]

    for (int j = 0; j < matrix.m; j ++)
    {
        for (int i = 0; i < matrix.n; i ++)
        {
            float val = matrix.data[i][j];

            // [...]
        }
    }

    // [...]
}

Upvotes: 1

Related Questions