openGL 2D mouse click location

10,047

Solution 1

GLdouble ox=0.0,oy=0.0,oz=0.0;
void Mouse(int button,int state,int x,int y) {
  GLint viewport[4];
  GLdouble modelview[16],projection[16];
  GLfloat wx=x,wy,wz;

  if(state!=GLUT_DOWN)
    return;
  if(button==GLUT_RIGHT_BUTTON)
    exit(0);
  glGetIntegerv(GL_VIEWPORT,viewport);
  y=viewport[3]-y;
  wy=y;
  glGetDoublev(GL_MODELVIEW_MATRIX,modelview);
  glGetDoublev(GL_PROJECTION_MATRIX,projection);
  glReadPixels(x,y,1,1,GL_DEPTH_COMPONENT,GL_FLOAT,&wz);
  gluUnProject(wx,wy,wz,modelview,projection,viewport,&ox,&oy,&oz);
  glutPostRedisplay();
}

Where ox, oy, oz are your outputted values

http://hamala.se/forums/viewtopic.php?t=20

Solution 2

In Windowing system, origin (0,0) is at the Upper Left corner, but OpenGL world window origin (0,0) is at the Lower Left corner. So you need to convert y coordinates only like such a way: new_y = window_height - y;

Share:
10,047
Wallter
Author by

Wallter

I'm a programer that dabbles in everything. I specialize in: Android (Tablets/Phones) - Love my Life IOS (iPad/iPhone) - Hate my Life PHP (specifically codeigniter) JavaScript HTML (dabbled in HTML5) Python C/C++ C# Server Config (Specifically Ubuntu/Cent-OS) CDMA Workshop / Flashing Phones (Android naturally)

Updated on June 04, 2022

Comments

  • Wallter
    Wallter almost 2 years

    Like this question states - I want to convert a click (2D) into coordinates relating to the rendering on the screen. I have the function glutMouseFunc bound to my function (below) but can not make sense of the x and y that are passed in - they seem to be relating to distance in pixels from the top left corner.

    I would like to know how to convert the x and y to world coordinates :)

    void mouse(int button, int state, int x, int y) {
      switch(button) {
      case GLUT_LEFT_BUTTON:
        printf(" LEFT ");
        if (state == GLUT_DOWN) {
            printf("DOWN\n");
            printf("(%d, %d)\n", x, y);
        }
        else 
          if (state == GLUT_UP) {
            printf("UP\n");
          }
        break;
    
      default:
        break;
      }
      fflush(stdout);                             // Force output to stdout
    }