XNA's ViewPort.Project() equivalent in DirectX 11

    General discussion

  •      Hi Everybody!

         While migrating my XNA games to DirectX 11, I stumbled into a problem trying to draw a texture on the screen in the location where a 3D model is supposed to be standing. In XNA, the answer is simple:


         I spent days trying to find the equivalent in DirectX 11, and although there is plenty of documentation about viewports available within the DeviceContext class, I couldn't find an equivalent method. Then, it hit me: The answer is back to the basics, back to math. The solution is rather simple, and even elegant:

    XMVECTOR vecPixel = XMVectorSet(0, 0, 0, 0);
    XMFLOAT3 vecThis = XMFLOAT3(0, 0, 0);
    vecPixel = vecAPositionIn3DSpace;
    vecPixel = XMVector4Transform(vecPixel, mtxWorldRotation);
    vecPixel = XMVector4Transform(vecPixel, mtxView);
    vecPixel = XMVector4Transform(vecPixel, mtxProjection);
    XMStoreFloat3(&vecThis, vecPixel);
    if (0 < vecThis.z)// *** <- No Div0!!! *** //
    	lngDisplayPosX = (vecThis.x / vecThis.z) * (lngDisplayWidth / 2);
    	lngDisplayPosY = -(vecThis.y / vecThis.z) * (lngDisplayHeight / 2);

         It works like a charm. Nothing like home-made code ;)

         I hope it helps!!!

         Tarh Ik

    PS: This posting has been posted "AS IS"

    Tarh ik

    Friday, November 21, 2014 7:38 PM

All replies

  • See XMVector3Project which is a DirectXMath function for doing just this.

    Note that if you are going to project more than a single point, you should combine mtxWorldRotation * mtxView * mtxProjection and then do the vector4*matrix multiply once.

    Note: If you are porting XNA Game Studio code from C# to C++, you might want to look at SimpleMath in the DirectX Tool Kit.

    Saturday, November 22, 2014 1:02 AM
  •      Hi Chuck,

         Cool, thanks!!! I never thought about looking for the answer in the vector functions... although now I understand why it's there.

         The idea about multiplying the three matrixes first and apply the result to all projections is a great one too, specially since I need to project about 600 instances per frame. Definitelly, that will boost performance.

         Thanks again!!!

         Tarh Ik.

    Tarh ik

    Saturday, November 22, 2014 4:41 AM