# 3D z-coordinate to Depth Buffer

## Recommended Posts

Hi,

What is the formula to convert a z-coordinate to depth buffer value??

The values of the depth buffer goes from 0.0 to 1.0 and I want to convert every value of z-axis to this range.

Thanks.

##### Share on other sites

It depends on your projection matrix! You should look at how your projection matrix is formed, and then follow through the math of the matrix multiplication to get the formula for computing the z and w components after projection. The depth buffer value will then be z / w.

##### Share on other sites

Here is my really old routine from my really old library that I've been too lazy/afraid to replace with something optimized. This generates a projection matrix that you can multiply in at the end of your matrices. I'm sure whatever lib you're using has something similar and better but just so you can get the idea.

template<class T> void TDL3D4x4Matrix<T>::Set(T fFOVAngleY, T fAspectRatio, T fNearZ, T fFarZ)
{
T fFOVHalfY = fFOVAngleY * (T) 0.5;
T fSinFov = (T) sin(fFOVHalfY);
T fCosFov = (T) cos(fFOVHalfY);

T fHeight = fCosFov / fSinFov;
T fWidth = fHeight / fAspectRatio;
T fRange = fFarZ / (fFarZ-fNearZ);

m_a.D[0][0] = fWidth;
m_a.D[0][1] = 0.0f;
m_a.D[0][2] = 0.0f;
m_a.D[0][3] = 0.0f;

m_a.D[1][0] = 0.0f;
m_a.D[1][1] = fHeight;
m_a.D[1][2] = 0.0f;
m_a.D[1][3] = 0.0f;

m_a.D[2][0] = 0.0f;
m_a.D[2][1] = 0.0f;
m_a.D[2][2] = fRange;
m_a.D[2][3] = 1.0f;

m_a.D[3][0] = 0.0f;
m_a.D[3][1] = 0.0f;
m_a.D[3][2] = -fRange * fNearZ;
m_a.D[3][3] = 0.0f;
m_pType = &DL3D_PROJECTION;
}

##### Share on other sites

Then,

If have a vector v and the matrix WVP (WorldViewProjection)

I'm using Left Hand System so v1 = v * WVP;

And the depth buffer value will be v1.z / v1.w

Is it correct??

##### Share on other sites

Yes, that's correct.

Thank you!

## Create an account

Register a new account

• ### Game Developer Survey

We are looking for qualified game developers to participate in a 10-minute online survey. Qualified participants will be offered a \$15 incentive for your time and insights. Click here to start!

• 37
• 16
• 18
• 25