OpenGL 使用统一缓冲区作为数组

OpenGL use uniform buffer as an array

我发现我可以像这样使用统一缓冲区来存储多个变量

#version 330 core
layout (location = 0) in vec3 aPos;

layout (std140) uniform Matrices
{
    mat4 projection;
    mat4 view;
};

uniform mat4 model;

void main()
{
    gl_Position = projection * view * model * vec4(aPos, 1.0);
}  

并像处理任何其他缓冲区一样处理此数据


unsigned int uboMatrices
glGenBuffers(1, &uboMatrices);
  
glBindBuffer(GL_UNIFORM_BUFFER, uboMatrices);
glBufferData(GL_UNIFORM_BUFFER, 2 * sizeof(glm::mat4), NULL, GL_STATIC_DRAW);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
  
glBindBufferRange(GL_UNIFORM_BUFFER, 0, uboMatrices, 0, 2 * sizeof(glm::mat4));

但是,我似乎找不到任何允许我将此类缓冲区视为数组的示例。本质上我想实现这样的全局随机访问缓冲区

#version 330 core
layout (location = 0) in vec3 aPos;

layout (what here?) uniform float[] globalBuffer;

uniform mat4 model;

void main()
{
    ...
}  

长期计划是稍后使用 OpenCL 生成此阵列

uniform float[] globalBuffer; 不是统一缓冲区。它只是一组制服。您必须使用 glUniform1fv.

设置制服

A Uniform block 将是:

layout (std140) uniform Foo 
{ 
    float[] globalBuffer; 
}

不幸的是,在这种情况下,每个数组元素都将与 vec4 的大小对齐。见 OpenGL 4.6 API Core Profile Specification; 7.6.2.2 Standard Uniform Block Layout:

  1. If the member is an array of scalars or vectors, the base alignment and array stride are set to match the base alignment of a single array element, according to rules (1), (2), and (3), and rounded up to the base alignment of a vec4.

我建议使用 Shader Storage Buffer Object

layout (std430) buffer Foo
{
    float[] globalBuffer; 
};

OpenGL 4.6 API Core Profile Specification; 7.6.2.2 Standard Uniform Block Layout:

Shader storage blocks (see section 7.8) also support the std140 layout qualifier, as well as a std430 qualifier not supported for uniform blocks. When using the std430 storage layout, shader storage blocks will be laid out in buffer storage identically to uniform and shader storage blocks using the std140 layout, except that the base alignment and stride of arrays of scalars and vectors in rule 4 and of structures in rule 9 are not rounded up a multiple of the base alignment of a vec4.