Skip to main content
GameDev.net gamedev.net
🔒 Locked

z-coordinate to Depth Buffer

Started by cHimura Apr 17, 2019 at 4:15 AM 5 replies 1.9k views
Original Post
cHimura
cHimura

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.


MJP
MJP

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.

Gnollrunner
Gnollrunner

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;
}


cHimura
cHimura

Thanks for your answers!

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??


MJP
MJP

Yes, that's correct.

cHimura
cHimura

Thank you!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.