所以我对opengl很新,目前正在学习实例化渲染。我试图渲染3个具有不同位置和颜色的三角形但无法使其工作。这是我的代码:
GLfloat verts[] = {
-0.5f, -0.5f,
-0.5f, +0.5f,
0.0f, -0.5f
};
GLuint vertexBufferID;
glGenBuffers(1, &vertexBufferID);
glBindBuffer(GL_ARRAY_BUFFER, vertexBufferID);
glBufferData(GL_ARRAY_BUFFER, sizeof(verts), verts, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);
GLfloat xOffsets[] = { 0.0f, 0.5f, 1.0f };
GLuint offsetsBufferID;
glGenBuffers(1, &offsetsBufferID);
glBindBuffer(GL_ARRAY_BUFFER, offsetsBufferID);
glBufferData(GL_ARRAY_BUFFER, sizeof(xOffsets), xOffsets, GL_STATIC_DRAW);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 1, GL_FLOAT, GL_FALSE, 0, 0);
glVertexAttribDivisor(1, 1);
unsigned int colors[] = { 0xffff0000, 0xff00ff00, 0xff00ff00 };
GLuint colorID;
glGenBuffers(1, &colorID);
glBindBuffer(GL_ARRAY_BUFFER, colorID);
glBufferData(GL_ARRAY_BUFFER, sizeof(colors), colors, GL_STATIC_DRAW);
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, 0);
glVertexAttribDivisor(1, 1);
GLushort indices[] = { 0, 1, 2 };
GLuint indexArrayBufferID;
glGenBuffers(1, &indexArrayBufferID);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexArrayBufferID);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
顶点着色器:
#version 330 core
layout(location = 0) in vec2 position;
layout(location = 1) in float offset;
layout(location = 2) in vec4 color;
out vec4 col;
void main()
{
gl_Position = vec4(position.x + offset, position.y, 0, 1);
col = color;
}
片段:
#version 330 core
out vec4 color;
in vec4 col;
void main()
{
color = col;
}
这是我呈现的方式:
glDrawElementsInstanced(GL_TRIANGLES, 3, GL_UNSIGNED_SHORT, 0, 3);
正如您所看到的,三角形位于正确的位置,但颜色是错误的。第一个三角形应为蓝色,其他两个应为绿色。但是在这里看起来每个三角形中的1个顶点都是蓝色的。我在这里做错了什么?