Search code examples
openglglm-math

Returning a glm::vec3 x value returns null


So I have an assignment where I have to return an axis of rotation as a normal vector perpendicular to the plane. Here is my code:

glm::vec3 Skeleton::returnAxis()
{
GLdouble firstPoint[3]; 
GLdouble secondPoint[3]; 
GLdouble thirdPoint[3]; 

GLint viewport[4];
GLdouble modelview[16];
GLdouble projection[16];

glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
glGetDoublev(GL_PROJECTION_MATRIX, projection);
glGetIntegerv(GL_VIEWPORT, viewport);

gluUnProject(0,0,0, modelview, projection, viewport, &firstPoint[0], &firstPoint[1], &firstPoint[2]);
gluUnProject(viewport[2], 0 ,0, modelview, projection, viewport, &secondPoint[0], &secondPoint[1], &secondPoint[2]);
gluUnProject(0,viewport[3],0, modelview, projection, viewport, &thirdPoint[0], &thirdPoint[1], &thirdPoint[2]);


glm::vec3 point1 = glm::vec3(secondPoint - firstPoint);
glm::vec3 point2 = glm::vec3(thirdPoint - firstPoint);
glm::vec3 axis = glm::normalize(glm::cross(point1, point2));
return axis; 
std::cout << axis.x;


}

Problem is, it isn't returning any numbers! Just blank. Even after I did a typecast to float (not shown in the code above).

Help!


Solution

  • It is not possible to perform vector operations on GLdouble[] arrays directly.

    glm::vec3 point1 = glm::vec3(secondPoint - firstPoint);
    

    The subtraction here is actually performed on the pointers (the addresses) of the arrays and does not return the mathematical operation. Instead a new address is calculated which is then again treated as a GLdouble[] to initialize the vec3. In addition, creating the vector as done here is also not a good idea since a temporary object is created.

    The correct code for what you want to do could be:

    glm::vec3 point1(secondPoint[0] - firstPoint[0],
                     secondPoint[1] - firstPoint[1],
                     secondPoint[2] - firstPoint[2]);
    

    Similar for point2.