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

做~自己de王妃 提交于 2020-01-21 13:27:54

问题


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?)


回答1:


-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.




回答2:


Initialize your translation matrix

glm::mat4 trans(1);


来源:https://stackoverflow.com/questions/47178228/glmtranslate-outputs-a-matrix-with-incorrect-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!