OpenGL or GLFW renders ok only when moving the window

Viewed 1350

I'm just trying to draw a line between the bottom left corner and the top right corner of the screen. The result is quite annoying since it renders a line that goes from the bottom left corner to the middle point of the screen... However if I move the window position with the mouse, it suddenly changes and renders properly! What is happening and how can I solve this?

I'm running the code on a macOS system and it's being builded using Xcode.

Before moving the window:

Before moving the window

After moving the window:

After moving the window

This is the code:

#include <GLFW/glfw3.h>

#define SCREEN_W 640
#define SCREEN_H 480

int main(int argc, char * argv[]) {

    glfwInit();

    GLFWwindow* window = glfwCreateWindow(SCREEN_W, SCREEN_H, "GLFW Window", NULL, NULL);

    glfwMakeContextCurrent(window);

    float lineVertices[] = {
        0, 0, 0,
        SCREEN_W, SCREEN_H, 0
    };

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glViewport(0.0f, 0.0f, SCREEN_W, SCREEN_H);
    glOrtho(0, SCREEN_W, 0, SCREEN_H, 0, 1);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    while (!glfwWindowShouldClose(window)) {
        glClear(GL_COLOR_BUFFER_BIT);

        glEnableClientState(GL_VERTEX_ARRAY);
        glVertexPointer(3, GL_FLOAT, 0, lineVertices);
        glDrawArrays(GL_LINES, 0, 2);
        glDisableClientState(GL_VERTEX_ARRAY);

        glfwSwapBuffers(window);

        glfwPollEvents();
    }

    glfwDestroyWindow(window);

    glfwTerminate();

    return 0;
}
2 Answers

Probably this is not related to the initial issue of this question since it was published 1.5 years ago but if you face this on Mac OS X Mojave then there is an issue opened on GLFW GitHub: https://github.com/glfw/glfw/issues/1334

You can check temporary workarounds there.

I ran into a similar issue on MacOS (Mojave) while going through the OpenGL Tutorial, so I figured I'd post a fix here (not my solution, see below). You can fix it by moving the window ever so slightly after you swap buffers:

#include <GLFW/glfw3.h>
void fix_render_on_mac(GLFWwindow* window) {
#ifdef __APPLE__
    static bool macMoved = false;
    if(!macMoved) {
        int x, y;
        glfwGetWindowPos(window, &x, &y);
        glfwSetWindowPos(window, ++x, y);
        macMoved = true;
    }
#endif
}

I recommend you slap this snippet in a header file, include it, and call fix_render_on_mac(window) right after you call glfwPollEvents() (or anytime after glfwSwapBuffers(window) to be more precise). You can inline it, but if you're doing the OpenGL tutorials or need to reuse it, then it's obviously ideal to have it in a function for simple reuse.

Credit goes someone named "BrutPitt" on github. You can see the original code here. I've modified it to be a bit more minimal and slapped it in a header file.

HTH.

Related