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

标签 c++ opengl glsl

我发现我可以使用统一缓冲区来存储多个变量,如下所示

#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 :

  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.

关于c++ - OpenGL使用统一缓冲区作为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68153281/

相关文章:

c++ - 在 OpenGL 中将窗口坐标转换为轴坐标

opengl - 如何查询 SSBO 结构的对齐/步幅?

C++ 地址存在吗?

c++ - 资源文件是编译为 UNICODE 还是 ANSI 代码页?

c++ - snprintf 是否可能返回以 '\0' 开头的字符数组?

opengl - GLSL 着色器在需要时不展开循环

opengl-es - webGL2统一缓冲区对象和布局的使用(std140)

c++ - GHC 未链接依赖项

opengl - 如何创建 4 维纹理?

opengl - 如何实现两次 channel 之间的深度值不变?