 |
 |
|
 | |
Creating a DL
Our first approach is to have the code to draw each snowman inside a display list. Each display list must have a unique id. OpenGL has a command to generate a unique id:
GLuint glGenLists(GLsizei numberOfIDsRequired);
This command allocates the required number of contiguous ids. The value returned is the index of the first id. For now lets allocate a single id.
GLuint snowManDL;
...
snowManDL = glGenLists(1);
...
Afterwards, we can use this id, snowManDL, to create the list. In order to simplify things we are going to define a simple function that creates the list and returns the id.
The sequence of OpenGL commands to be included in a Display List must be enclosed on the pair of commands: glNewList and glEndList.
The signature for these functions is as follows:
void glNewList(GLuint listID, GLenum mode);
void glEndList(void);
where listID is the id for the list about to be created, and GLenum can be one of the following:
-
GL_COMPILE: it creates the list but the commands are not executed.
-
GL_COMPILE_AND_EXECUTE: creates the list and executes the commands immediately.
Now the code of the function that creates the display list is presented:
GLuint createDL() {
GLuint snowManDL;
// Create the id for the list
snowManDL = glGenLists(1);
// start list
glNewList(snowManDL,GL_COMPILE);
// call the function that contains the rendering commands
drawSnowMan();
// endList
glEndList();
return(snowManDL);
}
Note that although we're calling the same function as before, in the version without Display Lists, there is no execution of the commands in the function because the list is being created with the mode GL_COMPILE.
This function should be called in the initialization section.
void initScene() {
DLid = createDL();
...
}
The value of DLid must be know outside his function so we'll declare DLid as a global variable.
After the execution of the function above, the list is created and the commands are precompiled and ready to be called.
All there is left to do is to change our function to render the scene in order to call the Display List. In order to call a Display List we use the command:
void glCallList(GLuint listID);
The function to render a single frame is now:
void renderScene(void) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Draw ground
glColor3f(0.9f, 0.9f, 0.9f);
glBegin(GL_QUADS);
glVertex3f(-100.0f, 0.0f, -100.0f);
glVertex3f(-100.0f, 0.0f, 100.0f);
glVertex3f( 100.0f, 0.0f, 100.0f);
glVertex3f( 100.0f, 0.0f, -100.0f);
glEnd();
// Draw 36 Snowmen
for(int i = -3; i < 3; i++)
for(int j=-3; j < 3; j++) {
glPushMatrix();
glTranslatef(i*10.0,0,j * 10.0);
// Instead of calling the commands directly, we call the list we just created
glCallList(DLid);
glPopMatrix();
}
glutSwapBuffers();
}
To see the full source code go here
The approximate frame rate for this example in the test machine is: 153 fps
|