Sign in to follow this  
LeoNatan

Need help with gluUnProject

Recommended Posts

Hey guys! Well, need some help with gluUnProject, but I'm guessing it's more to do with math. I'm doing a terrain editor. I have the following to render the scene:
void render()
		{
			Gl.glClearColor(173 / 255.0f, 192 / 255.0f, 255 / 255.0f, 255 / 255.0f);
			Gl.glClear(Gl.GL_COLOR_BUFFER_BIT | Gl.GL_DEPTH_BUFFER_BIT);

			Gl.glLoadIdentity();

			Glu.gluLookAt(camera.Position.X, camera.Position.Y, camera.Position.Z,
						  camera.Look.X, camera.Look.Y, camera.Look.Z,
						  camera.Up.X, camera.Up.Y, camera.Up.Z);

			terrain.Render(true);

			Glut.glutSwapBuffers();
		}

Basically it draws a terrain mesh loaded from a heightmap. Then I have the following to handle the mouse click:
void mouseHandler(int button, int state, int x, int y)
		{
			if (button == Glut.GLUT_LEFT_BUTTON && state == Glut.GLUT_DOWN)
			{
				var viewport = new int[4];
				var modelview = new double[16];
				var projection = new double[16];
				float winX, winY, winZ;
				double posX, posY, posZ;

				Gl.glGetDoublev( Gl.GL_MODELVIEW_MATRIX, modelview );
				Gl.glGetDoublev( Gl.GL_PROJECTION_MATRIX, projection );
				Gl.glGetIntegerv( Gl.GL_VIEWPORT, viewport );

				winX = x;
				winY = viewport[3] - y;
				// Read all pixels at given screen XY from the Depth Buffer
				var zzz = new float[16];
				Gl.glReadPixels(x, (int) winY, 1, 1, Gl.GL_DEPTH_COMPONENT, Gl.GL_FLOAT, zzz);
				winZ = zzz[0];

				Glu.gluUnProject(winX, winY, winZ, modelview, projection, viewport, out posX, out posY, out posZ);
			}
		}

And it works, just not as I'd want it to. I get the X,Y,Z position with relation to the camera, while I need the "real" coordinates. I'm guessing I have to do something with the matrices, but I'm not exactly sure what. Any help would be appreciated.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this