views:

756

answers:

1

I'm a newbie to OpenGL programming. How and at what stage is a valid OpenGL context created in my code? I'm getting errors on even simple OpenGL code.

+2  A: 

From the posts on comp.graphics.api.opengl, it seems like most newbies burn their hands on their first OpenGL program. In most cases, the error is caused due to OpenGL functions being called even before a valid OpenGL context is created. OpenGL is a state machine. Only after the machine has been started and humming in the ready state, can it be put to work.

Here is some simple code to create a valid OpenGL context:

#include <stdlib.h>
#include <GL/glut.h>

// Window attributes
static const unsigned int WIN_POS_X = 30;
static const unsigned int WIN_POS_Y = WIN_POS_X;
static const unsigned int WIN_WIDTH = 512;
static const unsigned int WIN_HEIGHT = WIN_WIDTH;

void glInit(int, char **);

int main(int argc, char * argv[])
{
    // Initialize OpenGL
    glInit(argc, argv);

    // A valid OpenGL context has been created.
    // You can call OpenGL functions from here on.

    glutMainLoop();

    return 0;
}

void glInit(int argc, char ** argv)
{
    // Initialize GLUT
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE);
    glutInitWindowPosition(WIN_POS_X, WIN_POS_Y);
    glutInitWindowSize(WIN_WIDTH, WIN_HEIGHT);
    glutCreateWindow("Hello OpenGL!");

    return;
}

Note:

  • The call of interest here is glutCreateWindow(). It not only creates a window, but also creates an OpenGL context.
  • The window created with glutCreateWindow() is not visible until glutMainLoop() is called.
Ashwin