2
votes

I've got a program, in which I display an object. First I load position p.x, p.y, p.z, and scale s.x, s.y, s.z from the file. Then I apply them to 4x4 ModelMatrix and perform many translation and scale operations to it.

When I load object for the first time, I use p and s values:

modelMatrix = glm::mat4(1.0));

/*Translations*/
modelMatrix = glm::translate(modelMatrix, glm::vec3(p.x, p.y, p.z));
modelMatrix = glm::scale(modelMatrix, glm::vec3(s.x, s.y, s,z));

While during the program I perform scale and translation operations, and then save p and s values back to the file.

void Display::Translate( double x, double y, double z)
{
    modelMatrix = glm::translate(modelMatrix, glm::vec3(x,y,z));
    p.x += x;   //that way p is composition of all translations
    p.y += y;
    p.z += z;
} 

void Display::Scale( double x, double y, double z)
{
    modelMatrix = glm::scale(modelMatrix, glm::vec3(x,y,z));
    s.x *= x;    //that way s is composition of all scalings
    s.y *= y;
    s.z *= z;
}

Now the problem is that after loading again (running the program again), objects are not in the place I save them, but some rather random place. (especially translation). Am I composing transformations in the wrong way (adding to x,y,z in translation and multiplying in scalings)?

1
I'm not sure what exactly you're saving to and loading from a file because you didn't bother telling us - there's a good chance your error is to be found there - but it's also worth pointing out that transformations aren't commutative - if you do a translate first and then a scale, the results are in the general case going to be different from doing first a scale and then a translation. If you want to save the transformation to a file, save the full transformation matrix, not the sum of all translations and the sum of all scales. - Cubic

1 Answers

2
votes

Am I composing transformations in the wrong way (adding to x,y,z in translation and multiplying in scalings)?

Yes, this is wrong, because your translations are in fact scaled as well. The better bet would be to simply extract the scale and translation from your model matrix. The translation can be found in the w-column (the rightmost column) and the scale can be found in the upper left 3×3 submatrix; the trivial case is just the diagonal elements, but if there were applied rotations you have to either to determine the major axis (https://en.wikipedia.org/wiki/Principal_axis_theorem) or just fluke it and simply take the lengths of the column vectors for scale.