• 10
• 9
• 13
• 10
• 18

# Help with Per Pixel Fog in HLSL

This topic is 4211 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

How do I add Per Pixel fog in a HLSL ? I searched though all samples in FX composer without luck.

##### Share on other sites
hmm i think it's not in the samples because it's a quite simple effect and is quite straight forward:

if you have a fogstart float ,a fogend float and the fogcolor you can just do sth like this("color" is the usual color that this pixel would have without the fog and "depth" is the pixel's depth)

endColor=lerp(color,fogcolor,(depth-fogstart)/(fogend-fogstart)); //endColor is the color that should be written to the backbuffer

i think i got everything right.

Edit: ok i think i should explain the solution:

Simple Fog means that you want to interpolate between the color that the pixel would have without fog("color") and the fogcolor(that's the color when a pixel is 100% fogged:"fogcolor"). The HLSL command for interpolating is lerp(x1,x2,factor). The first to parameters are the values you want to interpolate("color,"fogcolor"), and the factor is a value between 0 and 1(when factor=0, color will be returned;factor=1 fogcolor will be returned;everything inbetween:a mix of both colors will be returned).

The factor depends on the pixel's depth and on fogstart and fogend. (depth-fogstart) tells how much this pixel is in the fog-volume but we have to scale this value because we want a value between 0 and 1 as a factor. So we divide the value by the length of the fog volume(along the depth), which is the difference between fogstart and fogend.

regards,
m4gnus

[Edited by - m4gnus on September 8, 2006 5:27:21 AM]

##### Share on other sites
Hmm, I do like this in my Vertex Shader

[Source]half4 Po = half4(IN.Position.xyz,1.0);half3 Pw = mul(Po, World).xyz;float dist = distance(ViewInv[3].xyz,Pw);OUT.fogLerpParam = saturate((dist-gFogStart) / gFogRange);[/Source]

[Source]half4 result = lerp((SurfColor*map*(Kd*diffContrib+AmbiColor)) + specContrib + reflColor,float4(1,1,1,1),IN.fogLerpParam);[/Source]

where float(1,1,1,1) is fogColor.

But this is per vertex fog huu ???

Sorry for being a newbee but, where do I get "depth" from your sample ?

Thanks for all help!

##### Share on other sites
depth is distance to the eye position. its linear fog calculation

##### Share on other sites
pass the depth as a texture coordinate from vertex-shader to pixel shader and do fog calculation on it in pixel shader