1. 新建一个OpenGL 空effect;

2. 添加相关变量

右击Effect节点选择Add Variable->float->float / float3 添加镜面光强度、灯光位置和相机位置参数:

float3 vec3LightPosition = {-100.0,100.0,100.0};

float3 vec3EyePosition = {0,0,100.0};

右击Effect节点选择AddTexture->Add 2DTexture 添加base和bump两张纹理图片:

base

RenderMonkey 练习 第五天 【OpenGL NormalMapping】-LMLPHP

4. 在pass0中添加纹理对象 AddTextureObject 将base和normal图片添加进去,重新命名为baseMap和normalMap

5. 修改vertex shader :

uniform vec3 vec3LightPosition;
uniform vec3 vec3EyePosition;

varying vec2 texcoord;
varying vec3 lightDirection;
varying vec3 viewDirection;

void main(void)
{
   gl_Position = ftransform();
   
   texcoord = gl_MultiTexCoord0.xy;
   vec4 fvObjectPosition = gl_ModelViewMatrix * gl_Vertex;
   
   viewDirection = normalize(vec3EyePosition - fvObjectPosition.xyz);
   lightDirection = normalize(vec3LightPosition - fvObjectPosition.xyz);   
}

6.修改pixel shader:

varying vec2 texcoord;
varying vec3 lightDirection;
varying vec3 viewDirection;

uniform sampler2D normalMap;
uniform sampler2D baseMap;
void main(void)
{
   vec4 NormalMap = texture2D(normalMap,texcoord);
   
   // convert to range -1.0 to 1.0
   vec3 normal = NormalMap.xyz * 2.0 - 1.0;
   
   vec3 N = normalize(normal.xyz);
   vec3 L = normalize(lightDirection.xyz);
   float fNDotL = dot(N,L);
   
   vec3 fvReflection = normalize( 2 * normal * fNDotL - lightDirection);
   float fRDotV = max(dot(fvReflection, viewDirection),0.0);
   
   vec4 fvBaseColor = texture2D(baseMap,texcoord);
   
   float fSpecularPower = 25.0;
   
   vec4 fvTotalAmbient = vec4(0.3,0.3,0.3,1.0) * fvBaseColor;
   vec4 fvTotalDiffuse = vec4(0.8,0.8,0.8,1.0) * max(fNDotL,0.0)* fvBaseColor;
   vec4 fvTotalSpecular = vec4(0.6,0.6,0.6,1.0) * pow(fRDotV, fSpecularPower);    
       
   gl_FragColor = fvTotalAmbient + fvTotalDiffuse + fvTotalSpecular;
}

7. 效果图

RenderMonkey 练习 第五天 【OpenGL NormalMapping】-LMLPHP

05-11 20:48