Computing distance from the eye

In the preceding code, we used the absolute value of the z coordinate as the distance from the camera. This may cause the fog to look a bit unrealistic in certain situations. To compute a more precise distance, we could replace the line:

float dist = abs( Position.z ); 

With the following:

float dist = length( Position.xyz ); 

Of course, the latter version requires a square root, and therefore would be a bit slower in practice.

Get OpenGL 4 Shading Language Cookbook - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.