【发布时间】:2014-07-01 00:57:45
【问题描述】:
我想绘制实例立方体。
我可以成功拨打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 个向量)* array-size。
绘制循环:
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);
VertexAttribPointer(..., 4, VertexattribPointerType.Float, ...); 中任何大于 4 的数字都会导致崩溃。我觉得我必须将该值设置为 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-parameter 设置为 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;
}
【问题讨论】: