1.源码实现
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
float angle = 0.0;
void init()
{
glEnable(GL_DEPTH_TEST);
glEnable(GL_MULTISAMPLE);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glDepthFunc(GL_LEQUAL);
glClearDepth(1.0f);
GLfloat light_position[] = {1.0, -1.0, -0.5, 0.0};
GLfloat light_ambient[] = {0.2, 0.2, 0.2, 1.0};
GLfloat light_diffuse[] = {0.8, 0.8, 0.8, 1.0};
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
}
void update(int value)
{
angle += 2.0f;
if(angle > 360)
{
angle -= 360;
}
glutPostRedisplay();
glutTimerFunc(32, update, 0);
}
void display()
{
glClearColor(0.0, 0.0, 0.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glRotatef(angle, 0.0f, 1.0f, 0.0f);
glRotatef(angle, 0.0f, 0.0f, 1.0f);
//glTranslatef(0.0f, 0.0f, -0.3f);
glutSolidCube(0.8);
glFlush();
glutSwapBuffers();
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB|GLUT_DOUBLE|GLUT_DEPTH|GLUT_MULTISAMPLE);
glutInitWindowSize(400, 400);
glutCreateWindow("OpenGL Cube with Lighting");
init();
glutDisplayFunc(display);
glutTimerFunc(16, update, 0);
glutMainLoop();
return 0;
}
2.编译源码
$ g++ -o example example.cpp -std=c++11 -lGL -lglut
3.运行结果