Context & stateGL 1.0

glViewport

Sets which rectangle of the window the rendered image is mapped to.

Signature

void glViewport(GLint x, GLint y, GLsizei width, GLsizei height);

How it works

After the vertex shader, positions are in normalized device coordinates (NDC), from -1 to 1 on each axis. The viewport is the final step that turns them into pixel coordinates: -1 becomes x, +1 becomes x + width.

You usually set it once to the full framebuffer size, and again every time the window is resized.

NDC−11−11glViewportwindow(0, 0)(x, y)widthheight
Left: after the vertex shader, everything visible lies in the square from −1 to 1 (normalized device coordinates). Right: glViewport(x, y, width, height) stretches that square onto a rectangle of the window, counted in pixels from the bottom-left corner: x_window = x + (x_ndc + 1) / 2 · width.

Parameters

xGLint

Left edge in pixels, from the LEFT of the window.

yGLint

Bottom edge in pixels, from the BOTTOM of the window (OpenGL's origin is bottom-left).

widthGLsizei

Width in pixels.

heightGLsizei

Height in pixels.

Tips & pitfalls

  • On high-DPI screens the framebuffer is bigger than the window: use glfwGetFramebufferSize, not the window size.

  • When rendering into a framebuffer object of a different size (e.g. a shadow map), set the viewport to that size and restore it afterwards.

Errors

When the call is invalid it does nothing and sets an error, which glGetError returns:

GL_INVALID_VALUE
width or height is negative.

Example

example.cpp
1void framebufferSizeCallback(GLFWwindow*, int w, int h) {
2    glViewport(0, 0, w, h);
3}
4glfwSetFramebufferSizeCallback(window, framebufferSizeCallback);
Official Khronos documentation