How it works...

GLUT is initialized and a top-level window is created with the label, Displaying lines between two mouse clicks. The window size is specified as 1,000 px wide and 1,000 px in height. The drawLine callback function is invoked for drawing lines if any mouse click event has occurred.

In the drawLine function, the clear values for the clear buffers are specified. Also, the buffers are cleared to preset values so that colors can be applied to them. Because no mouse click has occurred yet, the value of noOfClicks global variable is 0, and hence no line will be drawn at the moment.

The glutSwapBuffers() function is invoked to swap the front and back buffers to display any frame that is rendered in the back buffer and is ready to be displayed. Because no mouse click has been made yet, nothing will happen with this function.

Then, the glutReshapeFunc function is invoked to specify the reshape callback function for the current window. The callback function projection will be invoked automatically whenever the window is reshaped, before the window's first display callback and after the window is created. In the projection callback, a viewport is set to define the vicinity in which we want the lines to be drawn. Thereafter, a matrix is set as the current matrix for the viewing and modeling transformations. Also, the vertices are rendered on the basis of the current state of the matrix, so the matrix is chosen accordingly.

Besides this, a two-dimensional orthographic viewing region is also set up. The mouse callback function is set up with the name mouseEvents, so whenever a mouse button is pressed or released, the mouseEvents callback function will be automatically invoked. In the callback function, the information about which mouse button is pressed and whether the mouse button is pressed or released is passed. Also, the x and y coordinates where the mouse action takes place are also passed to the mouseEvents callback function.

In the mouseEvents function, first, it checks whether the left mouse button is pressed. If yes, then the location where the mouse button is released, that location's x and y coordinates are picked up and assigned to the coord array. Basically, the mouse button has to be pressed and then released to store the coordinate values. When two mouse clicks and releases are observed, the drawLine function is invoked to draw the lines between the two coordinates.

To compile the program, start the X server and give the following command to compile the program:

gcc openglmouseclick.c -lGL -lGLU -lglut -lm -o openglmouseclick

If no error appears, that means the openglmouseclick.c program has successfully compiled into an executable file: openglmouseclick.exe. This file is executed using the following command:

$./openglmouseclick

We will get the output as shown in the following screenshot:

Figure 12.3

Once you implement this functionality, you can draw as many lines as you want.

Now let's move on to the next recipe!