Search code examples
openglcallbackglut

OpenGL / GLUT change callbacks inside glutMainLoop()


normally a GLUT application will be structured in the following pattern:

  • some initialization stuff
  • glutMainLoop()

I only have access to a drawing callback function inside the main Loop. I will not be able to change the initialization part. Is there any way to change a callback function like glutKeyboardFunc() within this Loop? Or is there another way to capture keyboard inputs without access to the initialization part?

Thanks


Solution

  • Yes, you can call glut…Func anytime. For example you could have to keyboard handler functions and switch between them (contextual keys)

    void keyfunc_edit(unsigned char key, int x, int y);
    void keyfunc_select(unsigned char key, int x, int y);
    
    void keyfunc_edit(unsigned char key, int x, int y)
    {
        switch( key ){
        case 'x':
        case 'X':
            /* switch to select mode */
            glutKeyboardFunc(keyfunc_select);
            break;
    }
    
    void keyfunc_select(unsigned char key, int x, int y)
    {
        switch( key ){
        case 'e':
        case 'E':
            /* switch to edit mode */
            glutKeyboardFunc(keyfunc_edit);
            break;
    }
    

    This works for any GLUT callback, so you can switch callbacks for display, idle and so on, at any time. For example say you want to show a load screen, then it makes perfect sense to switch the display callback to a loading screen display function, and once loading is complete change to a scene render function.