Search code examples
glfwopengl-3

Why do I get 2 callbacks in GLFW3 - OpenGL


I am using GLFW3 for window handling of OpenGL3.3+. Everything works correctly, however I do not understand why it prints "A pressed" two times whenever I press my A key. In particular I want it to be printed just once for 1 keypress A.

static void My_Key_Callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
    if( key == 'A' )
    {
        std::cout<< "A pressed\n";
        return;
    }
}


int main( int argc, char ** argv )
{
    // --1-- Initialise GLFW
    if( glfwInit() == false )
    {
        std::cerr << "Failed to initialize GLFW3\nQuiting....\n";
        exit(1);
    }


    // --2-- Create Window
    glfwWindowHint(GLFW_SAMPLES, 4); // 4x antialiasing
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // We want OpenGL 3.3
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //We don't want the old OpenGL

    GLFWwindow * window=NULL;
    window = glfwCreateWindow( 400, 400, "hello", NULL, NULL );
    if( window == NULL )
    {
        std::cerr << "Failed to create glfw window\nQuiting....\n";
        glfwTerminate();
        exit(1);
    }

    // --3-- Make current context
    glfwMakeContextCurrent( window );


// 
// .
// . Normal OpenGL code goes here
// .
//

    // set call back
    glfwSetKeyCallback( window, My_Key_Callback);

    // --5-- Main loop
    glfwSetInputMode( window, GLFW_STICKY_KEYS, GL_TRUE );
    glClearColor(0,0,.4,0);



    do
    {


        ////// Some more OpenGL code here 

        glDrawArrays(GL_TRIANGLES, 0, 36); 


        // swap buffers
        glfwSwapBuffers( window );
        glfwPollEvents();
    }
    while( glfwWindowShouldClose(window)==false );



}

Solution

  • There is a single keyboard event callback in GLFW3 which handles GLFW_RELEASE events as well:

    typedef void(* GLFWkeyfun)(GLFWwindow *, int, int, int, int)

    The 4th argument is action: GLFW_PRESS, GLFW_RELEASE or GLFW_REPEAT. You can ignore the key release event, e.g.,

    if (action == GLFW_RELEASE)
        return;
    
    // ... handle PRESS, REPEAT of a key...