我发现我可以使用统一缓冲区来存储多个变量,如下所示
#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
设置制服.
一个Uniform block将是:
layout (std140) uniform Foo
{
float[] globalBuffer;
}
不幸的是,在这种情况下,每个数组元素都将与 vec4
的大小对齐。请参阅OpenGL 4.6 API Core Profile Specification; 7.6.2.2 Standard Uniform Block Layout :
- 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 astd430
qualifier not supported for uniform blocks. When using thestd430
storage layout, shader storage blocks will be laid out in buffer storage identically to uniform and shader storage blocks using thestd140
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 avec4
.
关于c++ - OpenGL使用统一缓冲区作为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68153281/