简体   繁体   English

如何使用 DirectXMath 将世界空间中的 3D position 转换为 2D position

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

I want to take advantage of the SSE intrinsics (mostly for the speed advantage) that DirectXMath provides How would i do it?我想利用 DirectXMath 提供的 SSE 内在函数(主要是为了速度优势)我该怎么做? this is the current code im using这是我正在使用的当前代码

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;

If by 2D position you mean screenspace coordinates:如果二维 position 是指屏幕空间坐标:

First transform from local space to world space:首先从局部空间变换到世界空间:

XMVECTOR world_pos = XMVector4Transform(pos, world_matrix);

Then transform from world space to camera space:然后从世界空间变换到相机空间:

XMVECTOR view_pos = XMVector4Transform(world_pos, view_matrix);

Then transform from camera space to clip 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;请记住,您可以通过乘以XMMATRIX matrix = world_matrix * view_matrix * proj_matrix;将所有这些连接到一个变换中。 together and then transforming the point by matrix .一起,然后通过matrix变换点。

Now divide by w coordinate to get NDC:现在除以 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);您可以使用XMVECTOR ndc = XMVector3TransformCoord(clip_pos, matrix);组合变换和除法。

Your NDC x and y components are in interval [-1,1] .您的 NDC x 和 y 分量在区间[-1,1]中。 To transform them in [0,ScreenWidth] and [0,ScreenHeight] you use the following formulas:要在[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;

And those are your screen coordinates.这些是您的屏幕坐标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM