Search code examples
openglglm-math

what function to use in glm to get the same result as this function


There is a function GLRotation

inline const mat4 GLRotation(float x, float y, float z)
{
    const float cx = cosf(x * math_radians), sx = sinf(x * math_radians),
                cy = cosf(y * math_radians), sy = sinf(y * math_radians),
                cz = cosf(z * math_radians), sz = sinf(z * math_radians);

    // rotationX * rotationY * rotationZ
    return mat4(cy * cz, -cy * sz, sy, 0,
                cx * sz + sx * cz * sy, cx * cz - sx * sy * sz, -cy * sx, 0,
                sx * sz - cx * cz * sy, cz * sx + cx * sy * sz, cx * cy, 0,
                0, 0, 0, 1);
}

And use can call it like this GLRotation(v.rotation) where v.rotation - vector(x, y, z).

What function I need to use in glm(library) to get the same result?


Solution

  • Your function GLRotation() specifies the angle in radians to rotate in each principle axis. On the other hand glm::rotate(angle, axis) specifies a rotation about a provided axis. So, strictly speaking you can define your GLRotation as follows:

    inline mat4 
    GLRotation(float x, float y, float z)
    {
        return 
            glm::rotate(x, 1, 0, 0) * 
            glm::rotate(y, 0, 1, 0) * 
            glm::rotate(z, 0, 0, 1);
    }
    

    Although I wouldn't advise this, because describing rotations in this way can lead to Gimbal lock (when you rotate in one axis in such a way that it becomes aligned with another axis, losing you one degree of freedom).

    Better to look into Axis-Angle representations of rotations, which is what glm::rotate uses. They aren't susceptible to gimbal lock, and can represent any 3D rotation about an axis through the origin.