c++openglfreeglutobsolete

What the OpenGL coordinates are? Ignore OpenGL window size


I just started trying to folow simple "draw cube" openGl tutorial. After final victory over getting OpenGL to work, I still have very veird results. My problem is that the objects tend to resize themselves to match the window size. Instead, I'd like the window size determine the rendering area - the larger the window is, the more you may see.

Here are some screenshots of the resizing:
Normal size
Resized
Images kept as links intentionally!

This auto-resizing behavior brings a question what the coordinates used in OpenGL are.


Solution

  • First thing to keep in mind: OpenGL is a drawing API. It doesn't maintain a scene or something like that.

    So what OpenGL does is, it maps geometry input coordinates in the form of vertex attributes to screen space. In the old fixed function there's a special vertex attribute called "vertex position" or just short "vertex" (the actual vertex is more than just position).

    The position is transformed to what's usually called "screen" space (but depending on where the viewport is placed, it might as well be called "window" or "viewport) space) in a three step process:

    1. Transformation into view/eye space: This is done by multiplying the vertex position with the modelview matrix.

    Certain further calculations, like illumination calculation are done in view space.

    2. Transformation to clip space: The view space position is transformed into clip space. This is usually called the projection and aptly the matrix describing this transformation is called the projection matrix

    In clip space some special things happen, summarized as clipping, you don't have to worry about yet.

    3. In the final step transformed the clipped geometry into normalized device coordinates (NDC). NDC space is practically a 1:1 mapping toward the viewport, i.e. the limits of the NDC volume directly correspond to the offset and dimension of the viewport set with glViewport.

    You can't change the way the 3rd step happens, and the 1st step is reserved for transforming stuff into view space. So any adjustments must happen in the 2nd step.

    So here's what you have to do: The projection limits must be directly proportional to the viewport extents. Like this for example

    glViewport(0, 0, width, height);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-width/2, width/2, -height/2, height/2, -1, 1);
    

    Oh, and just on a general note: You should always set the viewport and projection setup in the drawing function, too. If you see a tutorial that puts those statements in a window resize handler, just disregard it and just do it in the drawing code anyway. On the long term this really simplifies things.