效果图:
代码:
1 #define GLUT_DISABLE_ATEXIT_HACK
2 #include "gl/glut.h"
3
4
5 void OnDisplay(void);
6 void OnReShape(int,int);
7 void SetupLights();
8
9 void main(int argc,char* argv[])
10 {
11 glutInit(&argc,argv);
12 glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
13 glutInitWindowSize(600,480);
14 glutCreateWindow("OpenGL平移变换");
15
16 glutReshapeFunc(OnReShape);
17 glutDisplayFunc(OnDisplay);
18
19 SetupLights();
20
21 glutMainLoop();
22 }
23
24 void OnDisplay(void)
25 {
26 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
27
28 glEnable(GL_DEPTH_TEST);
29
30 glMatrixMode(GL_MODELVIEW);
31 glLoadIdentity();
32
33 glColor3f(1.0f,0.0f,0.0f);
34 glutSolidSphere(10.0f,20,20);
35
36 glTranslatef(0.0f,50.0f,0.0f);
37 glColor3f(0.0f,1.0f,0.0f);
38 glutSolidSphere(10.0f,20,20);
39
40 glLoadIdentity();
41
42 glTranslatef(50.0f,0.0f,0.0f);
43 glColor3f(0.0f,0.0f,1.0f);
44 glutSolidSphere(10.0f,20,20);
45
46 glutSwapBuffers();
47
48 }
49
50 void OnReShape(int w,int h)
51 {
52 GLfloat aspect =(GLfloat)w/(GLfloat)h;
53 GLfloat nRange=100.0f;
54
55 glViewport(0,0,w,h);
56
57 glMatrixMode(GL_PROJECTION); //将当前矩阵指定为投影模式
58 glLoadIdentity();
59
60 //设置三维投影区
61
62 if (w<=h)
63 {
64 glOrtho(-nRange,nRange,-nRange*aspect,nRange*aspect,-nRange,nRange);
65 }
66 else
67 {
68 glOrtho(-nRange,nRange,-nRange/aspect,nRange/aspect,-nRange,nRange);
69 }
70
71 }
72
73 void SetupLights()
74 {
75 GLfloat ambientLight[]={0.2f,0.2f,0.2f,1.0f};//环境光
76 GLfloat diffuseLight[]={0.9f,0.9f,0.9f,1.0f};//漫反射
77 GLfloat specularLight[]={1.0f,1.0f,1.0f,1.0f};//镜面光
78 GLfloat lightPos[]={50.0f,80.0f,60.0f,1.0f};//光源位置
79
80 glEnable(GL_LIGHTING); //启用光照
81 glLightfv(GL_LIGHT0,GL_AMBIENT,ambientLight);//设置环境光源
82 glLightfv(GL_LIGHT0,GL_DIFFUSE,diffuseLight);//设置漫反射光源
83 glLightfv(GL_LIGHT0,GL_SPECULAR,specularLight);//设置镜面光源
84 glLightfv(GL_LIGHT0,GL_POSITION,lightPos);//设置灯光位置
85 glEnable(GL_LIGHT0); //打开第一个灯光
86
87 glEnable(GL_COLOR_MATERIAL); //启用材质的颜色跟踪
88 glColorMaterial(GL_FRONT,GL_AMBIENT_AND_DIFFUSE); //指定材料着色的面
89 glMaterialfv(GL_FRONT,GL_SPECULAR,specularLight); //指定材料对镜面光的反应
90 glMateriali(GL_FRONT,GL_SHININESS,100); //指定反射系数
91
92
93 }