OpenGL透视

时间:2012-07-19 13:39:06

标签: opengl 3d projection

我正在尝试使用透视投影来描绘立方体,但我得到的只是一个正方形的角落。正方形的面设置在原点并向正方向扩展。使用glOrtho我可以设置坐标系,但是我无法使用glPerspective做同样的事情。

#include <gl/glut.h>

void mesh(void) {
float v[8][3] = { /* Vertices for 8 corners of a cube. */
{0.0, 0.0, 0.0}, {100.0, 0.0, 0.0}, {100.0, 100.0, 0.0}, {0.0, 100.0, 0.0},
{0.0, 0.0, -100.0}, {100.0, 0.0, -100.0}, {100.0, 100.0, -100.0}, {0.0, 100.0, -100.0} };
float n[6][3] = { /* Normals for the 6 faces of a cube. */
{0.0, 0.0, 1.0}, {1.0, 0.0, 0.0}, {0.0, 1.0, 0.0},
{-1.0, 0.0, 0.0}, {0.0, -1.0, 0.0}, {0.0, 0.0, -1.0} };
int f[6][4] = { /* Indexes of the vertices in v that make the 6 faces of a cube. */
{0, 1, 2, 3}, {1, 5, 6, 2}, {3, 2, 6, 7}, 
{0, 4, 7, 3}, {0, 1, 5, 4}, {4, 5, 6, 7} };



for (int j = 0; j < 6; j++) {
    glBegin(GL_QUADS);
    glNormal3fv(&n[j][0]);
    glVertex3fv(&v[f[j][0]][0]);
    glVertex3fv(&v[f[j][1]][0]);
    glVertex3fv(&v[f[j][2]][0]);
    glVertex3fv(&v[f[j][3]][0]);
    glEnd();
    glFlush();
}
}

void display(void) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3f(1.0, 0.0, 0.0);
mesh();
}

void main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB |GLUT_DEPTH |GLUT_SINGLE);
glutInitWindowSize(400, 300);
glutInitWindowPosition(200, 200);
glutCreateWindow("Mesh");
glClearColor(0.0, 0.0, 0.0, 1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//glRotatef(15, 0.0, 0.0, 1.0);
//glOrtho(-400.0, 400.0, -300.0, 300.0, 200.0, -200.0);
gluPerspective(120,1,0,600);
glEnable(GL_DEPTH_TEST);
glEnable(GL_NORMALIZE);
glutDisplayFunc(display);
glutMainLoop();
}

1 个答案:

答案 0 :(得分:4)

你说你只看到立方体的角落?然后你的视野太宽了..你正在使用gluPerspective()并提供你的计算是正确的..值有点偏离imo,函数参数是:

void gluPerspective(GLdouble fovy,
                    GLdouble aspect_ratio,
                    GLdouble zNear,
                    GLdouble zFar);

我建议将其更改为

gluPerspective(45.0f,
               width_of_window / height_of_window,    //aspect ratio
               0.1f, 
               500.0f);