OpenGL常见的一些错误

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后,重新开始图元的绘制,比如三角形带会断开重开始。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值