1 #include "gl/glut.h" 2 3 void Initialization() 4 { 5 glClearColor(0.0f,0.0f,0.0f,1.0f); 6 7 GLfloat lightSpecular[]={1.0,1.0,1.0,1.0}; 8 GLfloat lightPosition[]={0.5,0.5,4.0,0.0}; 9 10 glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); //指定混合函数 11 glShadeModel(GL_SMOOTH); 12 13 glMaterialfv(GL_FRONT,GL_SPECULAR,lightSpecular); 14 glMaterialf(GL_FRONT,GL_SHININESS,100.0); 15 glLightfv(GL_LIGHT0,GL_POSITION,lightPosition); 16 17 glEnable(GL_BLEND);//启用混合状态 18 glEnable(GL_LIGHTING);//启用光照 19 glEnable(GL_LIGHT0);//打开光源0 20 glEnable(GL_DEPTH_TEST);//启用深度检测 21 glEnable(GL_COLOR_MATERIAL);//材质跟踪当前绘图色 22 } 23 24 void OnDisplay(void) 25 { 26 27 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 28 29 glMatrixMode(GL_MODELVIEW); 30 glLoadIdentity(); 31 32 glPushMatrix(); 33 glTranslatef(0.0f,0.0f,-3.0f); 34 glColor4f(1.0f,0.0f,0.0f,1.0f); 35 glutSolidTorus(1.0f,2.0f,30.0f,30.0f);//绘制圆环 36 glPopMatrix(); 37 38 39 glPushMatrix(); 40 glTranslatef(1.0f,1.0f,3.0f); 41 glColor4f(0.0f,1.0f,0.0f,0.4f); 42 glutSolidSphere(2.0f,30.0f,30.0f);//绘制球体 43 glPopMatrix(); 44 45 glutSwapBuffers(); 46 } 47 48 void OnReShape(int w,int h) 49 { 50 glViewport(0,0,w,h); 51 52 glMatrixMode(GL_PROJECTION); //将当前矩阵指定为投影模式 53 glLoadIdentity(); 54 55 if (h!=0) 56 { 57 GLfloat aspect =GLfloat(w)/GLfloat(h); 58 59 if(w<h) 60 glOrtho(-6.0f,6.0f,-6.0f*aspect,6.0f*aspect,-6.0f,6.0f);//三维正交投影 61 else 62 glOrtho(-6.0f/aspect,6.0f/aspect,-6.0f,6.0f,-6.0f,6.0f); 63 64 } 65 glMatrixMode(GL_MODELVIEW); 66 67 } 68 69 70 void main(int argc,char* argv[]) 71 { 72 glutInit(&argc,argv); 73 glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); 74 glutInitWindowSize(600,480); 75 glutCreateWindow("OpenGL透明"); 76 77 glutReshapeFunc(OnReShape); 78 glutDisplayFunc(OnDisplay); 79 80 Initialization(); 81 82 glutMainLoop(); 83 }