OpenGL glVertexPointer,glDrawElements无法正确绘制线循环

时间:2019-10-24 16:11:09

标签: c++ opengl opengl-compat

尝试使用GL_LINE_LOOP绘制简单的房屋,房屋的主体很好,但是屋顶是完全错误的:

glClearColor(1.0, 1.0, 1.0, 0.0);

typedef GLfloat vertex[2];

static const
vertex house_roof[3] = {
    {  0.0, 0.4 },
    { -0.3, 0.2 },
    {  0.3, 0.2 }
};

static const
vertex house_body[4] = {
    { -0.2,  0.2 },
    { -0.2, -0.2 },
    {  0.2, -0.2 },
    {  0.2,  0.2 }
};

static const
GLubyte indexes_roof[3] = {0, 1, 2};

static const
GLubyte indexes_body[4] = {0, 1, 2, 3};

glColor3f(0.0, 0.0, 0.0);

glEnableClientState(GL_VERTEX_ARRAY);

glVertexPointer(2, GL_FLOAT, 0, house_roof);
glDrawElements(GL_LINE_LOOP, 3, GL_UNSIGNED_BYTE, indexes_roof);

glVertexPointer(2, GL_FLOAT, 0, house_body);
glDrawElements(GL_LINE_LOOP, 4, GL_UNSIGNED_BYTE, indexes_body);

glDisableClientState(GL_VERTEX_ARRAY);
glFlush();

这将产生以下结果:

enter image description here

这里的屋顶是从(0,0)到(0,0.4)的黑色垂直线。车身已正确绘制,但由于某些原因屋顶始终不正确。如何正确绘制屋顶?

编辑

在完成一个完整的最小示例之后,我就解决了这个问题。原始代码将房子放在单独的house.hhouse.cpp文件中,分别导入到main.cpp中。上面的代码是房屋渲染功能。

#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>

#include "house.h"

House houses[1];

void loop() {
    glClear(GL_COLOR_BUFFER_BIT);
    houses[0].render();
}

int main(int argc, char** argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowPosition(50, 100);
    glutInitWindowSize(400, 300);
    glutCreateWindow("Test");
    glClearColor(1.0, 1.0, 1.0, 0.0);

    glutDisplayFunc(loop);
    glutMainLoop();
}

当我搬房子时,将额外的方法(尚未实现)剥离到一个文件中,程序开始工作。只需移动代码即可。我想知道我当时是否编译不正确。

g++ -std=c++17 -o Test main.cpp house.cpp -I./ -lglut -lGL -lGLU

0 个答案:

没有答案
相关问题