# Drawing cube in SharpDX, wrong perspective

I want to draw a cube. This is what i currently have:

As you can see, the perspective is VERY wrong. The the size in the z-direction is too small and the difference between the front and back size is wrong.

My code:

worldprojMatrix = Matrix.Identity;
worldprojMatrix *= Matrix.Translation(0, 0, 10);
//float ratio = ScreenWidth/ScreenHeight;
worldprojMatrix *= Matrix.PerspectiveFovLH(1f, ratio, 1f, 100f);
//worldprojMatrix *= Matrix.RotationY(1.3f);

worldprojMatrix.Transpose();

//update the matrix with a constant buffer
DeviceContext.UpdateSubresource(ref worldprojMatrix, worldprojBuffer);


Vertex Shader:

struct VOut
{
float4 position : SV_POSITION;
float4 color    : COLOR;
};

cbuffer meshBuffer  :  register(b1)
{
float4x4 worldprojMatrix;
}

VOut VShader(float4 position : POSITION, float4 color : COLOR)
{
VOut output;

output.position = mul(position, worldprojMatrix);
output.color = color;

return output;
}


I tried an ortho perspective, but there is the same problem: the z dimension is too small.

How can i fix that?

• How about you try rotating -before- multiplying by the perspective projection matrix? Matrix multiplication is not commutative, you know? Commented May 20, 2014 at 10:15
• @PandaPajama it worked :) edited my question, there is still something wrong Commented May 20, 2014 at 11:17
• Your new problem looks like inverted normals: you're looking at the inside of the cube. (@AlexTennant's answer explains it in more technical detail)
– Xan
Commented May 20, 2014 at 14:22
• @Xan i didn't noticed that, i was sure, the blue is the front... it finally works. Commented May 20, 2014 at 14:36

## 2 Answers

I don't know what vertex data you're using to draw that, but supposing it is a cube, I wouldn't say that the perspective is VERY wrong, or even wrong at all, on the left picture.

Based on your commented-out code, your ultimate view-projection matrix is getting calculated like this:

identity * translation * projection * rotation


Your drawing is getting distorted because you're rotating after applying the perspective matrix. Your view-projection matrix should be more like:

identity * rotation * translation * projection


Remember that matrix multiplication is not commutative.

OpenGL uses Right Handed coordinate system. But you are using Matrix.PerspectiveFovLH which creates a Left Handed perspective matrix. That is probably what causes the error.

• You did notice he's using SharpDX, as in "DirectX", right? Besides, mixing the handedness will just flip the X coordinate, and would not create the problem he's experiencing. Commented May 20, 2014 at 10:22
• I didn't notice that, indeed :/. Commented May 20, 2014 at 14:00