5
\$\begingroup\$

I want to get the depth of vertex in 0 to 1 range(like it done in the shader) and I do it like this

    D3DXVec3TransformCoord(&vertex, &vertex, &wvp);

depth = vertex.z;

It works(sometimes wrong) but when I write This

    if (depth > 1.0f || depth < 0.0f)return false;

Sometimes it returns false. How can I get correct depth for vertex in 0 to 1 range??

I want to compare two vertexes and select the nearest

EDIT

    wvp = worldmatrix*viewmatrix*projectionmatrix;

It works wrong when I zoom in

\$\endgroup\$
  • \$\begingroup\$ Is there anything behind the camera? \$\endgroup\$ – Bálint Feb 9 '16 at 12:29
  • \$\begingroup\$ No but .....if(depth > 1.0f) also returns false \$\endgroup\$ – harut9 Feb 9 '16 at 12:35
  • \$\begingroup\$ Wait, what did you set the near clipping plane? \$\endgroup\$ – Bálint Feb 9 '16 at 12:36
  • 2
    \$\begingroup\$ @Bálint The convention in D3DX is v*M. Do you have anything to back up your arbitrary swap of convention? \$\endgroup\$ – Lars Viklund Feb 9 '16 at 13:33
  • 3
    \$\begingroup\$ Possible duplicate of When is the Z coordinate normalized in GLSL? \$\endgroup\$ – Tim Feb 9 '16 at 14:12
0
\$\begingroup\$

Matrix multiplication is not commutative. You need to do projection * view * model

\$\endgroup\$
  • \$\begingroup\$ No it also dont works \$\endgroup\$ – harut9 Feb 9 '16 at 13:06
  • \$\begingroup\$ Ok, try out something: before multiplying the vertex with the mvp matrix, multiply it with the mv matrix, and orint out the z value. \$\endgroup\$ – Bálint Feb 9 '16 at 13:07
  • \$\begingroup\$ I have already done like that \$\endgroup\$ – harut9 Feb 9 '16 at 13:25
0
\$\begingroup\$

You are missing the normalization step, which requires a W component.

Hence, you should be calling D3DXVec4Transform and not D3DXVec3TransformCoord.

You need to feed this your vertex, with the last component (W) set to a 1.0 value.

The output vertex will have W set in the last component, and you need to divide by that:

v_in[3] = 1.0;

D3DXVec4Transform
(
    &v_out,
    &v_in,
    &wvp
);

v_out[0] = v_out[0] / v_out[3];
v_out[1] = v_out[1] / v_out[3];
v_out[2] = v_out[2] / v_out[3];

Now you can use v_out[2] as the depth value, but beware: it ranges from -1 to 1, and not from 0 to 1 as you assumed.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.