“glm::translate” outputs a matrix with incorrect v

2019-02-26 03:04发布

I took a sample code to test the glm::translate function:

glm::vec4 vec(1.0f, 0.0f, 0.0f, 1.0f);
glm::mat4 trans;
trans = glm::translate(trans, glm::vec3(1.0f, 1.0f, 0.0f));
vec = trans * vec;
std::cout << vec.x << ", " << vec.y << ", " << vec.z << std::endl;

It outputs the following:

-4.29497e+08, -4.29497e+08, -4.29497e+08

instead of the expected 2, 1, 0

What is the possible cause and what can I do about it?

(Should I search for the flaw outside this piece of code?)

2条回答
萌系小妹纸
2楼-- · 2019-02-26 03:39

Initialize your translation matrix

glm::mat4 trans(1);
查看更多
Viruses.
3楼-- · 2019-02-26 03:42
-4.29497e+08

This looks like uninitialised memory, which would lead me to believe the flaw lies in:

glm::mat4 trans;

You have not initialised the matrix, but have performed an arithmetic operation on it. You cannot assume that a constructor will initialise it's memory, so change to:

glm::mat4 trans(1.0f);

And that should fix the problem.

This may not show up in all development environments, as, for example, debug mode in VS has some safeguards to prevent this, but it will show up in release mode.

Simply put: Practice RAII: Resource Acquisition Is Initialisation. At the very least, zero the memory, as when the memory is reallocated, it will be set to whatever it's previous value was when it was last released.

查看更多
登录 后发表回答