user972014
user972014

Reputation: 3856

OpenGL and glfw - resize window after creating it in python

in python3 I use glfw and PyOpenGL. When I create a hidden window, render into it, read its' pixels - I get well rendered images.

If I try to resize the window - it seems that OpenGL is not aware of the new rendering size and keeps rendering large images, into a small window, which makes the read back images cropped

Here is an example:

width = height = 500

# Create the hidden window we are going to render into
glfw.window_hint(glfw.VISIBLE, False)
glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 2)
glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, OpenGL.GL.GL_TRUE)
glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
window = glfw.create_window(width, height, "hidden window", None, None)
assert window
glfw.make_context_current(window)

# THIS CODE BREAKS IT:
# width = height = 300
# glfw.set_window_size(window, 300, 300)

# render into the window:
# ...code to choose the VBO...
glDrawArrays(GL_TRIANGLES, ...)


# Read back the created pixels:
data = glReadPixels(0, 0, width, height, OpenGL.GL.GL_RGB, OpenGL.GL.GL_UNSIGNED_BYTE)
rendered_image =  np.frombuffer(data, dtype=np.uint8).reshape(rendered_image_height, rendered_image_width, 3)[::-1]

Another solution to change the rendering size after already creating the window and rendering to it several times (and obviously clearing it) might also be helpful

Upvotes: 1

Views: 2633

Answers (1)

Rabbid76
Rabbid76

Reputation: 211278

When the size of the window has changed, the you have to reset the viewport rectangle by glViewport

Implement the resize callback and set it by glfw.set_window_size_callback:

vp_size_changed = False
def resize_cb(window, w, h):
    global vp_size_changed
    vp_size_changed = True
glfw.set_window_size_callback(window, resize_cb)

Get the new framebuffer size by glfw.get_framebuffer_size and set the viewport rectangle by glViewport:

global vp_size_changed

while not glfw.window_should_close(window):
    glfw.poll_events()

    if vp_size_changed:
        vp_size_changed = False
        w, h = glfw.get_framebuffer_size(window)
        glViewport(0, 0, w, h)
        print("new viewport size:", w, h)

Upvotes: 1

Related Questions