I'm trying to implement a perspective projection using open-GL But when I apply gluPerspective(0,0.5,0.5,5) method, the polygon is not shown in a perspective view and shown in orthogonal view instead here is the output Anyone can help my code:
#include<GL/glut.h>
float angle = 2;
void myinit(void)
{
glClearColor(1.0, 1.0, 1.0, 0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 5);
//glFrustum(-0.5, 2.4, -0.5, 0.5, -0.5, 0.5);
//glFrustum(-5.0, 5.0, -5.0, 5.0, 5, 100);
gluPerspective(0,0.5,0.5,5);
}
void polygon(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0, 0.0, 1.0);
//glLineWidth(2);
//glRotatef(angle, 0.0, 0.0, 1.0);
glBegin(GL_POLYGON);
glVertex3f(0.25, 0.25, 0.0);
glVertex3f(0.75, 0.25, 0.0);
glVertex3f(0.75, 0.75, 0.0);
glVertex3f(0.25, 0.75, 0.0);
//glVertex3f(0, 0.5, 0.0);
glEnd();
glFlush();
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition(50, 100);
glutInitWindowSize(1000, 1000);
glutCreateWindow("Open Gl 2D Geometric Transformation");
myinit();
glutDisplayFunc(polygon);
glutMainLoop();
return 0;
}
the first argument to to gluPerspective
is wrong:
gluPerspective(0,0.5,0.5,5);
The first argument to gluPerspective
is the vertical field of view angle in degrees. The value has to be greater than 0.0 and less than 180. 0.0 is an invalid argument and causes undefined behavior.
Probably the instruction doesn't set the matrix at all.
Anyway, if you set a correct angle, then the geometry will be clipped. The perspective projection matrix defines a Viewing frustum. All the geometry which is not in between the near and fare plane is clipped. In your case the near plane is 0.5 and the far plane 5.0.
Set a view matrix and translate the geometry in between the near and far plane, by shifting the geometry along the negative z axis. For instance (0, 0, -2.5).
The 2nd argument of gluPerspective
is the aspect ration. Since the size of the window is 1000x1000, the aspect ratio has to be 1.0:
void myinit(void)
{
glClearColor(1.0, 1.0, 1.0, 0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
GLdouble fov = 90.0; // 90 degrees
GLdouble aspect = 1.0;
GLdouble near_dist = 0.5;
GLdouble far_dist = 5.0;
gluPerspective(fov, aspect, near_dist, far_dist);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0f, 0.0f, -2.5f); // near_dist < 2.5 < far_dist
}