Search code examples
lwjglglfw

LWJGL Game loop pauses whenever the GLFW window head is clicked


I have a very simple game loop.

public void gameLoop() {        
    long now;
    long updateTime;
    long wait;
    
    final int TARGET_FPS = 60;
    final long OPTIMAL_TIME = 1000000000 / TARGET_FPS;
            
    while (!window.shouldClose()) {
        now = System.nanoTime();
        
        update();
        render();
        frame++;
                    
        updateTime = System.nanoTime() - now;
        wait = (OPTIMAL_TIME - updateTime) / 1000000;

        try {
            Thread.sleep(wait);
        } catch (Exception e) {
            
        }

    }
    
    glfwTerminate();
    
}

Whenever I click the head of the window (the bar where the close and minimize buttons are), the loop for some reason pauses. The sounds in game continue to play (I use AL10), so this causes music and sounds to get out of sync with the game. I want to pause the window whenever this happens.

I but looking through the GLFW callbacks, there doesn't seem to be one which fixes this. The focus callback only works if I click outside of the window, and the windowPos callback only works whenever the window is moved, NOT when you simply click and hold the window head.

Is there a way to fix this problem.


Solution

  • This is actually expected behaviour on some platforms like Windows, where effectively glfwPollEvents will block inside of a Win32 API call for as long as you hold down the mouse button and/or potentially drag/move the window around.

    In order to fix this, you should make your game loop independent of the window event processing loop, by using separate threads.

    The main thread must be the one that is doing the window event processing (glfwPollEvents or glfwWaitEvents) to stay consistent with the requirements of some other platforms like macOS where this is a requirement, while another thread can do the game update and rendering.