之前实现的那个Reflection没有把光照加进去,使得不是很逼真,与真实的景象有出入。只要我们把光源也想象
为一个物体,在镜子中也会有镜像,也会使virtual object产生光照效果。这里我采用的是聚光灯,对其的属性设置如下:
GLfloat LightAmb[] = {0.5f, 0.5f, 0.5f, 1.0f}; // Ambient Light
GLfloat LightDif[] = {3.0f, 3.0f, 1.0f, 1.0f}; // Diffuse Light
GLfloat LightSpecular[] = {1.0, 1.0, 1.0, 1.0};
GLfloat spot_dir[] = {0.0, 0.0, 1.0};
GLfloat LightPos[] = {0.0f, 0.0f, 0.0f, 1.0f}; // Light Position
glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, 1);
glLightfv(GL_LIGHT0, GL_AMBIENT, LightAmb); // Set The Ambient Lighting For Light0
glLightfv(GL_LIGHT0, GL_DIFFUSE, LightDif); // Set The Diffuse Lighting For Light0
glLightfv(GL_LIGHT0, GL_SPECULAR, LightSpecular);
glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, spot_dir);
glLightf(GL_LIGHT0, GL_SPOT_EXPONENT, 3.0);
glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 180.0);
glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 0.5);
glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 1.0);
glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, 1.5);
注意,这只是在Init()函数中初始化聚光灯。其中有两个函数涉及到了光源的位置和方向,在此均没有设置。
因为他们与当时的模型视图矩阵相关,存储在人眼坐标系中。
//在当前模型视图矩阵下渲染实际的聚光灯
glDisable(GL_LIGHTING);
glColor3f(1.f, 1.f, 0.f);
glPushMatrix();
glMultMatrixd(light->worldMatrix());
glLightfv(GL_LIGHT0, GL_POSITION, pos);
glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, spot_dir);
gluSphere(p, 0.02, 12, 12);
glPopMatrix();
glEnable(GL_LIGHTING);
//渲染镜像聚光灯(virtual object)
glPushMatrix();
glMultMatrixd(reflector->matrix());
glScalef(1.f, 1.f, -1.f);
glDisable(GL_LIGHTING);
glColor3f(1.f, 1.f, 0.f);
glPushMatrix();
glMultMatrixd(light->matrix());
glLightfv(GL_LIGHT0, GL_POSITION, pos);
glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, spot_dir);
gluSphere(p, 0.02, 12, 12);
glPopMatrix();
glEnable(GL_LIGHTING);
glCullFace(GL_FRONT);
glMultMatrixd(virtualObject->matrix());
DrawObject();
glCullFace(GL_BACK);
glPopMatrix();
得到的效果图如下:(红色原点为光源位置)
这是聚光灯角度为90的效果图,可以看见实际的光照效果和镜面的明暗效果是一致的。下图为聚光角度180
的效果图: