copenglglfwopenglcontext

How to render to multiple windows using a single OpenGL context?


I created two windows using GLFW. The first window has an OpenGL context and the second one doesn't. What I want to do is render the same scene to both windows using a single OpenGL context. Something like this.

glBindVertexArray(vaoId);

// ... tell OpenGL to draw on first window

glClear(GL_COLOR_BUFFER_BIT);
glDrawArrays(...);

// ... swap first window buffers

// ... tell OpenGL to draw on second window

glClear(GL_COLOR_BUFFER_BIT);
glDrawArrays(...);

// ... swap second window buffers

glBindVertexArray(0);

The problem is I don't know how to tell OpenGL to draw on a specific window. And I also don't know how to swap buffers for a specific window. If it's necessary, I can use Win32 API.


Solution

  • As far as I'm aware, GLFW does not directly support that in it's API. It generally considers a Window and a GL context as a unit. However, with the native APIs, you can do what you want. For windows 32 in partiuclar, have a look at wglMakeCurrent(). In GLFW, you can get the required context and window handles via GLFW's native access API. Note that you will only get a HWND that way, you will have to manually use GetDC() to get the device context of the window.

    Be aware that switching contexts will imply flushing the GL command queue, which can have negative effects on the performance. See GL_KHR_context_flush_control for more details.