Search code examples
c++opengltranslationglm-math

C++ glm Opengl Transforming and rotating a glm::vec4 with glm::mat4


So I'm trying to translate vertices on the CPU for my batch rendering system. And I've tried to replicate glsl but it simply doesn't work. (The model doesn't show up)

glm::vec4 off = glm::vec4(0, 0, 0, 1);

off = Util::createTransform(offset, glm::vec3(0, 45, 0)) * off; //translated the vertex by the offset(supplied by the function) and rotates by 45 degrees on the Y axis

for (int i = 0; i < Tvertex.size(); i++) {
    Tvertex[i] *= glm::vec3(off.x, off.y, off.z); //I think its here I might have messed up?
}

And here is the "Util::createTransform" function:

glm::mat4 Util::createTransform(glm::vec3 pos, glm::vec3 rot) {
    glm::mat4 trans = glm::mat4(1.0);
    trans = glm::rotate(trans, glm::radians(rot.x), glm::vec3(1, 0, 0));
    trans = glm::rotate(trans, glm::radians(rot.y), glm::vec3(0, 1, 0));
    trans = glm::rotate(trans, glm::radians(rot.z), glm::vec3(0, 0, 1));
    trans = glm::translate(trans, pos);
    return trans;
}

So, where did I screw up?


Solution

  • Util::createTransform() returns a glm::mat4, while you just take the rightmost column of that matrix and store it in a glm::vec4.

    You are trying to create a transform matrix which represents the composition of a rotation and a translation. This operation cannot be represented by a single vec4. You could do that for a translation alone, and then would simply add the same vector to all of your vertices to translate the offset around. However, with rotations - or other transformations besides translations - you will need the full matrix.

    Since glm uses the same conventions the old "fixed function" GL used, you have to use the Matrix * Vector multiplication order to apply a transformation matrix to your vertices. So your code should look like this:

    glm::mat4 off = Util::createTransform(offset, glm::vec3(0, 45, 0)) * off; //translated the vertex by the offset(supplied by the function) and rotates by 45 degrees on the Y axis
    
    for (int i = 0; i < Tvertex.size(); i++) {
        Tvertex[i] = off * Tvertex[i];
    }