Search code examples
copenglglfwglad

How do I initialize OpenGL before GLFW?


I'm currently developing an OpenGL graphics engine with a focus on versatility. I aim for it to display frames in a window and also enable saving images to disk without displaying a window. To achieve this, I decided to initialize OpenGL before GLFW (OpenGL Framework). In the past, I initialized OpenGL after creating the window using the gladLoadGLLoader() function. However, due to the need to use the gladLoadGL() function now, I encounter a SIGSEV error when implementing it in C.

  ASSERT(!gladLoadGL(), "Failed to load OpenGL!\n");
  glViewport(0, 0, 256, 256);

  struct window wd;
  /*
   * this is the struct:
   *
   * struct window {
   *   int width, height;
   *   const char *title;
   *   GLFWwindow *id;
   * };
   * */


  ASSERT(!glfwInit(), "Failed to initialize GLFW!\n");

  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 4);
  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

#ifdef __APPLE__
  glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE);
#endif

  wd.id = glfwCreateWindow(256, 256, title, NULL, NULL);
  ASSERT(wd.id == NULL, "Failed to create window!\n");
  glfwMakeContextCurrent(wd.id);

The following code throws a SIGSEV. But when i initialize GLAD after GLFW with gladLoadGLLoader() it just works fine.


Solution

  • GLFW doesn't support creating headless contexts, so the easiest workaround is to simply create a hidden window. In short, include the following window hint:

    glfwWindowHint(GLFW_WINDOW_VISIBLE, GLFW_FALSE);
    

    Then when/if you actually want to show the window, call glfwShowWindow():

    glfwShowWindow(window);
    

    This of course isn't a true headless context, but again, GLFW doesn't support those, so this is the workaround you can do. Otherwise you need to use another library that supports proper off-screen rendering.