我试图在OpenGL中绘制一个简单的正方形时,我得到一个完全黑屏。在创建缓冲区之前调用这些方法:
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glOrtho(0.0f, windowX, windowY, 0.0f, 1000.0f, 0);
我正在创建缓冲区:
std::vector<unsigned int> indices;
std::vector<unsigned int> vertices;
vertices.push_back(0);
vertices.push_back(0);
vertices.push_back(0);
vertices.push_back(100);
vertices.push_back(0);
vertices.push_back(0);
vertices.push_back(100);
vertices.push_back(100);
vertices.push_back(0);
vertices.push_back(0);
vertices.push_back(100);
vertices.push_back(0);
indices.push_back(0);
indices.push_back(1);
indices.push_back(2);
indices.push_back(2);
indices.push_back(3);
indices.push_back(0);
glGenBuffers(1, &verticesbuffer);
glBindBuffer(GL_ARRAY_BUFFER, verticesbuffer);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(vertices[0]), &vertices[0], GL_STATIC_DRAW);
glGenBuffers(1, &indicesbuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicesbuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(indices[0]), &indices[0], GL_STATIC_DRAW);
显示功能:
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glBindBuffer(GL_ARRAY_BUFFER, verticesbuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicesbuffer);
glVertexPointer(3, GL_INT, 0, &vertices[0]);
glColor3f(1, 0, 0);
glEnableClientState(GL_VERTEX_ARRAY);
glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, &indices[0]);
glDisableClientState(GL_VERTEX_ARRAY);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
我已经开始使用AMD GPU PerfStudio查看我的程序的绘图调用,并且在glDrawElements()调用中,PerfStudio向我显示顶点和索引缓冲区后面的数据(索引缓冲区显然是完全空的,而顶点缓冲区只有一个点设置为x = y = z = 3.40282e + 038(最大浮点值)):
Unable to map element array buffer for reading.
GL_VERTEX_ARRAY_SIZE: 3
GL_VERTEX_ARRAY_TYPE: GL_INT
GL_VERTEX_ARRAY_STRIDE: 0
GL_VERTEX_ARRAY_POINTER: 0x0C30F2A8
GL_VERTEX_ARRAY_BUFFER_BINDING: 1
BufferState
GL_BUFFER_SIZE: 0
GL_BUFFER_USAGE: GL_STATIC_DRAW
GL_BUFFER_ACCESS: GL_READ_WRITE
GL_BUFFER_MAPPED: GL_FALSE
GL_BUFFER_MAP_POINTER: 0x00000000
显然这些价值观中的一些是不正确的,我只是无法弄清楚为什么它们没有像预期的那样出来。
答案 0 :(得分:5)
之前必须提出,但我无法通过快速搜索找到明确的副本。
问题在于:
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicesbuffer);
...
glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, &indices[0]);
在GL_ELEMENT_ARRAY_BUFFER
调用期间绑定glDrawElements()
时,代码就是这种情况,glDrawElements()
的最后一个参数是偏移到索引缓冲区。您传递的是索引缓冲区的CPU地址。
如果你想从它的开始使用索引缓冲区,这是你的情况下正确的做法,偏移应该是0:
glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0);
非常相似,这也被打破了:
glBindBuffer(GL_ARRAY_BUFFER, verticesbuffer);
...
glVertexPointer(3, GL_INT, 0, &vertices[0]);
同样,当绑定GL_ARRAY_BUFFER
时,glVertexPointer()
的最后一个参数是缓冲区的偏移量。所以这应该是:
glVertexPointer(3, GL_INT, 0, 0);
BTW,在OpenGL中使用整数作为顶点坐标是很不寻常的。看起来它支持,所以它应该工作。但是,使用GLfloat
/ GL_FLOAT
作为坐标会更常见,也可能更有效。