FreeGLUT window 在启动时消失

FreeGLUT window disappearing on startup

我今天刚开始使用 OpenGL,并在 Visual Studio 2010 年跟随 a tutorial 建立了一个 OpenGL 项目。 但是当我 运行 代码时,我得到一个 window 打开非常快,闪烁然后消失。这正常吗?

#include <GL\glew.h>
#include <GL\freeglut.h>
#include <iostream>

using namespace std;

//Window Resized, this function get called "glutReshapedFunc" in main
void changeViewport(int w, int h) {
      glViewport(0, 0, w, h);
}

//Here s a function that gets Called time Windows need to the redraw.
//Its the "paint" method for our program, and its setup from the glutDisplayFunc in main
void render() {

     glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
     glutSwapBuffers();
}

int main(int argc, char** argv) {
    //Initialize GLUT
    glutInit(&argc, argv);

    //Setup some Memory Buffer for our Display
    glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGBA|GLUT_DEPTH);

    //Setup Window Size
    glutInitWindowSize(800,600);

    //Create Window with Title
    glutCreateWindow("GL_HelloWorld");

    //Bind two functions (above) respond when necessary
    glutReshapeFunc(changeViewport);
    glutDisplayFunc(render);

    //Very important! this initialize the entry points in the OpenGL driver so we can
    //Call all the functions in the API
    GLenum err = glewInit();
    if (GLEW_OK != err) {
        fprintf(stderr, "GLEW error");
        return 1;
    }

}

您错过了 glutMainLoop 进入 GLUT 事件处理循环的时间:

int main(int argc, char** argv) {

    // [...]

    glutDisplayFunc(render);

    //Very important! this initialize the entry points in the OpenGL driver so we can
    //Call all the functions in the API
    GLenum err = glewInit();
    if (GLEW_OK != err) {
        fprintf(stderr, "GLEW error");
        return 1;
    }

    // start event processing loop - causes 1st call of "render"
    glutMainLoop();

    return 0;
}

此函数从不 returns、处理事件并执行回调,如显示回调 (render)。该函数处理主应用程序循环。 如果不调用此函数,则程序会在创建 window 后立即终止。

如果您希望您的应用程序不断重绘场景,那么您必须在 render 中调用 glutPostRedisplay()。这将当前 window 标记为需要重新显示,并导致在事件处理循环中再次调用显示回调 (render):

void render() {

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // draw the scene
    // [...]

    glutSwapBuffers();

    // mark to be redisplayed - causes continuously calls to "render"
    glutPostRedisplay()
}