glDrawElements的时候,发现索引(indices)报错 。数据为 0 1 2 3 4 -1 5 6 7 8 9 -110 11 12... 就是索引中出现了负值。
谷歌后找到结果:http://stackoverflow.com/questions/26113159/opengl-is-adding-an-extra-vertex-to-the-mesh-in-obj-loader
If present, negative indices are relative to the end of the vertices read so far. E.g. index -1 is the latest vertex read, -2 the second latest, etc.
如果存在负值的话,负值对应着顶点数组的末尾。例如 索引为-1 则最后一个顶点被访问,-2是倒数第二个,。
接着我来测试一下:
int w = picRect.Width(), h = picRect.Height();
glewInit();
glViewport(0, 0, (GLsizei)w, (GLsizei)h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, (GLdouble)w, 0.0, (GLdouble)h);
//glTranslatef(0.0f, 0.0f, 0.5f);
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
glShadeModel(GL_SMOOTH);
//GLuint VBO, IBO;
static GLint vertices[] = { 25, 25,
100, 325,
175, 25,
175, 325,
250, 25,
325, 325 };
static GLfloat colors[] = { 1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0,
1.0, 1.0, 0.0,
1.0, 0.0, 1.0,
0.0, 1.0, 1.0 };
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glVertexPointer(2, GL_INT, 0, vertices);
glColorPointer(3, GL_FLOAT, 0, colors);
GLuint indices[] = { 0, 1, 2, 2, 4 ,5};
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, indices);//GL_POLYGON
这是正常绘制的结果。
按英文内容说的话:将索引数组改为GLuint indices[] = { 0, 1, 2, -1, 4 ,5}; 也能绘制出同样的结果。
然而没有画出预期的图形,最后测试得知:
当索引为负值时,glDrawElements使用的是glVertexPointer指定的buffer向前偏移的值。
修改代码来解释一下
int w = picRect.Width(), h = picRect.Height();
glewInit();
glViewport(0, 0, (GLsizei)w, (GLsizei)h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, (GLdouble)w, 0.0, (GLdouble)h);
//glTranslatef(0.0f, 0.0f, 0.5f);
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
glShadeModel(GL_SMOOTH);
GLuint IBO;
static GLint vertices[] = {25,100,
50, 50,
100, 325,
175, 25,
175, 325,
250, 25,
325, 325 };
static GLfloat colors[] = { 1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0,
1.0, 1.0, 0.0,
1.0, 0.0, 1.0,
0.0, 1.0, 1.0,
1.0, 1.0, 1.0};
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glVertexPointer(2, GL_INT, 0, vertices+2);
glColorPointer(3, GL_FLOAT, 0, colors+3);
GLuint indices[] = { 0, 1, 2, -1, 4 ,5};
glGenBuffers(1, &IBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, 6 * sizeof(unsigned int), indices, GL_STATIC_DRAW);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0/*indices*/);//GL_POLYGON
图片的绘制结果说明-1值指向的顶点并非查到的文章里面说的last read vertex。而是buffer向前偏移的那个值。
再后来,找到了这种用法的api叫重启图元,在遇到设定的索引-1后,重新开始图元的绘制,比如三角形带会断开重开始。