I am trying to implement a feature where the screen location is centered at the spot where a user double clicks. I have added a MouseListener to my GLJPanel and here is its mouseClickced method:
public void mouseClicked( MouseEvent e )
{
if ( e.getClickCount( ) > 1 )
{
int x = e.getX( );
int y = e.getY( );
int realY = lastViewport[3] - y - 1;
System.out.println("x = " + x + "; y = " + y + "; realY = " + realY);
// Figure out the z-window coordinate of the galaxy to pass to gluUnProject
float z = (viewingDistance - NEAR_CLIP_PLANE) / (FAR_CLIP_PLANE - NEAR_CLIP_PLANE);
System.out.println("z = " + z);
double[] objPos = new double[3];
glu.gluUnProject( x, realY, z, lastModelViewMatrix, 0, lastProjectionMatrix, 0, lastViewport, 0, objPos, 0 );
lookX = -(float) objPos[0];
lookY = (float) objPos[1];
System.out.println("lookX = " + lookX + "; lookY = " + lookY);
repaint( );
}
}
I’m trying to use gluUnProject to find the x,y coordinate (in object space) of the screen coordinate clicked. There are two issues:
-
First, I’ve had to cache the model and projection matrices from the last time in display(). I use the following to get them
// Cache these matrices for later use in determining pixels per unit. gl.glGetIntegerv( GL.GL_VIEWPORT, lastViewport, 0 ); gl.glGetDoublev( GL.GL_MODELVIEW_MATRIX, lastModelViewMatrix, 0 ); gl.glGetDoublev( GL.GL_PROJECTION_MATRIX, lastProjectionMatrix, 0 );
If I don’t cache them, but try retrieving them in the mouseClicked method, they always come back all zero. I assume this is because something is not initialized in the GL context outside of the display() routine. Anyway caching seems to work fine.
- My real problem is getting the proper z-window value to pass into gluUnProject. The docs indicate it should be in the range [0,1] with 0 representing the near clip pane and 1 the far. My code above seems to work fine when the object I’m double clicking is positioned at either the near or far planes. However, for some reason, it doesn’t seem to work when the object is in between. If I set my viewing distance such that the object is exactly halfway between the near and far planes, and pass 0.5f for the z, the location returned doesn’t appear to be correct. I can’t figure out the problem. I know it’s a long shot that someone can help here, but if you have any ideas…
Bill