DirectXMath矩阵示例程序
1. XMMATRIX类使用范例
#include <windows.h> // 为了使 XMVerifyCPUSupport 函数返回正确值
#include <DirectXMath.h>
#include <DirectXPackedVector.h>
#include <iostream>
using namespace std;
using namespace DirectX;
using namespace DirectX::PackedVector;
// 重载“<<”运算符,这样就可以利用cout输出 XMVECTOR 和 XMMATRIX 对象
ostream& XM_CALLCONV operator << (ostream& os, FXMVECTOR v)
{
XMFLOAT4 dest; // 4D向量
XMStoreFloat4(&dest, v); // 将数据从 XMVECTOR 类型存储到 XMFLOAT4 类型
os << "(" << dest.x << ", " << dest.y << ", " << dest.z << ", " << dest.w << ")";
return os;
}
ostream& XM_CALLCONV operator << (ostream& os, FXMMATRIX m)
{
for (int i = 0; i < 4; ++i)
{
os << XMVectorGetX(m.r[i]) << "\t";
os << XMVectorGetY(m.r[i]) << "\t";
os << XMVectorGetZ(m.r[i]) << "\t";
os << XMVectorGetW(m.r[i]);
os << endl;
}
return os;
}
int main()
{
// 检查是否支持SSE2指令集
if (!XMVerifyCPUSupport())
{
cout << "directx math not supported" << endl;
return 0;
}
XMMATRIX A(1.0f, 0.0f, 0.0f, 0.0f,
0.0f, 2.0f, 0.0f, 0.0f,
0.0f, 0.0f, 4.0f, 0.0f,
1.0f, 2.0f, 3.0f, 1.0f); // 设置矩阵
XMMATRIX B = XMMatrixIdentity(); // 返回单位矩阵 I
bool isIdentity = XMMatrixIsIdentity(B); // 判断矩阵是单位矩阵
XMMATRIX C = A * B; // 矩阵乘法
XMMATRIX C1 = XMMatrixMultiply(A, B); // 矩阵乘法
XMMATRIX D = XMMatrixTranspose(A); //转置矩阵
XMVECTOR det = XMMatrixDeterminant(A); // 行列式
XMMATRIX E = XMMatrixInverse(&det, A); // 逆矩阵
XMMATRIX F = A * E;
cout << "A = " << endl << A << endl;
cout << "B = " << endl << B << endl;
cout << "C = A*B = " << endl << C << endl;
cout << "C1 = A multiply B = " << endl << C1 << endl;
cout << "D = transpose(A) = " << endl << D << endl;
cout << "det = determinant(A) = " << det << endl << endl;
cout << "E = inverse(A) = " << endl << E << endl;
cout << "F = A*E = " << endl << F << endl;
cout << "B 是单位矩阵?" << isIdentity << endl;
return 0;
}
运行结果:
2. 矩阵运算公式个人总结
2.1 矩阵乘法
是m×n矩阵,
是n×s矩阵
m×n n×s m×s
2.2 转置矩阵
,则
2.3 余子式
,则