Click or drag to resize
Ab4d.SharpEngine logo

SceneViewGetWorldToViewportMatrix Method

Gets Matrix4x4 that can be used to convert 3D coordinates to 2D viewport (screen) coordinates. If the method returns true, than the worldToViewportMatrix was set; if false is returned than the matrix cannot be calculated.

Namespace: Ab4d.SharpEngine
Assembly: Ab4d.SharpEngine (in Ab4d.SharpEngine.dll) Version: 2.0.8956+4c7684e186ca1be74e7a284fbe739d9a1b843d3c
Syntax
C#
public bool GetWorldToViewportMatrix(
	out Matrix4x4? worldToViewportMatrix,
	bool forceMatrixRefresh = false
)

Parameters

worldToViewportMatrix  Matrix4x4
reference to Matrix4x4
forceMatrixRefresh  Boolean  (Optional)
if true than the worldToViewportMatrix is always recalculated; if false the recalculation is done only when the main camera properties were changed

Return Value

Boolean
true if worldToViewportMatrix was set; false if the matrix cannot be calculated
Remarks

GetWorldToViewportMatrix gets Matrix4x4 that can be used to convert 3D coordinates to 2D viewport coordinates.

If the method returns true, than the worldToViewportMatrix was set; if false is returned than the matrix cannot be calculated (for example when MatrixCamera is used and the matrix cannot be inverted).

Important:
To calculate the screen coordinates of a 3D position you need multiply the position by the worldToViewportMatrix and then perform a perspective division (divide by W). See the following code:

C#
bool adjustByDpiScale = true;
Vector3 inputPosition3D = new Vector3();

Vector2 screenPosition = new Vector2(float.NaN, float.NaN);
bool isWorldToViewportMatrixValid = _sceneView.GetWorldToViewportMatrix(out Matrix4x4 worldToViewportMatrix, forceMatrixRefresh: false);

if (isWorldToViewportMatrixValid)
{
    var screenPoint4 = Vector4.Transform(new Vector4(inputPosition3D.X, inputPosition3D.Y, inputPosition3D.Z, 1), worldToViewportMatrix);

    // Get screen position - perform perspective division (divide by W)
    if (screenPoint4.W != 0)
    {
        if (adjustByDpiScale)
            screenPosition = new Vector2(screenPoint4.X / (screenPoint4.W * _sceneView.DpiScaleX), screenPoint4.Y / (screenPoint4.W * _sceneView.DpiScaleY));

        screenPosition = new Vector2(screenPoint4.X / screenPoint4.W, screenPoint4.Y / screenPoint4.W);
    }
}
See Also