Screen Coordinates to OpenGL Coordinates

How can I convert a mouse point’s screen coordinates to its OpenGL drawing coordinates if the drawing is a 2-D one? Thanks!

if you use an orthographic projection (using glOrtho) the mouse coordinates map directly to window coordinates.

jebus

Most of the time, the screen coordinates’s unit is pixel. When we draw points, we need to know the positions of the points. However, in this case we do not know the unit. That is to say, if we use glVertex2f(1.0f, 1.0f), we do not know the unit of these 1.0s. How can I solve the problem? That is to say, if my mouse screen coordinates are (100, 200), how much is the 100 in OpenGL? 1.0f? 0.5f? 2.0f?..

Of course we know the unit take the following ortho view.

void glOrtho( GLdouble left,
GLdouble right,
GLdouble bottom,
GLdouble top,
GLdouble zNear,
GLdouble zFar )

gluOrtho2D(-10.0, 10.0, -10.0, 10.0, -1, 1)

glViewport(0,0, 500, 500) Screen 500 x 500

Given that:

mouse_x = 0 = -10.0 openGL units
mouse_y = 0 = 10.0 openGL units

And we know the screen, we can make the following code:

x = -10.0 - (500 / (mouse_x + 1) * 20)

y = 10 - (500 / (mouse_y + 1) * 20)

Will give you the current mouse position in the current openGL units.

Originally posted by Rong Yao:
Most of the time, the screen coordinates’s unit is pixel. When we draw points, we need to know the positions of the points. However, in this case we do not know the unit. That is to say, if we use glVertex2f(1.0f, 1.0f), we do not know the unit of these 1.0s. How can I solve the problem? That is to say, if my mouse screen coordinates are (100, 200), how much is the 100 in OpenGL? 1.0f? 0.5f? 2.0f?..

Thanks a lot, Jebus and nexusone!

nexusone,

Do you mean 500 pixels = 20 OpenGL units in your case? If so, could it be

x = -10.0 + mouse_x/500 * 20
y = 10 - mouse_y/500 * 20

?

Why do you use mouse_x + 1 in your formula?

Thanks! Please reply.

I am a bit brian dead from the flu.

Sorry you are correct on the math, could be one other error on x or y in which should get the + or - 10.

Originally posted by Rong Yao:
[b]nexusone,

Do you mean 500 pixels = 20 OpenGL units in your case? If so, could it be

x = -10.0 + mouse_x/500 * 20
y = 10 - mouse_y/500 * 20

?

Why do you use mouse_x + 1 in your formula?

Thanks! Please reply.[/b]

nexusone,

Thank you for your reply. Sorry to hear you get flu. I was little bit confused just now.
The reason I post the last message is just to clarify my confusion and make sure I understand your method. Nothing else. Thanks again for your help and wish you recover from the flu soon!