OpenGL Diary

Day 1 - Getting started

Time to write my first OpenGL program. Looking through a few tutorials I found that the folowing code is a very good starting point.

#include <GL/gl.h>

#include <GL/glut.h>

 

void draw() {

  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  glFlush();

  glutSwapBuffers();

}

 

int main(int argc, char* argv[]) {

  glutInit(&argc, argv);

  glutInitDisplayMode(GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE);

  

  glutInitWindowPosition(100, 100);

  glutInitWindowSize(300, 200);

  glutCreateWindow("My OpenGL program");

  

  glutDisplayFunc(draw);

  glutIdleFunc(draw);

  

  glutMainLoop();

}

This will put a black (default color for glClear) window on your screen.

As you will notice most function calls are not OpenGL functions. Looking at a OpenGL reference you will notice that these functions start with "gl" followed by a capital letter (e.g. glClear or glFlush).

Most function calls above start with "glut" indicating they are part of GLUT. This library provides a lot of useful functions making it easier to use OpenGL. There are other libraries providing similar features but I stuck to GLUT and haven't had any problems yet.

Common trap:

Because the call to glutInit initializes many things needed by OpenGL, calling any OpenGL function before this will most likely result in a "Segmentation Fault" or some other error.

Now the next thing I did was using the draw function to really draw something.

void draw() {

  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  

  glBegin(GL_TRIANGLES);

    glVertex3f(-0.9f, -0.9f, 0.0f);

    glVertex3f(-0.9f, 0.9f, 0.0f);

    glVertex3f( 0.9f, 0.9f, 0.0f);

  glEnd();

  

  glFlush();

  glutSwapBuffers();

}

This will draw a triangle in the default color (white).

Screenshot showing simple triangle.

Note that resizing the windows also causes the triangle to be resized.

You can draw as much as you like between the calls to glBegin and glEnd, even using loops or calling other functions.

So when you do this:

void draw() {

  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  

  glBegin(GL_TRIANGLES);

    for (float i = 0.3f; i < 1.8f; i += 0.3f) {

      glVertex3f(-0.9f + i, -0.9f + i, 0.0f);

      glVertex3f(-0.7f + i, -0.9f + i, 0.0f);

      glVertex3f(-0.7f + i, -0.7f + i, 0.0f);

    }

  glEnd();

  

  glFlush();

  glutSwapBuffers();

}

You get this:

Screenshot showing multiple triangles.

The first thing to remember is that the X and Y coordinates passed to glVertex3f are mapped to the window in the following fashion.

X/Y coordinate system.

On Day 2 - Configuring the projection we will see what the Z coordinate is all about and how OpenGL projects objects onto the screen.