了解 GLM 4x4 矩阵函数

Understanding the GLM 4x4 Matrix functions

本文关键字:函数 4x4 GLM 了解      更新时间:2023-10-16

我在理解 GLM 矩阵函数的某个元素时遇到问题,同时试图复制它的一些数学来完成我的 Matrix4 课的作业。采取这个旋转功能。

    tmat4x4<T, P> const & m,
    T angle,
    tvec3<T, P> const & v
    T const a = angle;
    T const c = cos(a);
    T const s = sin(a);
    tvec3<T, P> axis(normalize(v));
    tvec3<T, P> temp((T(1) - c) * axis);
    tmat4x4<T, P> Rotate(uninitialize);
    Rotate[0][0] = c + temp[0] * axis[0];
    Rotate[0][1] = 0 + temp[0] * axis[1] + s * axis[2];
    Rotate[0][2] = 0 + temp[0] * axis[2] - s * axis[1];
    Rotate[1][0] = 0 + temp[1] * axis[0] - s * axis[2];
    Rotate[1][1] = c + temp[1] * axis[1];
    Rotate[1][2] = 0 + temp[1] * axis[2] + s * axis[0];
    Rotate[2][0] = 0 + temp[2] * axis[0] + s * axis[1];
    Rotate[2][1] = 0 + temp[2] * axis[1] - s * axis[0];
    Rotate[2][2] = c + temp[2] * axis[2];
    tmat4x4<T, P> Result(uninitialize);
    Result[0] = m[0] * Rotate[0][0] + m[1] * Rotate[0][1] + m[2] * Rotate[0][2];
    Result[1] = m[0] * Rotate[1][0] + m[1] * Rotate[1][1] + m[2] * Rotate[1][2];
    Result[2] = m[0] * Rotate[2][0] + m[1] * Rotate[2][1] + m[2] * Rotate[2][2];
    Result[3] = m[3];

或平移函数(v 是一个向量)

    tmat4x4<T, P> const & m,
    tvec3<T, P> const & v
    Result[3] = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3];

我难以理解的部分是矩阵结果[1]或m[0]访问的哪一部分。结果[1] = 结果[1][1]吗?它用于许多函数,这是我遇到麻烦的这些功能的最后一部分。

他们如何处理使用单个数字访问 2D 数组中的元素,以及该单个数字访问的元素?

定义模板tmat4x4<T,P>的代码,类型为 T 和精度P,可在此处获得,回答您的问题。

如您所见,第 60 行,tmat4x4的实际数据内容定义为由 4 个col_type元素组成的数组,访问m[i](将第 96 行定义为返回 col_type & )返回完整的第 i 列。

col_type 被 typedef'd to tvec4<T,P> ,其代码可在此处获得,并且还定义了一个返回类型 T &[] 访问运算符,因此当你写m[a][b]时,你会说"给我 A 列,其中的元素 b"。

tvec4<T,P>还定义了一个二元*运算符,因此将整个向量乘以某个类型为 U 的标量是有意义的,该标量是将向量的每个元素乘以该标量。

因此,为了回答您的问题,Result[1]不是Result[1][1]而是Result[1][1..4](即使这C++不合适)。

有两个函数名为 tmat4x4<T, P>::operator[] 。一个具有返回类型 tmat4x4<T>::col_type&,另一个具有返回类型 tmat4x4<T>::col_type const& 。因此,m[1]并不表示矩阵的单个元素;相反,它表示矩阵的整个列(四个元素),您可以对其执行数学列向量运算。