Aspect ratio for 2D quads when rotating

Hello!

I created a rectangle with four 2D-vertices using glVertex2D. If i put a glRotatef-command before glBegin(GL_QUADS), the rectangle gets rotated but does not keep its aspect ratio (only if my window is a square…).
Settings the perspective the following way…

glViewport (0, 0, Width, Height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0, Width / Height, 0.0, 100.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

… does not help. The rectangle is not rendered any longer. Is there a solution to my problem?

Benjamin

For one thing, make sure you move the camera back.
Right now the camera is at 0,0,0 (unless you do some glTranslate after the modelview loadidentity), and your vertices are at z=0.

Also, (but that is only a potential render quality issue), you should set zNear to something bigger than 0.

try gluPerspective(45.0, float(Width) / float(Height), 0.0, 100.0);

both forums should be unified

Huh? zNear == 0.0 is illegal. It must be > 0.0 in perspective mode.

Can you tell me how to setup a camera?
Here is a simple program to demonstrate my problem more detailed:

int main(int argc, char *argv[]) {
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
glutInitWindowSize(600,250);
glutInitWindowPosition(100,200);
glutCreateWindow(“Glut/OpenGL Program”);
init();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}

void init(void) {
glClearColor(0.0f ,0.0f ,0.0f ,0.0f);
glColor3f(0.0f,0.0f,1.0f);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
}

void display(void) {
glClear(GL_COLOR_BUFFER_BIT);
glRotatef(45.0f, 0.0f, 0.0f, 1.0f);
glBegin(GL_QUADS);
glVertex2f( -0.5, -0.2);
glVertex2f( -0.5,0.2);
glVertex2f(0.5, 0.2);
glVertex2f(0.5,-0.2);
glEnd();
glutSwapBuffers();
}

It draws a rectangle in the middle of the screen. If rotated by 45 degree, it gets distorted. What do i have to do to rotate it “correctly”?

Thanks for you help.

Benjamin

That’s simple.
The OpenGL defaults for modelview and projection matrices is the identity. An identity in the projection matrix is an orthographic projection of the unit cube with radius 1.0 around the origin. (Check the math in the OpenGL Programming Guide appendix F).
When your window is square, the OpenGL projection maps to square pixels.
What you need is to setup the glOrtho to have the aspect ratio of the window.

Looks like this in GLUT

void reshape(int w, int h)
{
    GLdouble aspectRatio = 1.0;

    glViewport(0, 0, (GLsizei) w, (GLsizei) h);
    
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    if (w > 0 && h > 0)
    {
       aspectRatio = (GLdouble) w / (GLdouble) h; 
    }

    glOrtho(-aspectRatio, aspectRatio, -1.0, 1.0, -1.0, 1.0);
    
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

int main(int argc, char** argv)
{
...
    glutReshapeFunc(reshape);
...
}

Great! Thank you! That saved me a lot of hours…

Benjamin