Trytio
Trytio

Reputation: 108

OpenGL: prevent make fog in every shaders programs

I currently have a fog made in one of my vertex shader with this code:

float Distance = length(PositionToCam.xyz);
Visibility = exp(-pow((Distance*Density), Gradient));
Visibility = clamp(Visibility, 0.0, 1.0);

Then, I use the Visibility in my fragment shader like this:

FragColor = mix(vec4(SkyColor, 1.0), FragColor, Visibility);

The fog work correctly, but the problem is that it only work with this particular shader, while I want the fog to apply on everything.

How can I have a kind of global shader to handle the fog on every element of the scene?

Upvotes: 0

Views: 656

Answers (2)

florent teppe
florent teppe

Reputation: 596

The answer from derhass can work, but it can be a bit of a pain to incorporate the calculation in every shader.

One other way to do it is to have a post processing pass where you use the depth buffer to calculate the distance to the camera, and then apply the same alogorithm to all the fragments in the pixel shader of your post processing pass.

You need to render your previous scene colors and depth to a texture to be able to do post processing.

Upvotes: 1

derhass
derhass

Reputation: 45342

How can I have a kind of global shader to handle the fog on every element of the scene?

You need to incorporate your fog calculations into each and every program object you intend to use for rendering your objects.

This does not necessarily mean that you have to copy the source code manually. However, you will need some basic strategy for managing your shaders.

  1. You can link multiple shader objects together for a single stage. That means you can make a separate vertex shader which just contains a function like fogCalculations() and just call that from all of your other vertex shaders, (and of course link the objects). Same for the Fragment Shader part.

  2. You can also programatically combine the strings for various stages, and basically inject your fog code where needed.

Also note that your fog calculations are just wrong. Your visibility is not a linear property, but it will be linearly interpolate (well, linear w.r.t. the space before the perspective divide, the actual calculations will be non-linear in screen-space, but that does not matter here). If you have a big triangle roughly extending in the viewing direction, and a small object which is basically at the center of the big triangles, it will receive a different visibility value than the triangle center. Furthermore, when your triangles get clipped, the visibility will also be off for the newly formed vertices at the intersection points.

Upvotes: 0

Related Questions