OpenGL was designed to be very easy to learn and use. Thus, its syntax is relatively straightforward, and you can actually be coding within minutes. As an example, here is a very simple OpenGL code snippet: glClearColor(0.0, 0.0, 0.0, 0.0); glClear(GL_COLOR_BUFFER_BIT); glLookAt(0, 0, -10, 0, 0, 0, 0, 1, 0); glBegin(GL_TRIANGLES); glColor3f(1,0,0); glVertex3f(-1,0,0); glColor3f(1,1,0); glVertex3f(1,0,0); glColor3f(0,0,1); glVertex3f(0,1,0); glEnd(); This relatively simple program draws a triangle on the screen. You can see the output in Figure B.1. But right now we will focus on learning the basic OpenGL syntax, and not so much on the triangle. Figure B.1. White triangle over black background; "Hello world" for OpenGL.As you will probably have discovered, all OpenGL calls start with the gl prefix. All words after gl use initial capital letters, and word separations are not separated by the underscore sign. Symbolic constants, on the contrary, use all caps and underscore each space. This makes command recognition simpler, for example:
OpenGL explicitly indicates the parameter types in the function name. So, a call like this: glColor3f receives three parameters, each one of float type. Different calls receive different parameter sets. Moreover, some calls have variants depending on the parameters you want to pass. For example, to specify colors, you could use:
This makes coding a bit more intuitive. Because OpenGL is available for many programming languages (C/C++, Pascal, Basic), it has its own generic types, so you can hide the specific types each language uses. For the C/C++ version of OpenGL, Table B.1 lists the parameter types.
Additionally, most calls to OpenGL accept vectors to be passed as parameters. For example, the following two calls are completely equivalent: glVertex3f(1.0, 0.0, 0.0); float vertex_array[] = {1.0, 0.0, 0.0}; glVertex3fv(vertex_array); Notice how the v suffix is used to indicate a vector is going to be passed. The numeric value then represents not the number of parameters, but the length of the vector. So now we can review the preceding code and figure out what each line does. The first two lines specify the background color and clear the frame buffer to that value. Next, we define a camera with the gluLookAt call. Then, we declare a geometry object (a triangle), specifying its three vertices and a different color for each one. Let's now explore the rendering capabilities of OpenGL, to better understand how geometry is sent to the graphics hardware. |