0
votes

I would like to output in my pixelshader the actual camera distance per pixel. This means, the result should (aside from some slight variations in precision and clamping) not depend upon the near/far clipping planes.

Also, a plane lying exactly on the near plane (and parallel to it) should therefore not output a uniform result, because pixels in the middle of the nearplane are closer to the camera than pixels on the border.

How can I calculate the actual camera distance for each pixel in a pixelshader? (actual shader language doesn't matter)

2

2 Answers

-4
votes

Here's a sample in Cg http://developer.download.nvidia.com/shaderlibrary/packages/DepthColor.cgfx.zip

It's setup for FX Composer, should be trivial to adopt for any other format.

-3
votes

You send the camera position is a uniform. You send the position to the fragment shader in a varying. You use the built-in distance function with those vectors.

It looks like this, but don't bother overcomplicating it with the .w if you don't need it.

Alternatively, multiply the vertex position by the ModelView matrix, and use length() on that.