Valid OpenGL context

前端 未结 1 1583
眼角桃花
眼角桃花 2021-01-06 13:58

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

相关标签:
1条回答
  • 2021-01-06 14:35

    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.
    0 讨论(0)
提交回复
热议问题