I am struggling trying to implement vertex selection by mouse clicking. I load in some set of vertices and display them onto the screen. Then I do the following to try and retrieve a line that passes through the selected point in world coordinates and through the eye position.
setFocus();
float xRatio, yRatio, xScene, yScene;
xRatio = (float)event->x() / width();
yRatio = (float)event->y() / height();
xScene = (1-xRatio)*-1 + xRatio*1;
yScene = yRatio*-1 + (1-yRatio)*1;
// mouse click now transformed to [-1,1]^2
// Import the viewPort
GLint *params = new GLint(4);
glGetIntegerv(GL_VIEWPORT, params);
QRect vp = QRect(*params, *(params + 1), *(params + 2), *(params + 3));
QVector3D dir = QVector3D(xScene, yScene, 0.2); // distance to near pane = 0.2
QVector3D origin = QVector3D(0.0, 0.0, 0.0);
// Now I have the origin and point in near clipping pane of the line (I think)
// Unproject them to world coordinates.
dir = dir.unproject(modelViewMatrix, projectionMatrix, vp);
origin = origin.unproject(modelViewMatrix, projectionMatrix, vp);
float minDist = 1000.0;
int minIndex = 0;
float dist;
for (int i = 0; i < vertexCoords.size(); ++i){
dist = vertexCoords[i].distanceToLine(origin, dir);
if (dist < minDist){
minDist = dist;
minIndex = i;
}
}
I keep getting wrong result with this method. It will almost always select the same point and report a large distance of about 20 to that point. So something is going terribly wrong. Can anyone spot what is going wrong or what I am missing?
Additionally, here is how the view and projection matrices look:
modelViewMatrix.setToIdentity();
modelViewMatrix.translate(QVector3D(0.0, 0.0, -3.0));
modelViewMatrix.scale(QVector3D(1.0, 1.0, 1.0));
modelViewMatrix.rotate(rotX, 0.0, 1.0, 0.0);
modelViewMatrix.rotate(rotY, 1.0, 0.0, 0.0);
projectionMatrix.setToIdentity();
projectionMatrix.perspective(FoV, dispRatio, 0.2, 8.0);
Sorry for the long question, I have found quite some resources online but none of them help me figure out what is going wrong. Also, if there is a better method I would gladly hear it! Thanks