MULTIMEDIA

# DirectX 10 Game Programming : Shaders and Effects - Pixel Shaders, Lighting (part 3) - Applying the Light

11/21/2013 7:48:40 PM
##### #### 2.3 Applying the Light A shader that uses the lighting functions described in the previous section is shown next. This shader contains a default ambient light and a single directional light. `#include "lightfuncs.fxh"// constant buffer of external variablescbuffer Variables{ matrix Projection; matrix World; float TimeStep;};// hardcoded example camera positionfloat3 camPos = float3(0.0f, 9.0, -256.0f);// lighting valuesfloat3 DirectLightColor = float3(1.0f,1.0f,1.0f);float3 DirectLightVector = float3(0.0f,0.602f,0.70f);float3 AmbientLightColor = float3(1.0f, 1.0f, 1.0f);// PS_INPUT - input variables to the pixel shader// This struct is created and filled in by the// vertex shaderstruct PS_INPUT{ float4 Pos : SV_POSITION; float4 Color : COLOR0; float3 Normal : TEXCOORD0; float3 ViewVector : TEXCOORD1;};////////////////////////////////////////////////// Vertex Shader - Main Function///////////////////////////////////////////////PS_INPUT VS(float4 Pos : POSITION, float4 Color : COLOR, float3 Normal : NORMAL){ PS_INPUT psInput; // save off the position float4 newPosition = Pos; // generate a new height value based on the time newPosition.y = sin((newPosition.x * TimeStep) + (newPosition.z / 3.0f)) *5.0f; // Pass through both the position and the color psInput.Pos = mul(newPosition, Projection); // pass the color and normal along to the pixel shader psInput.Color = Color; psInput.Normal = Normal; // Calculate the view vector psInput.ViewVector = normalize(camPos - psInput.Pos); return psInput;}///////////////////////////////////////////////// Pixel Shader///////////////////////////////////////////////float4 PS(PS_INPUT psInput) : SV_Target{ float3 normal = -normalize(psInput.Normal); // calculate the color using ambient lighting float3 vAmbient = CalculateAmbient(psInput.Color, AmbientLightColor); // calculate the diffuse lighting vfloat3 vDiffuse = CalculateDiffuse(psInput.Color, DirectLightColor, normal, DirectLightVector); // calculate specular float fSpecular = CalculateSpecular(psInput.ViewVector, DirectLightVector, normal); // determine the output color using phong shading float4 outColor; outColor.rgb = LightingCombine(vAmbient, vDiffuse, fSpecular); outColor.a = 1.0f; return outColor;}// Define the techniquetechnique10 Render{ pass P0 { SetVertexShader( CompileShader( vs_4_0, VS() ) ); SetGeometryShader( NULL ); SetPixelShader( CompileShader( ps_4_0, PS() ) ); }} ` The result is shown in Figure 2 and demonstrates lighting on a per-vertex level. Figure 2. Terrain with lighting applied.
 Other

 video

 Video tutorials