【发布时间】:2019-05-08 11:21:06
【问题描述】:
我很难理解为什么将两个 DirectX 4x4 矩阵相乘时得到不同的结果,具体取决于乘法是否在类函数中执行。
以恒等矩阵为例,使用以下代码,结果 1 和结果 2 的值最终会有所不同。
#include <iostream>
#include <DirectXMath.h>
using namespace DirectX;
class Model {
public:
XMMATRIX MatrixMult(XMMATRIX test) {
XMMATRIX result = test * XMMatrixIdentity();
return result;
}
private:
};
int main() {
Model m;
XMMATRIX result1 = XMMatrixIdentity() * XMMatrixIdentity(); //returns identity
XMMATRIX result2 = m.MatrixMult(XMMatrixIdentity()); //doesn't return identity
int height = 4;
int width = 4;
//Output results
XMMATRIX results[2] = { result1, result2 };
//for each result
for (int res = 0; res < 2; ++res) {
//for each row
for (int i = 0; i < height; ++i)
{
//for each column
for (int j = 0; j < width; ++j)
{
if (j == 0) {
std::cout << XMVectorGetX(results[res].r[i]) << ' ';
}
else if (j == 1) {
std::cout << XMVectorGetY(results[res].r[i]) << ' ';
}
else if (j == 2) {
std::cout << XMVectorGetZ(results[res].r[i]) << ' ';
}
else if (j == 3) {
std::cout << XMVectorGetW(results[res].r[i]) << ' ';
}
}
std::cout << std::endl;
}
std::cout << "\n";
}
return 0;
}
实际上看起来像在 result2 中,预期的结果从矩阵的第 3 行开始? (下面的输出)
//result1
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
//result2
8.2597e-39 -1.07374e+08 -1.07374e+08 -1.07374e+08
-1.07374e+08 -1.07374e+08 -1.07374e+08 -1.07374e+08
1 0 0 0
0 1 0 0
我知道通过将数组作为函数传递,我正在复制它,但我没想到这会有所作为。
任何帮助将不胜感激!
【问题讨论】:
-
你使用什么编译器和更新?
-
我正在使用 Visual Studio Community 2017 (15.9.11)
-
您如何看待结果?如果我使用
printf和%f,它会输出合理的输出。 -
嗯,这很奇怪。我已经包含了用于输出结果的代码,但是在调试时我在局部变量表中看到了相同的值(所以会认为它与输出过程无关?)。
-
一般输出
XMMATRIX的最佳方式是使用XMStoreFloat4x4,然后使用XMFLOAT4X4结构打印出元素。很可能存在一个编译器错误,所有 SIMD 都在内存中,并且你正在做的来回......
标签: c++ matrix directx multiplication directxmath