我正在使用两个渲染程序将两个不同的对象渲染到屏幕上。每个程序都有自己的与其关联的顶点和片段着色器。
在下面的代码中,我创建第一个渲染程序并使用 GL_ARRAY_BUFFER 将顶点加载到着色器中:
boardRenderingProgram = compileBoardShaders();
vector<GLfloat> boardVertices = board.getBorderVertices();
GLfloat* borderVertices = &boardVertices[0];
GLuint numberOfVerts = boardVertices.size();
GLuint anotherVBO;
GLuint anotherBuffer;
glGenVertexArrays(1, &anotherVBO);
glBindVertexArray(anotherVBO);
glGenBuffers(1, &anotherBuffer);
glBindBuffer(GL_ARRAY_BUFFER, anotherBuffer);
glBufferData(GL_ARRAY_BUFFER, numberOfVerts*3*sizeof(GLfloat), NULL, GL_STATIC_DRAW);
glBufferSubData(GL_ARRAY_BUFFER, 0, numberOfVerts*3*sizeof(GLfloat), borderVertices);
vert = glGetAttribLocation(boardRenderingProgram, "vBoardPosition");
glVertexAttribPointer(vert, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(vert);
第一个程序的顶点着色器:
#version 330 core
layout(location = 0) in vec4 vBoardPosition;
void main() {
gl_Position = vBoardPosition;
}
然后我对第二个渲染程序执行完全相同的操作,我还在第二个程序中设置旋转和平移矩阵:
renderingProgram = compileShaders();
moveMatrix = glm::make_mat4(moveArray);
currentBlockVertices = generator.getRandomBlock(blockNumber).getVertices();
numberOfVertices = 8;
GLfloat* vertices = ¤tBlockVertices[0];
glGenVertexArrays(1, &vertexArrayObject);
glBindVertexArray(vertexArrayObject);
glGenBuffers(1, &buffer);
glBindBuffer(GL_ARRAY_BUFFER, buffer);
glBufferData(GL_ARRAY_BUFFER, numberOfVertices*7*sizeof(GLfloat), NULL, GL_STATIC_DRAW);
glBufferSubData(GL_ARRAY_BUFFER, 0, numberOfVertices*3*sizeof(GLfloat), vertices);
vpos = glGetAttribLocation(renderingProgram, "vPosition");
glVertexAttribPointer(vpos, 3, GL_FLOAT, GL_FALSE, 0, 0);
mpos = glGetUniformLocation(renderingProgram, "mMove");
rpos = glGetUniformLocation(renderingProgram, "mRotate");
glProgramUniformMatrix4fv(renderingProgram, mpos, 1, GL_FALSE, glm::value_ptr(moveMatrix));
glProgramUniformMatrix4fv(renderingProgram, rpos, 1, GL_FALSE, glm::value_ptr(rotateMatrix));
glEnableVertexAttribArray(vpos);
第二个程序的顶点着色器:
#version 330 core
layout(location = 0) in vec4 vPosition;
layout(location = 1) uniform mat4 mMove;
layout(location = 2) uniform mat4 mRotate;
void main() {
gl_Position = mMove * mRotate * vPosition;
}
创建这些程序后,我在渲染函数中使用以下代码将它们绘制到屏幕上:
glUseProgram(boardRenderingProgram);
glDrawArrays(GL_POINTS, 0, 8);
glUseProgram(renderingProgram);
glDrawArrays(GL_LINE_LOOP, 0, 8);
SwapBuffers(hDC_);
然而,尽管指定了不同的顶点加载到每个渲染程序中,但这两个渲染程序都会将相同的顶点绘制到屏幕上。似乎第二个创建的渲染程序决定了使用哪些顶点。
我尝试在设置顶点和矩阵属性之前和之后添加额外的 glUseProgram() 调用,但这似乎没有帮助。
当我将不同的顶点加载到每个程序中时,为什么两个程序绘制相同的顶点?
最佳答案
#version 330 core
...
layout(location = 1) uniform mat4 mMove;
layout(location = 2) uniform mat4 mRotate;
^^^^^^^^^^^^^^^^^^^^
Explicit uniform locations自 OpenGL 4.3 起才成为核心。您需要检查 GL_ARB_explicit_uniform_location
之前using them在之前的版本上。
我怀疑你的第二个着色器无法编译。确保在调用 glUseProgram()
之前通过 GL_COMPILE_STATUS
/GL_LINK_STATUS
检查着色器编译和程序链接是否成功。
关于c++ - opengl 着色器程序中的重复顶点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21715126/