Problems mapping 2d window coordinates to 3d system coordinates

Hello everybody
I’m trying to solve this problem since several days, I searched a lot of threads, but I couldn’t manage to get rid of it yet
I use the same code showed in all the threads dealing about this problem:

//I got the mouse position, and invert the Y
GLfloat Y=ClientWindowWidth-MouseY;
GLfloat X=MouseX;
//then I get the Z by looking into the Z buffer:
GLdouble Z;
glReadPixels(X, Y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &Z);
//then I use this code to get the 3d coordinates
GLdouble objx,objy,objz;
GLint viewport[4];
GLdouble modelMatrix[16];
GLdouble projMatrix[16];
glGetIntegerv(GL_VIEWPORT, viewport);
glGetDoublev(GL_MODELVIEW_MATRIX,modelMatrix);
glGetDoublev(GL_PROJECTION_MATRIX,projMatrix);
gluUnProject(X, Y, Z , modelMatrix, projMatrix, viewport, &objx, &objy, &objz);

But the coordinates I get are very low, they seems to be the ones at Near Clip Plane (I use a Perspective projection with
fovy=45, NearPlane=1 and FarPlane=200)
But my object was about at z=-100 …How can I get the correct coordinates, or map the ones I got at z=-100 ???
I really Thank You in advance…Please HELP
Stefano B.

Your variable Z is of type Gldouble, but with glReadPixels you request GL_FLOAT.

Funny, you have made the very same mistake as the guy a couple weeks ago asking the same question. I don’t get why everybody makes this mistake, maybe there’s some buggy tutorial around or something. Or maybe I just got it all wrong. It sure looks like a mistake.

-Ilkka

Another mistake:

Originally posted by stefboombastic:
<…>
//I got the mouse position, and invert the Y
GLfloat Y=ClientWindowWidth-MouseY;
<…>

It should be height, not width.

Originally posted by zeckensack:
[b]Another mistake:

[quote]Originally posted by stefboombastic:
<…>
//I got the mouse position, and invert the Y
GLfloat Y=ClientWindowWidth-MouseY;
<…>

It should be height, not width.[/b][/QUOTE]

Thank You Mr. zeckensack but that was only a typing mistake in my code there is ClientWindowHeight of course! …I hope that won’t confuse anybody!
Good work!
Stefano B.

Originally posted by JustHanging:
[b]Your variable Z is of type Gldouble, but with glReadPixels you request GL_FLOAT.

Funny, you have made the very same mistake as the guy a couple weeks ago asking the same question. I don’t get why everybody makes this mistake, maybe there’s some buggy tutorial around or something. Or maybe I just got it all wrong. It sure looks like a mistake.

-Ilkka[/b]

Thank You VERY MUCH Mr. JustHanging
That little bug was the problem!! I’ve been trying to find a solution for days and it was so simple
I Think I’ve been mixed up by c++ auto casting …I haven’t thought OpenGL was so strict with types!
Now everything seems to work properly, even if the results given by glUnProject are not always very accurate!
Thank You again … My best regards!
Stefano B.