How to do it...

The following are the steps to make different graphical shapes:

  1. Initialize GLUT, define the window size, create the window, and set the position of the window.
  2. Define the callback function that will be automatically invoked after displaying the window.
  3. To draw a square, first, define its color.
  4. Draw a square by defining its four vertices and enclosing them within glBegin and glEnd statements along with the GL_QUADS keyword.
  5. To draw a line, set the width and color of the line.
  6. Group a pair of vertices within glBegin and glEnd with the GL_LINES keyword to draw a line.
  7. To draw the points, set the point size to 3 px and also set their color.
  8. The vertices are where the points have to be displayed. Group them into a pair of glBegin and glEnd with theĀ GL_POINTS keyword.
  9. To draw a triangle, group three vertices into glBegin and glEnd statements along with the GL_TRIANGLES keyword.
  10. The glFlush function is invoked to empty all the buffered statements and get the shapes drawn quickly.

The program for drawing the preceding four shapes is as follows:

//opengldrawshapes.c

#include <GL/glut.h>

void drawshapes() {
glClearColor(0.0 f, 0.0 f, 0.0 f, 1.0 f);
/* Making background color black as first
All the 3 arguments R, G, B are 0.0 */
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_QUADS);
glColor3f(0.0 f, 0.0 f, 1.0 f);
/* Making picture color blue (in RGB mode), as third argument is 1. */
glVertex2f(0.0 f, 0.0 f);
glVertex2f(0.0 f, .75 f);
glVertex2f(-.75 f, .75 f);
glVertex2f(-.75 f, 0.0 f);
glEnd();
glLineWidth(2.0);
glColor3f(1.0, 0.0, 0.0);
glBegin(GL_LINES);
glVertex2f(-0.5, -0.5);
glVertex2f(0.5, -0.5);
glEnd();
glColor3f(1.0, 0.0, 0.0);
glPointSize(3.0);
/* Width of point size is set to 3 pixel */
glBegin(GL_POINTS);
glVertex2f(-.25 f, -0.25 f);
glVertex2f(0.25 f, -0.25 f);
glEnd();
glBegin(GL_TRIANGLES);
glColor3f(0, 1, 0);
glVertex2f(0, 0);
glVertex2f(.5, .5);
glVertex2f(1, 0);
glEnd();
glFlush();
}

int main(int argc, char ** argv) {
glutInit( & argc, argv);
glutCreateWindow("Drawing some shapes");
/* Giving title to the window */
glutInitWindowSize(1500, 1500);
/* Defining the window size that is width and height of window */
glutInitWindowPosition(0, 0);
glutDisplayFunc(drawshapes);
glutMainLoop();
return 0;
}

Now, let's go behind the scenes to understand the code better.