1
votes

I made a simple OpenGL program that draws a 2D texture to the screen. When you resize the window, it doesn't adjust properly, so to fix that, I would just run the projection matrix code again:

if (windowSizeChange)
{
    std::cout << "Window resized." << std::endl;
    std::cout << windowWidth << " " << windowHeight << std::endl;
    windowSizeChange = false;
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0.0, windowWidth, windowHeight, 0.0, -1.0, 1.0);
    glMatrixMode(GL_MODELVIEW);
}

However, running this code warps the image. To my understanding, to make it so I can draw 2D-like on the screen, my texture is drawn using an orthographic projection matrix which means there is a plane that is "parallel" with the window port or something like that which I draw on. When I try to re-make it to accommodate for the new window size, it doesn't adjust properly. What's going wrong with this code?

2

2 Answers

1
votes

When the size of the window and the framebuffer has been changed, then you have to adjust the viewport rectangle.
The viewport rectangle can be set by glViewport and specifies how the normalized device coordinates are mapped to window coordinates. It defines the area of the framebuffer, where the normalized device coordinates from (-1, -1) to (1, 1) are mapped to.

glViewport(0, 0, windowWidth, windowHeight);

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, windowWidth, windowHeight, 0.0, -1.0, 1.0);
2
votes

In your code you're changing the ortho matrix, but you also need to change the glViewport:

if (windowSizeChange)
{
    glViewport(0, 0, windowWidth, windowHeight); // <-- Add this
    std::cout << "Window resized." << std::endl;
    std::cout << windowWidth << " " << windowHeight << std::endl;
    windowSizeChange = false;
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0.0, windowWidth, windowHeight, 0.0, -1.0, 1.0);
    glMatrixMode(GL_MODELVIEW);
}

Orthographic matrices are, like you said, just a matrix that in this case is parallel to the screen. When we call glOrtho, it changes the size of the matrix we're working with, and glViewport tells openGL the size of the viewport (in this case, our window) we're working with. You'll generally want glOrtho and glViewport to be the same dimensions