Sign in to follow this  

Calculating Depth Value

Recommended Posts

Hi I have a simple question.

How can i calculate the Depth value of a fragment, having the vertex position, the projection matrix and the modelview matrix?

thanks in advance

Share this post

Link to post
Share on other sites
Transform the model space vertex (Pmodel) by the modelviewprojection matrix, gives you the position in clip space (Pclip).

P[sub]clip[/sub] = proj*view*model*P[sub]model[/sub];

Clip space is divided by the W coordinate to get normalized device coordinates, which has xyz values from -1 (near plane) to 1 (far plane)

P[sub]ndc[/sub] = P[sub]clip[/sub] / P[sub]clip[/sub].w;

Then scale this depth value from [-1,1] to [0,1].

Depth = (P[sub]ndc[/sub].z * 0.5) + 0.5;

Share this post

Link to post
Share on other sites

First of all, you will need to apply the matrices to get your point into eye space, and then into projection space.
Assuming [b]v[/b] as the vertex position in world space, [b]P[/b] as the projection matrix and [b]M[/b] as the modelview matrix:
[b]p[/b] = [b]P[/b] ([b]M[/b] [b]v[/b])
where [b]p[/b] is the vertex in clip space. This uses multiplication of matrices and vectors, as defined by linear algebra. You could multiply the matrices first, so that you only need to apply one matrix for the next computation. For a single point, however, this method is faster.

The next step is normalization of the point. This means you need to divide the x, y and z components by the w component. Since you only want the depth, I will only show the z here.
z = [b]p[/b].z / [b]p[/b].w

The last step you need is the conversion to window coordinates. This transforms the coordinates from a range of [-1, 1] to [0, 1].
depth = 0.5 * z + 0.5

And you're done. :)


Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this