Click coordinates

Aug 13, 2013 at 8:13 PM
Edited Aug 13, 2013 at 8:14 PM
Hi,

I'm using SharpGL to render a DXF file. I defined my viewport like this
OpenGL gl = openGLControl.OpenGL;
gl.ClearColor(0, 0, 0, 0);
gl.MatrixMode(OpenGL.GL_PROJECTION);
gl.LoadIdentity();
gl.Ortho2D(dxf.MinX, dxf.MaxX, dxf.MinY, dxf.MaxY);
gl.MatrixMode(OpenGL.GL_MODELVIEW);
gl.Disable(OpenGL.GL_DEPTH_TEST);
gl.Clear(OpenGL.GL_COLOR_BUFFER_BIT);
I would like to know if there's a better way of getting the clicked position in the viewport (in world corrdinates).

Since I know my viewport is showing the area from (dxf.MinX, dxf.MinY) to (dxf.MaxX, dxf.MaxY) I can get the control coordinates and do some math to find the correct coordinate. But it seems an ugly option. Is there a better way of doing this?

Thanks in advance,
Rodrigo Basniak
Aug 13, 2013 at 9:13 PM
Use the function gl.Unproject to convert from screen to world coordinates.
Aug 14, 2013 at 1:10 PM
I tried to use the Unproject function, but it seems I'm missing something:

I created a viewport like this:
OpenGL gl = openGLControl.OpenGL;
gl.ClearColor(0, 0, 0, 0);
gl.MatrixMode(OpenGL.GL_PROJECTION);
gl.LoadIdentity();
gl.Ortho2D(0, 100, 0, 100);
gl.MatrixMode(OpenGL.GL_MODELVIEW);
gl.Disable(OpenGL.GL_DEPTH_TEST);
gl.Clear(OpenGL.GL_COLOR_BUFFER_BIT);
Then I draw a line as this one:
gl.Begin(OpenGL.GL_LINES);
gl.Vertex(5, 5);
gl.Vertex(10, 10);
gl.End();
gl.Flush();
The line shows in the lower left corner of the control, as if the origin was at the bottom left.

Then I use the Unproject function to get a clicked coordinate near the endpoints of the line I just draw, expecting the returned coordinates to be 5,5 and 10,10

But the return of the Unproject function is 5,95 and 10,90 (as if the origin was on the upper left corner of the control)

What am I'm missing here?
Aug 14, 2013 at 8:58 PM
So the line of code below sets up your the origin in the lower left corner of your control; with a width and height of 100 units.
gl.Ortho2D(0, 100, 0, 100);
That said, you need to invert the y-component of your mouse Point ! In my code I'm using WPF, so the mousedown event could look like this:
public Point ScreenToWorld(Point mousePoint)
        {
            double[] coords = gl.UnProject(mousePoint.X, mousePoint.Y, 0.0);
            return new Point(coords[0], coords[1]);
        }

private void OpenGLControl_OnMouseDown(object sender, MouseButtonEventArgs e)
        {
            var openGlControl = sender as OpenGLControl;

            Point mousePoint = e.GetPosition(openGlControl);
            Point invertedPoint = new Point(mousePoint.X, openGlControl.ActualHeight - mousePoint.Y);

            var modelWorldPoint = ScreenToWorld(invertedPoint);
        }
Aug 15, 2013 at 12:52 AM
Thanks Liamv06, that solved the problem.