出于目的,我需要将4x4矩阵分解为四元数和vec3。抓取四元数很简单,因为你可以将矩阵传递给构造函数,但我找不到抓取翻译的方法。肯定有办法吗?
看起来像glm 0.9.6支持矩阵分解http://glm.g-truc.net/0.9.6/api/a00204.html
glm::mat4 transformation; // your transformation matrix.
glm::vec3 scale;
glm::quat rotation;
glm::vec3 translation;
glm::vec3 skew;
glm::vec4 perspective;
glm::decompose(transformation, scale, rotation, translation, skew, perspective);
glm::vec3(m[3])
是位置向量(假设m
是glm::mat4
)
在版本glm-0.9.8.1,您必须包括:
#include <glm/gtx/matrix_decompose.hpp>
要使用它:
glm::mat4 transformation; // your transformation matrix.
glm::vec3 scale;
glm::quat rotation;
glm::vec3 translation;
glm::vec3 skew;
glm::vec4 perspective;
glm::decompose(transformation, scale, rotation, translation, skew,perspective);
请记住,生成的四元数不正确。它返回它的共轭!
要解决此问题,请将此添加到您的代码:
rotation=glm::conjugate(rotation);
我想我会在2019年发布一个更新和完整的答案。这是基于valmo的答案,包括Konstantinos Roditakis的答案中的一些项目以及我遇到的一些其他信息。
无论如何,从版本0.9.9开始,您仍然可以使用实验矩阵分解:https://glm.g-truc.net/0.9.9/api/a00518.html
首先,我正在添加的部分,因为我在其他任何地方都没有看到,除非您在下面的包含之前定义以下内容,否则您将收到错误:
#define GLM_ENABLE_EXPERIMENTAL
接下来,您必须包括:
#include <glm/gtx/matrix_decompose.hpp>
最后,一个使用示例:
glm::mat4 transformation; // your transformation matrix.
glm::vec3 scale;
glm::quat rotation;
glm::vec3 translation;
glm::vec3 skew;
glm::vec4 perspective;
glm::decompose(transformation, scale, rotation, translation, skew,perspective);
此外,如Konstantinos Roditakis的回答中所述,Quaternion确实是错误的,可以通过应用以下内容来修复:
rotation = glm::conjugate(rotation);
对不起,来晚了。实际上,当计算四元数的x,y,z分量时,你必须共轭结果quat的原因是矩阵分量的错误减法顺序。
Here是一个如何解释和示例代码。
所以基本上在glm,decompose()方法,matrix_decompose.inl文件中:
我们有 :
orientation.x = root * (Row[1].z - Row[2].y);
orientation.y = root * (Row[2].x - Row[0].z);
orientation.z = root * (Row[0].y - Row[1].x);
它应该是:
orientation.x = root * (Row[2].y - Row[1].z);
orientation.y = root * (Row[0].z - Row[2].x);
orientation.z = root * (Row[1].x - Row[0].y);
另外see this impl看起来非常接近GLM中发现的那个,但这是正确的。