code_junkie

OpenGL: projecting mouse click onto geometry

Nov 11th, 2011
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.91 KB | None | 0 0
  1. glMatrixMode(GL_MODELVIEW); //Switch to the drawing perspective
  2. glLoadIdentity(); //Reset the drawing perspective
  3.  
  4. GLdouble modelMatrix[16];
  5. GLdouble projMatrix[16];
  6. GLint viewport[4];
  7.  
  8. glGetIntegerv(GL_VIEWPORT, viewport);
  9. glGetDoublev(GL_MODELVIEW_MATRIX, modelMatrix);
  10. glGetDoublev(GL_PROJECTION_MATRIX, projMatrix);
  11.  
  12. GLdouble x, y, z;
  13. gluUnProject(sx, viewport[1] + viewport[3] - sy, 0, modelMatrix, projMatrix, viewport, &x, &y, &z);
  14.  
  15. // replace the above gluUnProject call with
  16. gluUnProject(sx, viewport[1] + viewport[3] - sy, 1, modelMatrix, projMatrix, viewport, &x, &y, &z);
  17.  
  18. GLfloat nearv[3], farv[3]; // already computed as above
  19.  
  20. if(nearv[2] == farv[2]) // this means we have no solutions
  21. return;
  22.  
  23. GLfloat t = (nearv[2] - z) / (nearv[2] - farv[2]);
  24.  
  25. // so here are the desired (x, y) coordinates
  26. GLfloat x = nearv[0] + (farv[0] - nearv[0]) * t,
  27. y = nearv[1] + (farv[1] - nearv[1]) * t;
Add Comment
Please, Sign In to add comment