### Bookstore

 Computer Math and Games in Pascal (preview) Lazarus Handbook

### Author Topic: Read OpenGLContent mouse position and convert back to coords.  (Read 1524 times)

#### wp

• Hero Member
• Posts: 12067
##### Re: Read OpenGLContent mouse position and convert back to coords.
« Reply #15 on: May 21, 2024, 04:58:08 pm »
I have the impression that you want to click on the vertices of the OGL model, "nodes" in your words, right? In this case, since there are only a few nodes you could iterate over the nodes, calculate the screen point and compare with the click position (and allow for some tolerance). Calculation of the screen point can be done by the inverse of your gluUnproject: gluProject
Code: Pascal  [Select][+][-]
1. type
2.   TOpenGLPoint = record
3.     X, Y, Z: GLDouble;
4.   end;
5.
6. function CalcOpenGLScreenPoint(P: TOpenGLPoint): TPoint;
7. var
8.   viewport:   array[0..3]  of Integer;
9.   modelview:  array[0..15] of GLDouble;
10.   projection: array[0..15] of GLDouble;
11.   X,Y,Z: Double;
12. begin
13.   glGetDoublev(GL_MODELVIEW_MATRIX, @modelview );
14.   glGetDoublev(GL_PROJECTION_MATRIX, @projection );
15.   glGetIntegerv(GL_VIEWPORT, @viewport);
16.
17.   gluProject(P.X, P.Y, P.Z, @modelView, @projection, @viewport, @X, @Y, @Z);
18.   Result.X := round(X);
19.   Result.Y := viewport[3] - round(Y);
20. end;
21.
22. function TForm1.FindClickedNodeIndex(X, Y: Integer): Integer;
23. // Assuming that your model consists of an array of vertices (TOpenGLPoint)
24. const
25.   Tolerance = 5;
26. var
27.   i: Integer;
28.   P: TPoint;
29. begin
30.   for i := 0 to Length(Vertices)-1 do
31.   begin
32.     P := CalcOpenGLScreenPoint(Vertices[i]);
33.     if (abs(P.X - X) < Tolerance)) and (abs(P.Y - Y) < Tolerance) then
34.     begin
35.       Result := i;
36.       exit;
37.     end;
38.   end;
39.   Result := -1;
40. end;

Attaching a small OpenGL project which demonstrates this. The nodes in the demo are at the corners/endpoints of the table-like object. Ctrl-click on them and the coordinates of the clicked vertex (in model coordinates) will be displayed in the blue label at the bottom.
P.S. Sorry for mentioning the integer issue in my previous post, I was just confused by the different order of declarations and procedure calls.
« Last Edit: May 21, 2024, 06:50:03 pm by wp »