GLSL:缺少顶点

时间:2013-06-24 13:20:31

标签: opengl glsl

当我使用立即模式时,它会正确绘制,但是当我将相同的顶点传递给GPU,或者甚至指向它们时,它都不起作用。

有一个位置缓冲区保存顶点:

std::vector<glm::vec3> posbuf;

及其指数。

立即模式:

for (unsigned int i =0; i < indices.size(); i++) {
    glBegin(GL_TRIANGLES);
    glVertex3f(posbuf[indices[i].index[0]].x, posbuf[indices[i].index[0]].y, posbuf[indices[i].index[0]].z);
    glVertex3f(posbuf[indices[i].index[1]].x, posbuf[indices[i].index[1]].y, posbuf[indices[i].index[1]].z);
    glVertex3f(posbuf[indices[i].index[2]].x, posbuf[indices[i].index[2]].y, posbuf[indices[i].index[2]].z);
    glEnd();
    }

这是顶点属性代码:

glEnableVertexAttribArray(GL_ATTRIB_POS);
glVertexAttribPointer(GL_ATTRIB_POS, 3, GL_FLOAT, GL_FALSE, 0,&posbuf[0]);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indVBO);
glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glDisableVertexAttribArray(GL_ATTRIB_POS);

和它的着色器:

#version 120
attribute vec3 position;
void main()
{
    vec4 finalv=vec4(position, 1.0);
    gl_Position = gl_ModelViewProjectionMatrix * vec4(finalv.xyz,1.0);
}

[frag]
#version 120


void main()
{
gl_FragColor = vec4(1.0,0.0,0.0,1.0);
}

立即结果:enter image description here

着色器结果: enter image description here

我不知道出了什么问题,我也尝试使用glm :: value_ptr传递posbuf,它们都给出相同的结果。我在fedora 18上,支持glsl到#version 140,opengl 3.3。

编辑:

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indVBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(Triangle) * indices.size(), &indices[0], GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

struct Triangle {
int index[3];
};

1 个答案:

答案 0 :(得分:2)

您的indices向量似乎包含完整的三角形,每个三角形包含3个索引。但是在glDrawElements中,您使用indices.size()作为要绘制的元素数量。但是glDrawElements没有采用基元的数量,而是采用索引的数量,所以你缺少了2/3的三角形。它应该是

glDrawElements(GL_TRIANGLES, indices.size() * 3, GL_UNSIGNED_INT, 0);

(并且indices应该重命名为triangles以避免进一步混淆。顺便说一下,index可能应该是unsigned int[3]承诺的OpenGL。在任何合理的系统上intunsigned int之间不存在代表性差异,但在告诉OpenGL它是int时使用unsigned int有点不一致。)

相关问题