5.5 编程实例
5.5.1 二维实例——红蓝三角形
#include <GL/glut.h>
typedef GLfloat point2d[2];
void triangle( point2d a, point2d b, point2d c)
{
glBegin(GL_TRIANGLES);
glVertex2fv(a);
glVertex2fv(b);
glVertex2fv(c);
glEnd();
}
void display(void)
{
point2d v[3] = {{-1.0, -0.58}, {1.0, -0.58}, {0.0, 1.15}};
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0,0.0,1.0);
glLoadIdentity();
glViewport(0, 0, 300, 400);
triangle(v[0], v[1], v[2]);
glColor3f(1.0,0.0,0.0);
glViewport(300, 0, 300, 400);
glRotatef(90.0, 0.0, 0.0, 1.0);
triangle(v[0], v[1], v[2]);
glFlush();
}
void init()
{
glMatrixMode(GL_PROJECTION);
gluOrtho2D(-2.0, 2.0, -2.0, 2.0);
glMatrixMode(GL_MODELVIEW);
glClearColor(1.0, 1.0, 1.0,1.0);
}
void main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(600, 400);
glutCreateWindow("Triangle");
glutDisplayFunc(display);
init();
glutMainLoop();
}
5.5.2 三维实例——立方体透视投影
#include <GL/glut.h>
GLint winWidth = 600, winHeight = 600;
GLfloat x0 = 0.0, y0= 0.0, z0 =5.0;
GLfloat xref = 0.0, yref =0.0, zref = 0.0;
GLfloat Vx = 0.0, Vy = 1.0, Vz = 0.0;
GLfloat xwMin = -1.0, ywMin = -1.0, xwMax = 1.0, ywMax = 1.0;
GLfloat dnear = 1.5, dfar = 20.0;
void init (void)
{
glClearColor(1.0,1.0,1.0,0.0);
gluLookAt (x0, y0, z0, xref, yref, zref, Vx, Vy, Vz);
glMatrixMode (GL_MODELVIEW);
glScalef (2.0, 2.0, 2.0);
glRotatef(45.0, 0.0, 1.0, 1.0);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
glFrustum (xwMin, xwMax, ywMin, ywMax, dnear, dfar);
}
void display (void)
{
glClear (GL_COLOR_BUFFER_BIT);
glColor3f (0.0, 1.0, 0.0);
glutSolidCube (1.0);
glColor3f (0.0, 0.0, 0.0);
glLineWidth (2.0);
glutWireCube (1.0);
glFlush ();
}
void reshape (GLint newWidth, GLint newHeight)
{
glViewport (0, 0, newWidth, newHeight);
winWidth = newWidth;
winHeight = newHeight;
}
void main (int argc, char** argv)
{
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition (100, 100);
glutInitWindowSize (winWidth, winHeight);
glutCreateWindow ("单位立方体的透视投影");
init ();
glutDisplayFunc (display);
glutReshapeFunc (reshape);
glutMainLoop ();
}