Atmospheric fog

Use the depth_texture to create atmospheric fog.

The fog decrease with altitude (like in real world).

Setup: SphereMesh + Custom Shader.

if (raw < 0.0000001) cut the fog closer of farter from camera.
Check if camera z-far can render the sphere.

The terrain here is 200km, the sphere is 400km diameter and camera z-far is 400km.

Shader code
shader_type spatial;
render_mode unshaded, cull_front, depth_test_disabled, blend_mix;

uniform sampler2D DEPTH_TEXTURE : hint_depth_texture;
uniform vec3 fog_color : source_color = vec3(0.7, 0.8, 0.9);
const float fog_density = 0.0001; 
const float altitude_scale = 2000.0;
varying float alt;

void vertex() {
    alt = (MAIN_CAM_INV_VIEW_MATRIX * vec4(0.0, 0.0, 0.0, 1.0)).y;
}

void fragment() {
    float raw = texture(DEPTH_TEXTURE, SCREEN_UV).r;
    if (raw < 0.0000001) {		// If raw depth is 0.0, it's the background/sky (Godot 4 reversed-Z)
        discard;
    }
    vec4 clip_pos = vec4(SCREEN_UV * 2.0 - 1.0, raw, 1.0);
    vec4 view_pos = INV_PROJECTION_MATRIX * clip_pos;
    view_pos /= view_pos.w;
    float dist = -view_pos.z;
    float altitude_factor = 1.0 / (1.0 + max(alt, 0.0) / altitude_scale);
    float alpha = 1.0 - exp(-dist * fog_density * altitude_factor);
    ALPHA = clamp(alpha, 0.0, 1.0);
    ALBEDO = fog_color;
}
Live Preview
Tags
atmospheric, Data/Generation, depth_texture, Fog
The shader code and all code snippets in this post are under CC0 license and can be used freely without the author's permission. Images and videos, and assets depicted in those, do not fall under this license. For more info, see our License terms.

More from spaghetti

Related shaders

Comments 0

No comments yet.