Search code examples
c++matrixglm-math

Reuse matrix in glm?


I have a glm::mat4 field in a class of mine representing a model transformation matrix, and I would like to update the transformation every frame. However, I would like to reuse the matrix in this field every time I update the transformation, instead of setting it to a glm::mat4(), which I imagine would waste more and more memory as the matrix that was stored there is assigned over. Am I imagining this leak? Is there a way for me to "re-identity" a matrix in glm?


Solution

  • There is no leak, what you are doing every frame is similar to int i = 1 every frame;

    // Im assuming somewhere in your class you have this:
    class Example{
        public:
            ...
            void Update();
            void Draw();
        private:
            glm::mat4 m_Model;
    };
    
    void Example::Update()
    {
        // This will rotate the model 1 degree every time update is called
        m_Model = glm::rotate(m_Model, 1.0f, glm::vec3(1, 0, 0);
    }
    
    void Example::Draw()
    {
        glUniformMatrix4fv(1, GL_FALSE, GL_FALSE, glm::value_ptr(m_Model));
        // Draw model etc.. 
    };
    

    The point is that you don't have to set m_Model to glm::mat4 every frame if you're just keeping it at a static position ( it's always at x,y,z position ), that's equivalent to setting int i = 1 every single update, it's pointless as it is stored in your classes memory and retains the last value set until the class is destroyed.