可以使用哪些方法来使用GLSL处理2D数组?

问题描述

我的特定情况是一个计算着色器,用于在n by m matrixn legnth vector之间进行矩阵乘法(其中nm在编译时是未知的)。

解决方法

使用二维图像(请参见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;
 
            // [...]
        }
    }

    // [...]
}

或将数据写入Shader存储缓冲区对象中的一维开放尺寸数组:

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];
            
            // [...]
        }
    }

    // [...]
}

如果在编译时知道大小,则不必使用开放大小的数组(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];

            // [...]
        }
    }

    // [...]
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...