c++openglgeometryorthographic

Drawing circle with GL_POLYGON, radius out of scale


I am trying to draw a circle using GL_POLYGON and the code I tried is working but the radius of the circle seems to be out of scale with the window size and I am not understanding why.

Here is the code:

void display()
{
    glClear(GL_COLOR_BUFFER_BIT);

    if(start == OFF)
    {
        //Set Drawing Color - Will Remain this color until otherwise specified
        glColor3f(0.2, 0.3, 0.5);  //Some type of blue   

        //Draw Circle
        glBegin(GL_POLYGON);
        for(double i = 0; i < 2 * PI; i += PI / 24) 
            glVertex3f((cos(i) * radius) + gX,(sin(i) * radius) + gY, 0.0);
        glEnd();

        //Draw Circle
        center_x = gX;
        center_y = gY;
    }     

    glutSwapBuffers();
}

and the init function:

void init (void) 
{
  /* selecionar cor de fundo (preto) */
  glClearColor (0.0, 0.0, 0.0, 0.0);

  /* inicializar sistema de viz. */
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
}

I am setting the window size as 600 and the radius as 1 and a quarter of the circle takes us the whole window. I am guessing I have to do some kind of transformation with the radius, I just don't know how.


Solution

  • The projection matrix describes the mapping from 3D points of a scene, to 2D points of the viewport. It transforms from eye space to the clip space, and the coordinates in the clip space are transformed to the normalized device coordinates (NDC) by dividing with the w component of the clip coordinates. The NDC are in range (-1,-1,-1) to (1,1,1).

    At Orthographic Projection the coordinates in the eye space are linearly mapped to normalized device coordinates.

    Orthographic Projection

    The orthographic projection can be set up by glOrtho. You are setting up a viewport with a bottom left corner at (0, 0), a top right corner at (1, 1) and depth range from -1 to 1:

    glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
    

    If you want to set up a projection that allows you to draw in window size scales, then you have to do it like this:

    int wndWidth  = 800; // for example a window with the size 800*600  
    int wndHeight = 600; 
    
    glOrtho( 0.0, (float)wndWidth, 0.0, (float)wndHeight, -1.0, 1.0 );
    

    If you want to have the origin of (0, 0) in the center of the window, then you have to do it like this:

    float w = (float)wndWidth/2.0f;
    float h = (float)wndHeight/2.0f;
    
    glOrtho( -w, w, -h, h, -1.0, 1.0 );
    

    See further: