Search code examples
c++openglmatrixglm-mathcoordinate-transformation

glm set object position


I want to set the x, y, z coordinates of the object (not a camera) using glm library in OpenGL. I expect glm::translate method to cope with that, but it generates the matrix, that actually modifies the way I look at my object.

That is the way a call the method:

glm::translate(glm::vec3(x, y, z));

And it returns the matrix:

| 1  0  0  0 |
| 0  1  0  0 |
| 0  0  1  0 |
| x  y  z  1 |

But I expect:

| 1  0  0  x |
| 0  1  0  y |
| 0  0  1  z |
| 0  0  0  1 |

I made a quick-fix like glm::transpose(glm::translate(glm::vec3(x, y, z))), but it seems to be a bad code.

Is there a way to generate a matrix that would create a parallel translation, that would set the object's x, y, z coordinates, without transposing the matrix itself?

See this picture


Solution

  • GLM creates column major order matrices, because GLSL creates column major order matrices.

    If you want to get a row major order matrix, then you have either to glm::transpose the matrix or you have to use a matrix initializer:

    glm::mat4 m = glm::mat4(
        1.0f, 0.0f, 0.0f, x,
        0.0f, 1.0f, 0.0f, y,
        0.0f, 0.0f, 1.0f, z,
        0.0f, 0.0f, 0.0f, 1.0 );
    


    See OpenGL Mathematics (GLM):

    OpenGL Mathematics (GLM) is a header only C++ mathematics library for graphics software based on the OpenGL Shading Language (GLSL) specifications.


    See The OpenGL Shading Language 4.6, 5.4.2 Vector and Matrix Constructors, page 101:

    To initialize a matrix by specifying vectors or scalars, the components are assigned to the matrix elements in column-major order.

    mat4(float, float, float, float,  // first column
         float, float, float, float,  // second column
         float, float, float, float,  // third column
         float, float, float, float); // fourth column
    


    See also OpenGL Mathematics (GLM); 2. Vector and Matrix Constructors