我正在尝试使用带有 Qt 的 OpenGL 中的顶点缓冲区对象绘制一个样方。这是我的几何:
numVertices = 4;
vertices = new float[3*numVertices];
int i = 0;
vertices[i++] = 0.0f; vertices[i++] = 0.0f; vertices[i++] = 0.0f; // (0,0,0)
vertices[i++] = 1.0f; vertices[i++] = 0.0f; vertices[i++] = 0.0f; // (1,0,0)
vertices[i++] = 1.0f; vertices[i++] = 1.0f; vertices[i++] = 0.0f; // (1,1,0)
vertices[i++] = 0.0f; vertices[i++] = 1.0f; vertices[i++] = 0.0f; // (0,1,0)
i = 0;
// spilt quad into two triangles:
numTriangles = 2;
indices = new unsigned int[numTriangles*3];
indices[i++] = 0; indices[i++] = 1; indices[i++] = 2;
indices[i++] = 0; indices[i++] = 2; indices[i++] = 3;
接下来在 initializeGL 方法中:
QGLBuffer vertexBuffer;
vertexBuffer.create();
vertexBuffer.bind();
vertexBuffer.allocate(vertices, numVertices*sizeof(float));
QGLShaderProgram* shaderProgram_ = new QGLShaderProgram;
shaderProgram_->addShaderFromSourceFile(QGLShader::Vertex,"C:/src/light.vert.glsl") ) {
shaderProgram_->addShaderFromSourceFile(QGLShader::Fragment, "C:/src/light.frag.glsl");
bool ok = shaderProgram_->link();
ok = shaderProgram_->bind();
我认为 VBO 部分所做的就是将顶点复制到 GPU?(为什么这么多行?)
着色器部分适用于旧式 glBegin(GL_QUADS);
接下来在我的paintGL方法中:
shaderProgram_->setAttributeBuffer("vertex", GL_FLOAT, 0, 3, 0);
shaderProgram_->enableAttributeArray("vertex");
glDrawElements(GL_TRIANGLES, numTriangles, GL_UNSIGNED_INT, indices);
前两条线在做什么?也许告诉着色器有一个名为“顶点”的顶点缓冲区,类型为 GL_FLOAT?但是我在创建 VBO 时没有指定任何名称!?OpenGL如何知道这是“顶点”?
反正我什么都没看到!?有没有我遗漏的步骤?我的着色器很简单:
# version 120
varying vec4 color;
void main() {
vec4 vertex = gl_Vertex;
// pass trough:
gl_Position = gl_ProjectionMatrix * gl_ModelViewMatrix * vertex;
color = gl_Color;
}
# version 120
varying vec4 color;
void main (void)
{
// pass-trough:
gl_FragColor = color;
}