Skip to content
systemcoding.dev
GPU

Handle Window Resizes and Framebuffer Size Changes in GLFW

Keep the OpenGL viewport and projection correct when a GLFW 3.4 window resizes, using the framebuffer size callback and the window size versus pixel size rules.

7 min read
Summarize in AI
Flat illustration of a GPU die of compute units with one thread block lit, with the C, Vulkan and Khronos Group logos.

You draw a perfect circle, drag the window wider, and the circle turns into an egg. Or you open the same program on a laptop with a high-resolution display and the picture fills only the lower-left quarter of the window. Both bugs have the same root: a window has two sizes, and OpenGL cares about the one most beginners do not read. This post explains the two sizes in GLFW 3.4, shows the callback that keeps the viewport right, and then fixes the aspect ratio of a projection so shapes stay round when the window changes shape. It builds on the GLFW window program and uses C with OpenGL 3.3 core and glad.

Two sizes, two units

GLFW reports a window's size in screen coordinates. These are the units the operating system uses to place and size windows. On a plain display one screen coordinate is one pixel. On a display with scaling, such as a Retina Mac or a Windows machine set to 150 percent, one screen coordinate covers several pixels, so a window that is 800 by 600 screen coordinates holds a framebuffer of 1600 by 1200 pixels at a scale of 2.

OpenGL draws into the framebuffer, which is measured in pixels. glViewport takes pixels, and glClear fills the framebuffer, so everything GL-related needs the pixel size. The functions are:

QuantityFunctionUnit
Window sizeglfwGetWindowSizeScreen coordinates
Framebuffer sizeglfwGetFramebufferSizePixels
Content scaleglfwGetWindowContentScaleRatio of dpi to a baseline

Rule of thumb: ask for the window size when you lay out the window itself, and ask for the framebuffer size when you talk to OpenGL.

The failing program

Here is a program that uses the window size for the viewport. On a display with a scale of 2 it reproduces the quarter-window bug, because the viewport is half the framebuffer on each axis:

broken_viewport.cc
int w, h;
glfwGetWindowSize(window, &w, &h);   // screen coordinates: wrong unit for GL
glViewport(0, 0, w, h);

On such a display with an 800 by 600 window, the framebuffer is 1600 by 1200, and the viewport rectangle covers only 800 by 600 pixels starting at the lower-left corner. Everything you draw shrinks into that corner.

The fix: query pixels and listen for changes

Replace the call with the framebuffer query, and register a callback so the viewport follows every resize:

resize.cc
#include <glad/gl.h>
#include <GLFW/glfw3.h>
#include <stdio.h>

static void on_framebuffer_size(GLFWwindow* window, int width, int height) {
    glViewport(0, 0, width, height);
    printf("framebuffer: %d x %d\n", width, height);
}

int main(void) {
    if (!glfwInit()) return 1;
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    GLFWwindow* window = glfwCreateWindow(800, 600, "Resize", NULL, NULL);
    if (!window) { glfwTerminate(); return 1; }
    glfwMakeContextCurrent(window);
    gladLoadGL(glfwGetProcAddress);
    glfwSwapInterval(1);

    glfwSetFramebufferSizeCallback(window, on_framebuffer_size);

    int fw, fh;
    glfwGetFramebufferSize(window, &fw, &fh);
    on_framebuffer_size(window, fw, fh);

    while (!glfwWindowShouldClose(window)) {
        glClearColor(0.1f, 0.1f, 0.15f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwTerminate();
    return 0;
}

Two details matter. The callback is only called when the size changes, and no event announces the initial size, so the program calls the same function once at startup with the size it queried. Skipping that call is the usual reason a window looks wrong until the first drag. And the callback is registered after the context exists, because it calls glViewport. A resize event can arrive from glfwPollEvents at any iteration, so the viewport changes between frames, never in the middle of one.

On a standard display, dragging the window from 800 by 600 to 1000 by 700 prints one line for each size change the system reports, ending in the final size. On a scaled display the numbers are larger:

Text
framebuffer: 800 x 600
framebuffer: 900 x 650
framebuffer: 1000 x 700

The intermediate lines depend on how the window system delivers drag events, and the first and last lines are the reliable ones. If the display scale is 2 and the window is 800 by 600, the first line is framebuffer: 1600 x 1200.

Fix the aspect ratio

A correct viewport still leaves one problem. Suppose you draw a square with coordinates from -0.5 to 0.5 in normalized device coordinates, which always span the full viewport from -1 to 1 on both axes. When the window is wider than tall, the square stretches into a rectangle. The fix is a projection matrix that scales the horizontal axis by the inverse of the aspect ratio, so one unit has the same physical length in both directions.

The aspect ratio is width divided by height of the framebuffer. In an orthographic projection with the vertical range fixed at -1 to 1, the horizontal range becomes minus aspect to plus aspect. Write the matrix by hand to keep the example free of libraries:

ortho.cc
// Column-major 4x4 orthographic matrix, left/right/bottom/top at z = 0.
static void ortho(float* m, float l, float r, float b, float t) {
    for (int i = 0; i < 16; ++i) m[i] = 0.0f;
    m[0]  =  2.0f / (r - l);
    m[5]  =  2.0f / (t - b);
    m[10] = -1.0f;
    m[12] = -(r + l) / (r - l);
    m[13] = -(t + b) / (t - b);
    m[15] =  1.0f;
}

static float g_projection[16];

static void update_projection(int width, int height) {
    float aspect = (float)width / (float)height;
    ortho(g_projection, -aspect, aspect, -1.0f, 1.0f);
}

Call update_projection from the framebuffer callback, next to glViewport, and upload g_projection to a uniform mat4 named uProjection each frame. For a 1600 by 800 framebuffer the aspect is 2.0, so the horizontal range is -2 to 2 and the vertical range is -1 to 1. A 1 by 1 unit square then occupies 1/4 of the width and 1/2 of the height in normalized coordinates, which is 400 by 400 pixels, so it stays square.

The vertex shader applies the matrix:

shape.vertglsl
#version 330 core
layout(location = 0) in vec2 aPos;
uniform mat4 uProjection;

void main() {
    gl_Position = uProjection * vec4(aPos, 0.0, 1.0);
}

Without the matrix a window of 1600 by 800 pixels maps the square's x range of -0.5 to 0.5 to 800 pixels across and its y range to 400 pixels tall, so it draws as a 2 to 1 rectangle. With the matrix the same square is 400 by 400 pixels.

Guard against a zero size

When the user minimizes a window, GLFW reports a framebuffer of 0 by 0 on some platforms. Dividing by zero in the aspect calculation yields infinity or NaN, which poisons the projection matrix, and the scene is invisible after the window is restored until the next resize. Skip the update when either dimension is zero:

guard.cc
static void on_framebuffer_size(GLFWwindow* window, int width, int height) {
    if (width == 0 || height == 0) return;
    glViewport(0, 0, width, height);
    update_projection(width, height);
}

A related trick: while the window is minimized, glfwGetWindowAttrib(window, GLFW_ICONIFIED) is true, and you can skip rendering entirely, or call glfwWaitEvents to sleep until the window returns.

The window size callback is a different callback

GLFW also provides glfwSetWindowSizeCallback, which reports the size in screen coordinates. Use it for layout that is independent of pixels, such as remembering the window's size in a settings file so the next run reopens at the same size in the same units. Do not use it for glViewport. The two callbacks both fire on a resize, and on a display with scaling they report different numbers. A third callback, glfwSetWindowContentScaleCallback, fires when the window moves to a monitor with a different scale, for example when the user drags it from a laptop panel to an external display. The framebuffer size callback fires in that case as well when the pixel size changes, so the viewport stays right without extra code, though text and UI sizes should use the new scale.

Resizing and the frozen loop

On Windows and macOS the operating system runs its own modal loop while the user drags a window edge, so glfwPollEvents does not return until the drag ends, and the application stops rendering during it. The picture stays at the old size until release, which looks like a stretched or stale frame. GLFW provides glfwSetWindowRefreshCallback for this: the callback fires when the contents need redrawing, including during a drag on platforms where the modal loop would otherwise block.

refresh.cc
static void on_refresh(GLFWwindow* window) {
    glClearColor(0.1f, 0.1f, 0.15f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    // draw the scene here
    glfwSwapBuffers(window);
}

// glfwSetWindowRefreshCallback(window, on_refresh);

Move the drawing code into one function that both the loop and the refresh callback call, so the drag shows a live picture. The behavior is platform specific, and the GLFW documentation notes that on some platforms the callback is the only way to get redraws during a resize.

Checklist

Use the framebuffer size for glViewport and for any pixel-based calculation. Register the framebuffer callback and also call its body once at startup. Rebuild the projection from the framebuffer's aspect ratio. Ignore zero sizes. Use the window size only for window layout. If you also draw UI, scale it by the content scale so text keeps its physical size.

These functions are documented in the GLFW window guide, including the sections on framebuffer size and window content scale.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.