旋转一组向量 [英] Rotating a Group of Vectors
问题描述
我正在尝试将采样的一组矢量旋转到三角形的法线
I am trying to rotate a group of vectors I sampled to the normal of a triangle
如果这是正确的,则随机采样的半球将与三角形对齐.
If this was correct, the randomly sampled hemisphere would line up with the triangle.
当前,我在Z轴上生成它,并尝试将所有样本旋转到三角形的法线.
Currently I generate it on the Z-axis and am attempting to rotate all the samples to the normal of the triangle.
但它似乎刚刚好"
glm::quat getQuat(glm::vec3 v1, glm::vec3 v2)
{
glm::quat myQuat;
float dot = glm::dot(v1, v2);
if (dot != 1)
{
glm::vec3 aa = glm::normalize(glm::cross(v1, v2));
float w = sqrt(glm::length(v1)*glm::length(v1) * glm::length(v2)*glm::length(v2)) + dot;
myQuat.x = aa.x;
myQuat.y = aa.y;
myQuat.z = aa.z;
myQuat.w = w;
}
return myQuat;
}
我是从此页面底部撤出的: http://lolengine.net/blog/2013/09/18/beautiful-maths-quaternion-from-vectors
Which I pulled from the bottom of this page : http://lolengine.net/blog/2013/09/18/beautiful-maths-quaternion-from-vectors
然后我:
glm::vec3 zaxis = glm::normalize( glm::vec3(0, 0, 1) ); // hardcoded but test orginal axis
glm::vec3 n1 = glm::normalize( glm::cross((p2 - p1), (p3 - p1)) ); //normal
glm::quat myQuat = glm::normalize(getQuat(zaxis, n1));
glm::mat4 rotmat = glm::toMat4(myQuat); //make a rotation matrix
glm::vec4 n3 = rotmat * glm::vec4(n2,1); // current vector I am trying to rotate
推荐答案
构造 4x4变换矩阵,而不是四元数.
-
不要忘记OpenGL具有逐列矩阵
所以double m[16];
是m[ 0],m[ 1],m[ 2]
中的X
轴矢量
是m[ 4],m[ 5],m[ 6]
中的Y
轴矢量
是m[ 8],m[ 9],m[10]
中的Z
轴矢量
并且位置在m[12],m[13],m[14]
so for double m[16];
is X
axis vector in m[ 0],m[ 1],m[ 2]
is Y
axis vector in m[ 4],m[ 5],m[ 6]
is Z
axis vector in m[ 8],m[ 9],m[10]
and position is in m[12],m[13],m[14]
LCS 表示局部坐标系(您的三角形或对象或任何其他物体)
, GCS 表示整体坐标系(世界或其他任何东西).
The LCS mean local coordinate system (your triangle or object or whatever)
and GCS mean global coordinate system (world or whatever).
所有X,Y,Z
矢量都应归一化为单位矢量,否则会发生缩放.
All the X,Y,Z
vectors should be normalized to unit vectors otherwise scaling will occur.
建筑
- 将
Z
轴矢量设置为三角形法线 - 将位置( LCS 原点)设置到三角形的中点(或形成其顶点的平均点)
-
现在您只需要简单的
X
和Y
轴
- set
Z
-axis vector to your triangle normal - set position (LCS origin) to mid point of your triangle (or average point form its vertexes)
now you just need
X
andY
axises which is easy
让X = any triangle vertex - triangle midpoint
或X = substraction of any 2 vertexes of triangle
X
必须满足的唯一条件是它必须位于三角形平面上.
现在让Y = X x Z
叉积将创建垂直于X
和Z
(也位于三角形平面内)的向量.
The only condition that must be met for X
is that it must lie on triangle plane.
Now let Y = X x Z
the cross product will create vector perpendicular to X
and Z
(which also lies in triangle plane).
现在将所有这些内容放入矩阵中,并将其作为ModelView
矩阵或任何其他形式加载到 OpenGL 中.
now put all this inside matrix and load it to OpenGL as ModelView
matrix or what ever.
这篇关于旋转一组向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!