How to make a simple fog effect in OpenGL ?

Ok, I’ve just implemented the fog effect while studying OpenGL, so I’m going to show you guys how to do it.

In order to test the effect, you must have object in 3d space. Here mine is a 2×2 texture
(I create a simple 2×2 texture and then mapping it to the 4-vertex square)

texture

My vertex shader file:

// Vertex shader
attribute vec3 a_position;
attribute vec2 a_uv;

uniform mat4 u_projection;
uniform mat4 u_view;
uniform mat4 u_model;

varying vec3 v_position;
varying vec2 v_uv;

void main()
{
vec4 positionTmp = vec4 ( a_position, 1.0 );

v_position = ( u_model * positionTmp ).xyz;
v_uv = a_uv;

gl_Position = u_projection * u_view * u_model * positionTmp;
}

My fragment shader file:

// Fragment shader
precision mediump float;

uniform sampler2D u_texture;
uniform vec4 u_fogColor;
uniform vec4 u_eyePos;
uniform float u_fogMaxDist;
uniform float u_fogMinDist;

varying vec3 v_position;
varying vec2 v_uv;

float eyeDist;

float computeLinearFactor()
{
float factor;

factor = ( u_fogMaxDist - eyeDist ) /
( u_fogMaxDist - u_fogMinDist );
factor = clamp ( factor, 0.0, 1.0 );

return factor;
}
void main()
{
eyeDist = distance ( v_position, u_eyePos );

float factor = computeLinearFactor();
vec4 fogColor = fogFactor * u_fogColor;
vec4 baseColor = texture2D ( u_texture, v_uv );

gl_FragColor = baseColor * fogFactor +
fogColor * ( 1.0 - fogFactor );

Result ( my u_fogColor is red):
texture_fog

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s