glm returning nan on simple translate

时光怂恿深爱的人放手 提交于 2019-12-24 00:36:12

问题


I'm tinkering with OpenGL using glfw, glad, and glm. In one of the tutorials I'm using, they demonstrate some simple usage of glm as so:

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;

When I compile and run this code, I get trash values (usually NAN). The tutorial specifically noted that instantiating

glm::mat4 trans;

would by default create an identity matrix for the varialbe "trans". I'm thinking that perhaps this is the issue, though I have verified that glm does do this by default.

In case it would be helpful, you can find the entire source file here on line 308. I greatly appreciate your time!


回答1:


You have to initialize the matrix variable glm::mat4 trans.

The glm API documentation refers to The OpenGL Shading Language specification 4.20.

5.4.2 Vector and Matrix Constructors

If there is a single scalar parameter to a vector constructor, it is used to initialize all components of the constructed vector to that scalar’s value. If there is a single scalar parameter to a matrix constructor, it is used to initialize all the components on the matrix’s diagonal, with the remaining components initialized to 0.0.

This means, that an identity matrix can be initialized by the single parameter 1.0: glm::mat4(1.0f).

Change your code somehow like this:

glm::mat4 trans(1.0f);


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




回答2:


Answering my own question: though the tutorial and other sources said that glm would automatically instantiate an identity vector for

glm::mat4 trans;

it did not. Looking at a different tutorial, it seems that you can do so explicitly with

glm::mat4 trans = glm::mat4(1.0f);

And this solved the problem!



来源:https://stackoverflow.com/questions/49058381/glm-returning-nan-on-simple-translate

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