I just started today with OpenGL and follow a tutorial for setting up an OpenGL project in Visual Studio 2010. But when I run the code, I get a window opening very fast, blinking and disappearing. Is this normal?
#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;
}
}
You missed to enter the GLUT event processing loop by glutMainLoop
:
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;
}
This function never returns, process the events and executes callbacks like the display callback (render
). This function process the main application loop.
If this function is not called, then the program terminates immediately after the window was created.
If you want that your application continuously redraws the scene, then you've to call glutPostRedisplay()
in render
. This marks the current window as needing to be redisplayed, and causes that the display callback (render
) is called again in the event processing loop:
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()
}