使用`gluUnProject`在opengl中拾取鼠标

时间:2013-06-06 13:05:09

标签: c++ opengl geometry mouse-picking

我有一个场景,我用openGL渲染几个立方体(程序结构不使用GLUT,它在win32程序结构中,但我只是用glutSolidCube绘制多维数据集) 现在我想通过拾取鼠标来选择这些立方体。这就是我在做的事情: 首先当用户点击场景上的鼠标按钮时,我得到鼠标位置并试图在场景坐标中找到它的坐标(templateSkeletons是我用立方体创建的骨架,仅此而已):

if (mouse.buttonPressed(Mouse::BUTTON_LEFT))
        {
            mouse.update();
            templateSkeletons[0].selectionMode = true;
            Vector3* points;
            points = GetOGLPos();
            templateSkeletons[0].setIntersectionPoints(points[0],points[1]);
        }else
            templateSkeletons[0].selectionMode = false;

这是GerOGLPos函数,我正在检索场景中的坐标(注意我有自己的camrea和它自己的投影矩阵,但我只是通过调用{{1}来获取此函数中的投影矩阵这是错的,我应该得到我自己的camrea的投影矩阵?):

glGetDoublev (GL_PROJECTION_MATRIX, projmatrix);

现在我想我有两点表示我在场景中采摘射线。现在,当我渲染立方体时,我尝试计算光线和立方体创建的线的距离,如果它小于值,我改变立方体的颜色以知道我选择它(jointsOfSkeleton指示每个立方体不再创建骨架,在这里我只测试数组中的多维数据集编号6:

Vector3* GetOGLPos()
  {Vector3 pointsOnLine[2];
double mvmatrix[16];
double projmatrix[16];
int viewport[4];
double dX, dY, dZ, dClickY,zz;  
glGetIntegerv(GL_VIEWPORT, viewport);   
glGetDoublev (GL_MODELVIEW_MATRIX, mvmatrix);
glGetDoublev (GL_PROJECTION_MATRIX, projmatrix);
dClickY = double (viewport[3] - mouse.yPos()); 
// OpenGL renders with (0,0) on bottom, mouse reports with (0,0) on top
//glReadPixels( mouse.xPos(), int(dClickY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &zz );
gluUnProject ((double) mouse.xPos(), dClickY, 0.0, mvmatrix, projmatrix, viewport, &dX, &dY, &dZ);
pointsOnLine[0] = Vector3( (float) dX, (float) dY, (float) dZ );
gluUnProject ((double) mouse.xPos(), dClickY, 1.0, mvmatrix, projmatrix, viewport, &dX, &dY, &dZ);
pointsOnLine[1]  = Vector3( (float) dX, (float) dY, (float) dZ );

    return pointsOnLine;
       }

当我点击窗口上不相关的位置时,我看到立方体的颜色变化,它不能正常工作,我正在观察调试器上的距离,距离看起来不正确。这是我用来寻找线点距离的函数:

 if(selectionMode)
        {

            distToLine  = Vector3::PointToLineDistance3D(rayPoints[0],rayPoints[1],Vector3::Vector3(jointsOfSkeleton[6].x,
                jointsOfSkeleton[6].y,jointsOfSkeleton[6].z));
            //distToLine = sqrt(distToLine);
            if(distToLine < 0.5)
                glColor3f(1.0,0.0,0.0);

            else 
                glColor3f(1.0,1.0,1.0);
        }

1 个答案:

答案 0 :(得分:2)

这就是我写PointToLineDistance3D

的方式
static float PointToLineDistance3D(const Vector3 &a, const Vector3 &b, const Vector3 &point){   
    Vector3 lineDirection = Vector3::normalize(b - a), pointDirection = point - a;
    float t = Vector3::dot(pointDirection,lineDirection);
    Vector3 projection = a + (lineDirection * t);

   float ShortestDistance = (projection - point).length();
   return ShortestDistance;
}

我假设:

  • Vector3类有一个length方法,具有明显的含义,
  • 有一个*运算符来缩放向量,
  • 还有一个normalize函数,它返回...一个规范化的向量(这也可以作为避免构造额外对象的方法)。

我们的想法是计算point在光线上的投影,然后计算projectionpoint之间的距离。正如您所看到的,算法与您的实现略有不同,最值得注意的是t的计算。也许这就是你的问题所在。

为了测试我上面提供的代码,我用它编写了一个小程序,它在XY平面上构建了一个3x3的立方体墙,墙的中心是<0,0,0>。即使在移动相机时,我设法让它正常工作。唯一的问题是关于从上到下的鼠标坐标系统(即,Y_鼠标坐标向下增加_),这是自然OpenGL Y轴的对立面。它需要 SDL 库才能编译和运行。

#include <iostream>

#include <GL/gl.h>
#include <GL/glu.h>
#include <SDL/SDL.h>
#include <unistd.h>

#include <Vector3.h>

#define WIDTH 800
#define HEIGHT 600

GLuint box;
int highlight[2]; // position of the cube in the wall
const float cube_width = 5.0; 

Vector3 position(0,0,-25); // camera position

// build the cube display list
void setup_cube(){

  const float w = cube_width;

  float w0 = -w, h0 = -w, w1 = w, h1 = w;

  box = glGenLists(1);
  glNewList(box, GL_COMPILE);
    glBegin(GL_QUAD_STRIP);
      glVertex3f(w0, h1, w0);
      glVertex3f(w0, h0, w0 );
      glVertex3f(w1, h1, w0 );
      glVertex3f(w1, h0, w0 );
      glVertex3f(w1, h1, w1 );
      glVertex3f(w1, h0, w1 );
      glVertex3f(w0, h1, w1 );
      glVertex3f(w0, h0, w1 );
    glEnd();
    glBegin(GL_QUAD_STRIP);
      glVertex3f(w1, h1, w0 );
      glVertex3f(w1, h1, w1 );
      glVertex3f(w0, h1, w0 );
      glVertex3f(w0, h1, w1 );
      glVertex3f(w0, h0, w0 );
      glVertex3f(w0, h0, w1 );
      glVertex3f(w1, h0, w0 );
      glVertex3f(w1, h0, w1 );
    glEnd();
  glEndList();
}

void setup_scene(){

  float r = WIDTH / HEIGHT;

  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glFrustum( -r, r, -1, 1, 1, 1024);

  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();

  glTranslatef(position[0],position[1],position[2]);

  glEnable(GL_CULL_FACE);
  glEnable(GL_DEPTH_TEST);
}

void draw_scene(){

  const float w = cube_width;
  int i = 0, j = 0;

  for (int i = -1; i < 2; i++) {
    for (int j = -1; j < 2; j++) {
      float x = w * 2 * i,  y = w * 2 * j;

      if (highlight[0] == i && highlight[1] == j)
         glColor3f(0.0, 1.0, 0.0);
      else 
         glColor3f(1.0, 0.0, 0.0);

      glPushMatrix ();
         glTranslatef(x,y,0);
         glCallList(box);
      glPopMatrix ();
    }
  }
}

void aim(float xm, float ym_){

  const float w = cube_width;
  float ym = HEIGHT - ym_;

  GLdouble model[16];
  GLdouble proj[16];
  GLint view[16];

  glGetDoublev(GL_MODELVIEW_MATRIX, model);
  glGetDoublev(GL_PROJECTION_MATRIX, proj);
  glGetIntegerv(GL_VIEWPORT, view);
  highlight[0] = -5;
  highlight[1] = -5;

  for (int i = -1; i < 2; i++) {
    for (int j = -1; j < 2; j++) {
      float x = w * 2 * i, y = w * 2 * j;
      double ox, oy, oz;
      Vector3 centre(x,y,0);
      gluUnProject(xm, ym, 0, model, proj, view, &ox, &oy, &oz);
      Vector3 p0(ox,oy,oz);
      gluUnProject(xm, ym, 1, model, proj, view, &ox, &oy, &oz);
      Vector3 p1(ox,oy,oz);
      float d = PointToLineDistance(p0,p1,centre);
      if (d < w) {
        highlight[0] = i;
        highlight[1] = j;
        return;
      }
    }
  }
}

int main(){

  SDL_Surface *screen;

  SDL_Init(SDL_INIT_VIDEO);

  SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 );
  SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 5 );
  SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 );
  SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 );
  SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

  if ( (screen=SDL_SetVideoMode( WIDTH, HEIGHT, 32, SDL_OPENGL )) == NULL ) {
    SDL_Quit();
    return -1;
  }

  setup_cube();

  while (1) {
    SDL_Event event;
    setup_scene();

    while(SDL_PollEvent(&event)){
      switch(event.type){
      case SDL_MOUSEMOTION:
        aim(event.motion.x, event.motion.y);
        break;
      case SDL_KEYDOWN: 
        {
          switch (event.key.keysym.sym){
          case SDLK_ESCAPE:
            SDL_Quit();
            exit(1);
          case SDLK_LEFT:
            position.add(Vector3(1,0,0));
            break;
          case SDLK_RIGHT:
            position.sub(Vector3(1,0,0));
            break;
          case SDLK_UP:
            position.add(Vector3(0,0,1));
            break;
          case SDLK_DOWN:
            position.sub(Vector3(0,0,1));
            break;
          case SDLK_PAGEDOWN:
            position.add(Vector3(0,1,0));
            break;
          case SDLK_PAGEUP:
            position.sub(Vector3(0,1,0));
            break;
          }
        }
      default:
        break;
      }
    }
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    draw_scene();
    SDL_GL_SwapBuffers();
    usleep(10);
  }

  return 0;
}

上面列出的源正确显示鼠标指针所针对的立方体。可以使用箭头和向上/向下翻页键来移动。