我无法弄清楚为什么下面的代码不起作用,我正在尝试绘制 2 个形状,一个红色的三角形和一个多色的立方体,它们本身可以完美地绘制,但是如果我尝试同时绘制两者给出了奇怪的错误,我尝试在改变变量修改我的着色器周围改变线条,但我似乎无法接近我想要的结果,当前代码最终绘制了 2 个使用立方体颜色的相同三角形。
GLuint VertexArrayID;
glGenVertexArrays(1, &VertexArrayID);
glBindVertexArray(VertexArrayID);
GLuint MatrixID = glGetUniformLocation(shader->id(), "MVP");
glm::mat4 Projection = glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 100.0f);
glm::mat4 View = glm::lookAt(
glm::vec3(4,2,2), // Camera location
glm::vec3(0,0,0), // and looks at the origin
glm::vec3(0,1,0) // Head is up (set to 0,-1,0 to look upside-down)
);
glm::mat4 myMatrix = glm::translate(-2.f,0.f,0.f);
glm::mat4 Model = glm::mat4(1.f);
Model= myMatrix * Model;
glm::mat4 MVP = Projection * View * Model;
glm::mat4 myMatrix2 = glm::translate(2.f,0.f,0.f);
glm::mat4 Model2 = glm::mat4(1.f);
Model2= myMatrix2 * Model2;
glm::mat4 MVP2 = Projection * View * Model2;
glViewport(0, 0, windowWidth, windowHeight); // set viewport to the size of the window
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
shader->bind();
glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,0,(void*)0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, colourBuffer);
glVertexAttribPointer(1,3,GL_FLOAT,GL_FALSE,0,(void*)0);
glDrawArrays(GL_TRIANGLES,0,12*3);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP2[0][0]);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer2);
glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,0,(void*)0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, colourBuffer2);
glVertexAttribPointer(1,3,GL_FLOAT,GL_FALSE,0,(void*)0);
glDrawArrays(GL_TRIANGLES, 0, 3);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
SwapBuffers(hdc);
glDeleteBuffers(1, &vertexBuffer);
glDeleteBuffers(1, &vertexBuffer2);
glDeleteBuffers(1, &colourBuffer);
glDeleteBuffers(1, &colourBuffer2);
shader->unbind();
glDeleteVertexArrays(1, &VertexArrayID);
这是主要代码。我以类似的方式创建所有缓冲区,基本上使用以下 3 行的变体来插入不同的缓冲区名称和数据,
glGenBuffers(1, &vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER,sizeof(Cube), Cube, GL_STATIC_DRAW);
片段着色器
#version 330 core
in vec3 fragmentColour;
out vec3 colour;
void main(){
colour = fragmentColour;
}
顶点着色器
#version 330 core
uniform mat4 MVP;
layout(location = 0) in vec3 vertexPosition_modelspace;
layout(location = 1) in vec3 vertexColour;
out vec3 fragmentColour;
void main(){
gl_Position = MVP * vec4(vertexPosition_modelspace,1);
fragmentColour = vertexColour;
}