Problem calculating screen point for a point in a 3D world with view matrix and projection matrix

I am trying to calculate the 2D screen point of a 3D world position. For this I use the multiplication ViewMatrix * ProjectionMatrix. But I am not getting good results and I think I am messing up my calculations or my ViewMatrix itself is wrong (I think the latter).

This is a snapshot of how my ViewMatrix looks like when the camera is looking downwards (at my feet):

 0.362,    0.932,    0.000,    0.000
-2.241,    0.094,   -0.966,    0.000
-0.900,    0.350,    0.259,    0.000
8.100,  -16.860,    4.598,    1.000


I calculate my left handed perspective ProjectionMatrix manually using 4/3 aspect ratio 60 FOV and using 0.1 and 1000 for my near and far Z. This is the ending projection matrix:

-0.117,    0.000,    0.000,    0.000
0.000,   -0.156,    0.000,    0.000
0.000,    0.000,    1.000,    1.000
0.000,    0.000,   -0.100,    0.000


I multiply the previous 2 matrices with ViewMatrix * ProjectionMatrix and use that as my ViewProjectionMatrix.

Now I need to calculate the clipping space coordinates of the 3D point. I do this as follows:

XMFLOAT4 clipCoords;
clipCoords.x = pos.x * viewMatrix._11 + pos.y * viewMatrix._21 + pos.z * viewMatrix._31 + viewMatrix._41;
clipCoords.y = pos.x * viewMatrix._12 + pos.y * viewMatrix._22 + pos.z * viewMatrix._32 + viewMatrix._42;
clipCoords.z = pos.x * viewMatrix._13 + pos.y * viewMatrix._23 + pos.z * viewMatrix._33 + viewMatrix._43;
clipCoords.w = pos.x * viewMatrix._14 + pos.y * viewMatrix._24 + pos.z * viewMatrix._34 + viewMatrix._44;


Now I convert this to normalised device coordinates:

XMFLOAT3 NDC;
NDC.x = clipCoords.x / clipCoords.w;
NDC.y = clipCoords.y / clipCoords.w;
NDC.z = clipCoords.z / clipCoords.w;


As a final step I convert it to the 2D point on a screen for a given size:

XMFLOAT2 screen;
screen.x = (windowWidth / 2 * NDC.x) + (NDC.x + windowWidth / 2);
screen.y = -(windowHeight / 2 * NDC.y) + (NDC.y + windowHeight / 2);


Can you spot the problem with the above calculation?

Steffen

1 Answer

Matrix multiplication is non-cumulative, aka A * B doesn't always equal to B * A. The order of the multiplications should be

projection * view * model * vector


Your projection matrix is also messed up, the values should be this way:

I would say where the values in your matrix are, but I have zero idea.

• Thanks for your answer, I am using the following function to calculate the projection matrix: msdn.microsoft.com/en-us/library/windows/desktop/…. I think the issue lies in that the view matrix doesn't have any values at the last two columns of the first row. – Steffen Brem Jan 25 '17 at 22:32
• @Steffen that shouldn't be a problem, did you try what I said? – Bálint Jan 26 '17 at 9:17
• @Steffen an image about the problem would also be nice – Bálint Jan 26 '17 at 9:18