In the previous project, we implemented vertex illumination calculation in Vs, and then passed the vertex color to PS. In this chapter, we try fragment illumination (or PS illumination). In vs, we directly transmit the normal direction and position of vertices in the world coordinate system to PS.
// The normal direction of vertices in the world coordinate system.
Float3 n = MUL (input. Normal, (float3x3) worldmatrix );
Output. worldnormal = N;
// World coordinate system vertex position
Worldposition = MUL (input. Position, worldmatrix );
Output. worldposition = worldposition;
What is the difference between vs light and ps light?
In fact, it is very simple. For vs lighting, we calculate the color of each vertex in Vs, and then the fixed GPU pipeline will implement bilinear difference based on the vertex color value before ps, calculate the color of each pixel. For PS illumination, the position and direction of each vertex are different, so that each pixel has its own corresponding position and direction, the computing of illumination is completed in PS.
Therefore, the use of PS light, its color will be more soft, not as visual contrast.
Our PS functions are as follows:
Float4 lightpixelshader (pixelinputtype input): sv_target
{
Float3 P = input. worldposition. XYZ;
Float3 n = normalize (input. worldnormal );
// Self-emission color
Float4 emissive = ke;
// Computing environment light
Float4 ambient = Ka * globalambient;
// Calculate the diffuse reflection light
// Lightdirection is a pure parallel light.
// The Position of the light source minus the vertex position, which is a point light source that does not consider Attenuation
Float3 L = normalize (lightposition. XYZ-P );
Float diffuselight = max (dot (n, l), 0 );
Float4 diffuse = KD * lightcolor * diffuselight;
// Calculate the highlight
Float3 v = normalize (cameraposition. XYZ-P );
Float3 H = normalize (L + V );
Float specularlight = POW (max (dot (n, h), 0), shininess );
If (diffuselight <= 0)
Specularlight = 0;
Float4 specular = KS * lightcolor * specularlight;
Float4 finalcolor = emissive + ambient + DIFFUSE + specular;
Return finalcolor;
}
In addition, in lightshaderclass, we also need to change the previously set vs material illumination constant buffer to set the PS illumination constant buffering.
// Set the constant buffer of the illumination material.
Devicecontext-> pssetconstantbuffers (buffernumber, 1, & m_lightmaterialbuffer );
Other code is almost unchanged. After the program is executed, the effect is as follows:
Complete code can be found:
Project File mytutoriald3d11_19
Download Code:
Http://files.cnblogs.com/mikewolf2002/myTutorialD3D11.zip