如何使用 DirectXMath 将世界 space 中的 3D 位置转换为 2D 位置

How to convert a 3D position in world space to 2D position using DirectXMath

我想利用 DirectXMath 提供的 SSE 内在函数(主要是为了速度优势) 我该怎么做?这是我当前使用的代码

DirectX::XMFLOAT4 clipCoordinates;
DirectX::XMFLOAT4X4 WorldMatrix4x4;
DirectX::XMStoreFloat4x4(&WorldMatrix4x4, WorldMatrix);
    
clipCoordinates.x = pos.x * WorldMatrix4x4._11 + pos.y * WorldMatrix4x4._12 + pos.z * WorldMatrix4x4._13 + WorldMatrix4x4._14;
clipCoordinates.y = pos.x * WorldMatrix4x4._21 + pos.y * WorldMatrix4x4._22 + pos.z * WorldMatrix4x4._23 + WorldMatrix4x4._24;
clipCoordinates.z = pos.x * WorldMatrix4x4._31 + pos.y * WorldMatrix4x4._32 + pos.z * WorldMatrix4x4._33 + WorldMatrix4x4._34;
clipCoordinates.w = pos.x * WorldMatrix4x4._41 + pos.y * WorldMatrix4x4._42 + pos.z * WorldMatrix4x4._43 + WorldMatrix4x4._44;

如果 2D 位置是指屏幕space 坐标:

首先从本地 space 转换到世界 space:

XMVECTOR world_pos = XMVector4Transform(pos, world_matrix);

然后从世界space变换到相机space:

XMVECTOR view_pos = XMVector4Transform(world_pos, view_matrix);

然后从相机 space 转换为剪辑 space:

XMVECTOR clip_pos = XMVector4Transform(view_pos , proj_matrix);

Remember that you can concatenate all of these into one transform by multiplying the XMMATRIX matrix = world_matrix * view_matrix * proj_matrix; together and then transforming the point by matrix.

现在除以w坐标得到NDC:

XMVECTOR w_vector = XMVectorSplatW(clip_pos);
XMVECTOR ndc = XMVectorDivide(clip_pos, w_vector);

You can combine the transform and divide by using XMVECTOR ndc = XMVector3TransformCoord(clip_pos, matrix);

您的 NDC x 和 y 分量在区间 [-1,1] 内。要在 [0,ScreenWidth][0,ScreenHeight] 中转换它们,您可以使用以下公式:

float ndc_x = XMVectorGetX(ndc);
float ndc_y = XMVectorGetY(ndc);
float pixel_x = (1.0f + ndc_x) * 0.5 * ScreenWidth;
float pixel_y = (1.0f - ndc_y) * 0.5 * ScreenHeight;

这些是你的屏幕坐标。