# OpenGL Calculating Z value for Unprojection

This topic is 2931 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

This is related to my active topic regarding building an RTS engine, but i have gone into a small query that i need to ask.

Generally speaking, when there was a need to project screen space coords to world space coords, we were forced to do this by utilising

glReadPixel - after the rendering part was done

glUnproject - with the Z value from glReadPixel

I have my own glUnproject method that is utilising the matrices instead of calling OpenGL - it works great, but as usual i need to pass a Z (depth) value i am currently picking .

I have a perspective projection, my terrain can be rotated and is visible from above but not constantly, it can be zoomed to but you never see the horizon ( see the vid below )

[media]
[/media]

It is time to implement terrain mesh editing stuff into the engine and here comes the trouble - is there any way i can calculate that Z value without calling glReadPixel ?
I mean are we stuck with it or there is something else i can do to calculate it without reading from depth buffer?

Having 'constant' Z value passed to my unproject method isn't a good idea, especially that it isn't that precise as you can see below:

[media]
[/media]

Any other approach or i should go with glReadPixel and there's nothing i can do - which means, everybody uses this method.

As my scene is not yet fully detailed it might sound reasonable to use glReadPixel - but i am afraid of the consequences later on when i'll use several FBOs / with or without depth buffers attached..

Any suggestions?

##### Share on other sites
Pass two different Z values, 0 and 1 will give you a point on the near-plane and another at the far-plane. These two points form a line, and that line intersects your geometry somewhere. Calculate the intersection using normal ray/triangle intersection or some other method. Intersecting a line with a height-map is generally not too difficult.

##### Share on other sites
Ok will have a look into this then, thanks!

• ### Game Developer Survey

We are looking for qualified game developers to participate in a 10-minute online survey. Qualified participants will be offered a \$15 incentive for your time and insights. Click here to start!

• 9
• 11
• 15
• 21
• 26