我用SDL窗口编写了一个OpenGL应用程序。在Mac OSX 10.9上运行OpenGL 4.1的核心配置文件。命令glclearcolor
工作得很好,我在屏幕上得到了正确的颜色。但是在我的呈现器中,每次执行命令glenablevertexattribarray
和gldrawarrays
时,都会出现gl_invalid_operation
错误。
这就是代码:
顶点着色器:
#version 410
in vec4 position;
void main(void)
{
gl_Position = position;
}
#version 410
out vec4 out_Color;
void main(void)
{
out_Color = vec4(0.0, 1.0, 0.0, 1.0);
}
static const float VertexBufferData[] = {
0.75f, 0.75f, 0.0f, 1.0f,
0.75f, -0.75f, 0.0f, 1.0f,
-0.75f, -0.75f, 0.0f, 1.0f,
};
glGenBuffers(1, &m_VertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, m_VertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(VertexBufferData), VertexBufferData, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glUseProgram(m_ShaderProgram);
glBindBuffer(GL_ARRAY_BUFFER, m_VertexBuffer);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);
glDrawArrays(GL_TRIANGLES, 0, 3);
// glDrawElements( GL_TRIANGLES, 3, GL_UNSIGNED_INT, nullptr);
glDisableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glUseProgram(0);
产出:
正如BDL所说:解决方案是创建一个VAO。作为一个简短的描述:VAO(顶点数组对象)是一个VBO的集合,它描述顶点布局和着色器的顶点。
更多信息请参见:
static const float VertexBufferData[] = {
0.75f, 0.75f, 0.0f, 1.0f,
0.75f, -0.75f, 0.0f, 1.0f,
-0.75f, -0.75f, 0.0f, 1.0f,
};
glGenVertexArrays(1, &m_VertexBufferArray);
glBindVertexArray(m_VertexBufferArray);
glGenBuffers(1, &m_VertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, m_VertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(VertexBufferData), VertexBufferData, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);
glBindVertexArray(0);
glUseProgram(m_ShaderProgram);
glBindVertexArray(m_VertexBufferArray);
glDrawArrays(GL_TRIANGLES, 0, 3);
glBindVertexArray(0);
glUseProgram(0);