我想绘制实例化的立方体。
我可以成功调用GL.DrawArraysInstanced(PrimitiveType.Triangles, 0, 36, 2);
。
我的问题是所有的立方体都在同一位置和同一旋转角度上绘制。如何为每个立方体单独更改它们的位置和旋转角度?
为了创建不同的位置等,我需要为每个立方体创建一个矩阵,对吗?我已经创建了这个:
Matrix4[] Matrices = new Matrix4[]{
Matrix4.Identity, //do nothing
Matrix4.Identity * Matrix4.CreateTranslation(1,0,0) //move a little bit
};
GL.BindBuffer(BufferTarget.ArrayBuffer, matrixBuffer);
GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(sizeof(float) * 16 * Matrices.Length), Matrices, BufferUsageHint.StaticDraw);
我需要创建一个缓冲区来存储矩阵。 matrixBuffer
是指向我的缓冲区的指针。我不确定大小是否正确,我使用了 float * 4(用于 Vector4)* 4(用于 4 个向量)* 数组大小。
绘制循环:
GL.BindBuffer(BufferTarget.ArrayBuffer, matrixBuffer);
GL.VertexAttribPointer(3, 4, VertexAttribPointerType.Float, false, 0, 0);
//GL.VertexAttribDivisor(3, ?);
GL.EnableVertexAttribArray(3);
GL.DrawArraysInstanced(PrimitiveType.Triangles, 0, 36, 2);
任何大于4的数字在
VertexAttribPointer(..., 4, VertexattribPointerType.Float, ...);
中都会导致崩溃。我以为我需要将该值设为16?我不确定是否需要一个VertexAttribDivisor,可能我需要每36个顶点调用一次
GL.VertexAttribDivisor(3, 36);
?但是当我这样做时,我看不到任何立方体。我的顶点着色器:
#version 330 core
layout(location = 0) in vec3 position;
layout(location = 1) in vec4 color;
layout(location = 2) in vec2 texCoord;
layout(location = 3) in mat4 instanceMatrix;
uniform mat4 projMatrix;
out vec4 vColor;
out vec2 texCoords[];
void main(){
gl_Position = instanceMatrix * projMatrix * vec4(position, 1.0);
//gl_Position = projMatrix * vec4(position, 1.0);
texCoords[0] = texCoord;
vColor = color;
}
所以我的问题是:
- 我的代码有什么问题?
- 为什么我只能将VertexAttribPointer的size参数设置为4?
- VertexAttribDivisor的正确值是什么?
编辑:
根据Andon M. Coleman的回答,我做出了以下更改:
GL.BindBuffer(BufferTarget.UniformBuffer, matrixBuffer);
GL.BufferData(BufferTarget.UniformBuffer, (IntPtr)(sizeof(float) * 16), IntPtr.Zero, BufferUsageHint.DynamicDraw);
//Bind Buffer to Binding Point
GL.BindBufferBase(BufferRangeTarget.UniformBuffer, matrixUniform, matrixBuffer);
matrixUniform = GL.GetUniformBlockIndex(shaderProgram, "instanceMatrix");
//Bind Uniform Block to Binding Point
GL.UniformBlockBinding(shaderProgram, matrixUniform, 0);
GL.BufferSubData(BufferTarget.UniformBuffer, IntPtr.Zero, (IntPtr)(sizeof(float) * 16 * Matrices.Length), Matrices);
关于着色器:
#version 330 core
layout(location = 0) in vec4 position; //gets vec3, fills w with 1.0
layout(location = 1) in vec4 color;
layout(location = 2) in vec2 texCoord;
uniform mat4 projMatrix;
uniform UniformBlock
{ mat4 instanceMatrix[]; };
out vec4 vColor;
out vec2 texCoords[];
void main(){
gl_Position = projMatrix * instanceMatrix[0] * position;
texCoords[0] = texCoord;
vColor = color;
}
instanceMatrix[0]
更改为instanceMatrix[gl_InstanceID]
时,我会得到以下错误:"OpenGL需要常量索引来访问未定大小的数组(instanceMatrix)"。你能帮我解决这个问题吗? - fedab