Paiku Han
Paiku Han

Reputation: 583

How to go from GLM to JOML (OpenGL Mathematics Libraries)

I have a code for my C++ Transform class that is supposed to give the user of the class a Model View Matrix

code-listing 1:

glm::mat4 Transform::GetModel(glm::vec3 pos, glm::vec3 rot, glm::vec3 scale, glm::mat4 parentTransformationMatrix){
    glm::mat4 posMat    = glm::translate(pos);
    glm::mat4 scaleMat  = glm::scale(scale);
    glm::mat4 rotX      = glm::rotate(rot.x, glm::vec3(1.0, 0.0, 0.0));
    glm::mat4 rotY      = glm::rotate(rot.y, glm::vec3(0.0, 1.0, 0.0));
    glm::mat4 rotZ      = glm::rotate(rot.z, glm::vec3(0.0, 0.0, 1.0));
    glm::mat4 rotMat    = rotX * rotY * rotZ;

    return parentTransformationMatrix * posMat * rotMat * scaleMat;
}

I made part of the code using JOML (for LWJGL3) already but I'm stuck with other parts (commented)

code-listing 2:

public Matrix4f GetModel(Vector3f pos, Vector3f rot, Vector3f scale, Matrix4f parentTransformationMatrix){
    Matrix4f posMat   ;// = translate(pos);
    Matrix4f scaleMat ;// = scale(scale);
    Matrix4f rotX     ;// = rotate(rot.x, Vector3f(1.0, 0.0, 0.0));
    Matrix4f rotY     ;// = rotate(rot.y, Vector3f(0.0, 1.0, 0.0));
    Matrix4f rotZ     ;// = rotate(rot.z, Vector3f(0.0, 0.0, 1.0));
    Matrix4f rotMat    = rotX.mul(rotY).mul(rotZ);

    return parentTransformationMatrix.mul(posMat).mul(rotMat).mul(scaleMat);
}

Upvotes: 0

Views: 1935

Answers (1)

httpdigest
httpdigest

Reputation: 5797

The exact equivalent of your GLM code would be this Java code using JOML:

public Matrix4f GetModel(Vector3f pos, Vector3f rot, Vector3f scale, Matrix4f parent) {
  return new Matrix4f(parent)
        .translate(pos)
        .scale(scale)
        .rotateXYZ(rot);
}

Unlike C/C++, Java does not (yet) have stack allocation built into the language itself (unless optimized by HotSpot when JIT'ting the bytecode). So prefer having a "dest"/destination/out parameter over creating a new Matrix4f instance (or modifying the parentTransformationMatrix matrix like you did above, because calling mul will modify it and not create a new Matrix4f).

So we end up with:

public Matrix4f GetModel(Vector3f pos, Vector3f rot, Vector3f scale, Matrix4f parent, Matrix4f dest) {
  return parent.translate(pos, dest)
               .scale(scale)
               .rotateXYZ(rot);
}

Upvotes: 1

Related Questions