今天我们来学习下Direct3D里面的光源和材质.
四大光照类型:
环境光 | Ambient Light | 一个物体没有被光照直接照射,通过每一些物体反射的光线到达这个物体,它也有可能被看到.这种称为环境光 |
漫反射光 | Diffuse Light | 这种类型光沿着特定的方向传播,当达到某一个表面,它会向四周方向均匀反射(重点考虑反射光的空间位置和方向) |
镜面反射光 | Specular Light | 当此类光到达一个表面时,严格地沿着一个方向反射。 |
自发光 | Emissive Light | 自发光就是对象自己发光 |
环境光的开启:
Device->SetRenderState(D3DRS_AMBIENT,D3DCOLOR_XRGB(50,50,36));
镜面反射光开启:
Device->SetRenderState(D3DRS_SPECULARENABLE,true);
三大光源类型:
点光源(Point Light)具有颜色和位置,但是没有方向,它向所有方向发射光都一样,光源不会因为距离而衰减
方向光源(direction Light) 在场景中以相同的方向传播,具有颜色和方向,不受到衰减和范围的影响.
聚光灯源, 在我们生活中有手电筒由一个内圆柱体和外圆柱体组成,光从最中心位置到外围逐渐衰减. Phi和Theta分别是两个圆锥体的里面夹角大小
创建点光源:
D3DLIGHT9 light; ::ZeroMemory(&light,sizeof(light)); light.Type = D3DLIGHT_POINT; //各种光源类型,现在是点光源 light.Ambient = D3DXCOLOR(0.8f,0.8f,0.8f,1.0f); //下面三个参数是环境光,漫反射光,镜面反射光的颜色值 light.Diffuse = D3DXCOLOR(1.0f,1.0f,1.0f,1.0f); light.Specular = D3DXCOLOR(0.3f,0.3f,0.3f,1.0f); light.Position = D3DXVECTOR3(0.0f,200.0f,0.0f); //坐标位置 light.Attenuation0 = 1.0f; //下面三个参数是光随着距离衰减的系数 light.Attenuation1 = 0.0f; light.Attenuation2 = 0.0f; light.Range = 300.0f; //光照的范围,在某些光源中才有效果 Device->SetLight(0,&light); //设置光源 Device->LightEnable(0,true); //开启光源
创建方向光源:
//创建方向光源 D3DLIGHT9 light; ::ZeroMemory(&light,sizeof(light)); light.Type = D3DLIGHT_DIRECTIONAL; //方向光源 light.Ambient = D3DXCOLOR(0.5f,0.5f,0.5f,1.0f); light.Diffuse = D3DXCOLOR(1.0f,1.0f,1.0f,1.0f); light.Specular = D3DXCOLOR(0.3f,0.3f,0.3f,1.0f); light.Direction = D3DXVECTOR3(0.0f,0.0f,1.0f); Device->SetLight(0,&light); Device->LightEnable(0,true);
创建聚光灯:
D3DLIGHT9 light; ::ZeroMemory(&light,sizeof(light)); light.Type = D3DLIGHT_SPOT; light.Position = D3DXVECTOR3(100.0f,100.0f,100.0f); light.Direction = D3DXVECTOR3(-1.0f,-1.0f,-1.0f); light.Ambient = D3DXCOLOR(0.3f,0.3f,0.3f,1.0f); light.Diffuse = D3DXCOLOR(1.0f,1.0f,1.0f,1.0f); light.Specular = D3DXCOLOR(0.3f,0.3f,0.3f,0.3f); light.Attenuation0 = 1.0f; light.Attenuation1 = 0.0f; light.Attenuation2 = 0.0f; light.Range = 300.0f; light.Falloff = 0.1f; light.Phi = D3DX_PI / 3.0f; light.Theta = D3DX_PI / 6.0f; Device->SetLight(0,&light); Device->LightEnable(0,true);
材质:
光照和材质就像两个好基友,物体表面的材质属性决定了它能反射什么颜色的光线,以及能反射多少, 材质是属于某一个物体的,
来学习下如何创建材质
//创建材质: D3DMATERIAL9 mtrl; ::ZeroMemory(&mtrl,sizeof(mtrl)); mtrl.Ambient = D3DXCOLOR(0.5f,0.5f,0.7f,1.0f); //表示物体表面对环境光的反射率,填写一个颜色,ARGB值在0-1之间 mtrl.Diffuse = D3DXCOLOR(0.6f,0.6f,0.6f,1.0f); //对漫反射光的反射率 mtrl.Specular = D3DXCOLOR(0.3f,0.3f,0.3f,0.3f); //对镜面反射光的反射率 mtrl.Emissive = D3DXCOLOR(0.0f,0.0f,0.0f,1.0f); //对自发光颜色的反射率 mtrl.Power = 0.1f; Device->SetMaterial(&mtrl); //设置材质
物体的顶点颜色的亮度总和有一个公式:
颜色总和 = 环境光 + 漫反射光 + 镜面反射光 + 自发光