View Full Version : Getting screen location of 3D point.

09-27-2017, 07:25 PM
I am trying to get the screen location of a 3D point.
I scraped together code from some online sources into this:

glm::vec2 ProjPoint(Cam* camera, glm::vec3 p) {
glm::vec3 front;
front.x = cos(glm::radians(camera->pitch)) * cos(glm::radians(camera->yaw));
front.y = sin(glm::radians(camera->pitch));
front.z = cos(glm::radians(camera->pitch)) * sin(glm::radians(camera->yaw));
front = glm::normalize(front);

glm::mat4 projection = glm::perspective(glm::radians(fov), float(width) / float(height), 0.1f, 100.0f);
glm::mat4 view = glm::lookAt(camera->pos, camera->pos + front, glm::vec3(0.0f, 1.0f, 0.0f));

glm::mat4 viewProjectionMatrix = projection * view;
glm::vec4 point = viewProjectionMatrix * glm::vec4{ p.x,p.y,p.z,1 };
int winX = (int)(((point.x + 1) / 2.0) * float(width));
int winY = (int)(((1 - point.y) / 2.0) * float(height));
return glm::vec2(winX, winY);

What am i doing wrong? Since i have never used matrices till now ( was just useing glTranslate and glRotate), i dont know how to debug this.

Well, to answer my own question, i got it to work!
I changed the ProjPoint function to:

GLint viewport[4];
GLdouble mvmatrix[16], projmatrix[16];
GLdouble wx, wy, wz;
glGetIntegerv(GL_VIEWPORT, viewport);
glGetDoublev(GL_MODELVIEW_MATRIX, mvmatrix);
glGetDoublev(GL_PROJECTION_MATRIX, projmatrix);
gluProject(-p.x,p.y,-p.z, mvmatrix, projmatrix, viewport, &wx, &wy, &wz);
return glm::vec2{ wx ,wy };

However what i still dont understand is the weird translation i have to do before calling it:

glRotatef(-camera.pitch, 1.0f, 0.0f, 0.0f);
glRotatef(camera.yaw, 0.0f, 1.0f, 0.0f);
glTranslated(camera.x, -camera.y, camera.z);

Using gluProject(-p.x,p.y,-p.z, mvmatrix, projmatrix, viewport, &wx, &wy, &wz); with glTranslated(camera.x, -camera.y, camera.z); works but gluProject(p.x,p.y,p.z, mvmatrix, projmatrix, viewport, &wx, &wy, &wz); with glTranslated(-camera.x, -camera.y, -camera.z); doesnt.