0%

DirectX 3D将屏幕坐标映射到世界坐标系

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <D3D9.h>
#include <DirectXMath.h>

struct Point
{
Point(const int32_t x, const int32_t y)
: _x(x)
, _y(y)
{
}

int32_t _x;
int32_t _y;
};

struct PointF
{
PointF(const double x, const double y)
: _x(x)
, _y(y)
{
}

double _x;
double _y;
};

PointF screen_pos_to_d3d_world_pos(HWND hWnd, IDirect3DDevice9* device, const Point& pt)
{
using namespace DirectX;

XMVECTOR screenPos = XMVectorSet(pt.x(), pt.y(), 0, 0);
XMVECTOR worldPos;

// 获取客户区宽高
RECT clientRect;
GetClientRect(hWnd, &clientRect);

// 获取视口信息
D3DVIEWPORT9 viewport;
device->GetViewport(&viewport);

// 获取投影矩阵
D3DMATRIX projectionMatrix;
device->GetTransform(D3DTS_PROJECTION, &projectionMatrix);

// 获取世界矩阵
D3DMATRIX worldMatrix;
device->GetTransform(D3DTS_WORLD, &worldMatrix);

// 获取视图矩阵
D3DMATRIX viewMatrix;
device->GetTransform(D3DTS_VIEW, &viewMatrix);

XMMATRIX xmProjectionMatrix = XMLoadFloat4x4((XMFLOAT4X4*)&projectionMatrix);
XMMATRIX xmWorldMatrix = XMLoadFloat4x4((XMFLOAT4X4*)&worldMatrix);
XMMATRIX xmViewMatrix = XMLoadFloat4x4((XMFLOAT4X4*)&viewMatrix);

worldPos = XMVector3Unproject(
screenPos,
viewport.X,
viewport.Y,
clientRect.right - clientRect.left,
clientRect.bottom - clientRect.top,
viewport.MinZ,
viewport.MaxZ,
xmProjectionMatrix,
xmViewMatrix,
xmWorldMatrix
);

return PointF(XMVectorGetX(worldPos), XMVectorGetY(worldPos));
}
请我喝瓶肥仔快乐水?

欢迎关注我的其它发布渠道