سؤال

I am trying to do a simple projection, but I am having trouble with GLM. I have isolated the problem code to this example. Everything is well-formed until glm::vec4 v = mvp * v;. I have read of others running into a similar issue because of mismatched types (double and float, for example). I am getting very large or very small numbers that change each runtime. This leads me to believe that something is pointing to a garbage address somewhere.

How do I tell what types the vec4 and mat4 are (they are templated)? Is there something else going wrong here? This is getting frustrating since I know my mistake must be little, but I can't figure it out.

#define GLM_FORCE_RADIANS // Hide warnings
#include <cstdio>
#include <cstdlib>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_transform.hpp>

void print_mat4(glm::mat4 mat)
{
    int i, j;
    for (j = 0; j < 4; j++) 
    {
        for (i = 0; i < 4; i++) 
        {
            printf("%f\t", mat[i][j]);
        }

        printf("\n");
    }
}

int main()
{
    glm::mat4 projection = glm::perspective(45.0f, 1.0f, 0.1f, 100.0f);
    glm::mat4 view = glm::lookAt(
        glm::vec3(4.0f, 3.0f, 3.0f), 
        glm::vec3(0.0f, 0.0f, 0.0f), 
        glm::vec3(0.0f, 1.0f, 0.0f)  
    );

    glm::mat4 model = glm::mat4(1.0f);   
    glm::mat4 mvp   = projection * view * model;


    printf("Projection: \n");
    print_mat4(projection);
    printf("View: \n");
    print_mat4(view);
    printf("Model: \n");
    print_mat4(model);
    printf("MVP: \n");
    print_mat4(mvp);;

    glm::vec4 vert = glm::vec4(-1.0f, -1.0f, 0.0f, 1.0f);
    glm::vec4 v = mvp * v;

    printf("\nOriginal: (%f, %f, %f, %f)\n", vert.x, vert.y, vert.z, vert.w);
    printf("Transformed: (%f, %f, %f, %f)\n", v.x, v.y, v.z, v.w);

    return 0;
}

P.S. You can compile and run this code without linking anything. g++ matrix_test.cpp -o matrix_test && ./matrix_test

هل كانت مفيدة؟

المحلول

There is nothing wrong with GLM, You are using an uninitialized glm::vec4 v in your multiplication.

Check this line:

glm::vec4 v = mvp * v;

Instead you should do this:

glm::vec4 v = mvp * vert;
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top