【问题标题】:OpenGL with GLUT. Not Drawing?带有 GLUT 的 OpenGL。不会画画?
【发布时间】:2012-07-23 04:45:47
【问题描述】:
#include <GL/gl.h>
#include <GL/glut.h>

void display();
void init();

int main(int argc, char* argv[])
{
    init();

    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
    glutInitWindowSize(320, 240);
    glutCreateWindow("Main Window");
    glutDisplayFunc(display);
    glutMainLoop();

    return 0;
}

void init()
{
    glDisable(GL_DEPTH_TEST);
}

void display()
{
    glClearColor(0, 0, 0, 0);
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

    glLoadIdentity();

    glBegin(GL_QUADS);
    glColor3i(255,255,255);
        glVertex2f(10, 10);
        glVertex2f(100, 10);
        glVertex2f(100, 100);
        glVertex2f(10, 100);
    glEnd();

    glutSwapBuffers();
}

理论上,这段代码应该绘制一个白色矩形。但我看到的只是一个黑色的空屏幕。怎么了?

【问题讨论】:

  • 该矩形很可能不在您的相机区域内。
  • 此外,据我所知,quad的顶点必须按逆时针顺序定义。

标签: c++ opengl glut freeglut


【解决方案1】:

这是我所做的更改的工作示例,由 cmets 记录:

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

#define WINDOW_WIDTH 320
#define WINDOW_HEIGHT 240

void display();
void init();

int main(int argc, char* argv[])
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
    glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
    glutCreateWindow("Main Window");
    init(); // changed the init function to come directly before display function
    glutDisplayFunc(display);
    glutMainLoop();

    return 0;
}

void init()
{
    glClearColor(0, 0, 0, 0); // moved this line to be in the init function
    glDisable(GL_DEPTH_TEST);

    // next four lines are new
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0.0, WINDOW_WIDTH-1, WINDOW_HEIGHT-1, 0, -1.0, 1.0);
    glMatrixMode(GL_MODELVIEW);
}

void display()
{
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();

    glBegin(GL_QUADS);
    glColor3ub(255,255,255); // changed glColor3i to glColor3ub (see below)
        glVertex2f(10, 10);
        glVertex2f(100, 10);
        glVertex2f(100, 100);
        glVertex2f(10, 100);
    glEnd();

    glFlush(); // added this line 
    //glutSwapBuffers(); // removed this line
}

glColor3ub 是您想要提供 0-255 范围内的颜色时要使用的函数。

希望这会有所帮助。

【讨论】:

  • opengl.org/sdk/docs/man/xhtml/glFlush.xml。它强制执行前面的 gl 命令。
  • @BЈовић 请参阅上面的评论,如果没有那行,它将无法使用。
  • 附带说明,您应该将init 中的代码放入绘图路由中,因为那才是它真正所属的地方。
  • 为什么在glOrtho 中将WINDOW_WIDTHWINDOW_HEIGHT 减去1?
  • 好的,你需要GLUT_SINGLE模式。那你就不需要glutSwapBuffers();
猜你喜欢
  • 2023-03-22
  • 2012-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-16
  • 2012-05-05
  • 2021-11-19
  • 1970-01-01
相关资源
最近更新 更多