To simulate fog in hlsl you simply need to make an interpolation between your final obtained color and some color that you want your fog to have.
First we need the depth witch is basically the z component of the final position in view space that you calculate for your pixel shader :
VSPerPixelFogOutput output = (VSPerPixelFogOutput)0;
float4 worldPosition = mul(input.Position, World);
float4 viewPosition = mul(worldPosition, View);
output.Position = mul(viewPosition, Projection);
float4 viewPosition = mul(worldPosition, View);
output.Position = mul(viewPosition, Projection);
output.Depth = output.Position.z;
The interpolation factor can be calculated as :
float l = saturate((Depth - FogStart) / (FogEnd - FogStart));
where:
FogStart is the distance where you want your fog to start from your camera.
FogEnd is the distance where you want your fog to end from your camera.
Finally in the pixel shader all you have to do is interpolate between your fog color and your color obtained in the shader based on that factor :
return float4(lerp(OriginalColor,FogColor, l), 1);
And this is how you can simply and efficiently emulate the fog that was in the fixed pipeline.
Here is an example of this executed in XNA 4.0 with per vertex and per pixel fog, it's on Microsoft SkyDrive(if you have an account and you are not logged in you might not see it):
FogDemo
FogDemo

Very helpful and straight to the point. Thanks.
ReplyDelete