Weird Color Behavior

I ma having some weird color behavior. I have a random color generator that I have create a color for each polygon I need to draw. The code looks like this where numPolygons is what it sounds like, the number of polygons I have:

   colors = (GLfloat *)malloc(numPolygons*3*sizeof(GLfloat));

   srand( (unsigned) time( NULL ) );
   GLfloat randomNum;

    // Create an array to hold the colors
   for( int i = 0 ; i < ( numPolygons * 3 ) ; i++ )
      randomNum = ( (GLfloat) rand( ) ) / RAND_MAX;
      colors[i] = randomNum;

When I draw this with display lists, I manually enter the array of colors to retrieve the RGB values for each polygon. Every polygon has its own unique color. But when I draw the object with vertex arrays, I have polygons next to each other having the same colors. When I debug, I discover these colors should not be the same. My code for this looks like:

	    // Enable use of vertex array
      glEnableClientState ( GL_VERTEX_ARRAY );
	    // Enable use of RGB color array
      glEnableClientState ( GL_COLOR_ARRAY );

	    // Specify pointer to vertex array
	    // (No. coordinates per vertex, type, byte offset, 
	    // pointer to array)
      glVertexPointer ( 3, GL_DOUBLE, 0, vertices );
	    // Specify pointer to color array
	    // Same structure as array pointer
      glColorPointer ( 3, GL_FLOAT, 0, colors );

Then when I display the polygons I use this simple code where numPolygons are the number of plygons to draw, numPoints are the number of points (vertices) per polygon and indices is the array holding my 3-dimensional vertices:

for( int i = 0 ; i < ( numPoints * numPolygons ) ; i = ( i + numPoints ) )
            glDrawElements( GL_POLYGON, numPoints, GL_UNSIGNED_INT, &indices[i] );

Does it look like I am doing something wrong? I know I must be if I am not coloring all my polygons correctly. Thanks for your help again!

Your post suggest that your color array stores a color per polygon. This is not how vertex arrays works in OpenGL; you cannot have per-polygon data in an array, only per-vertex data. So the color array must store one color for each vertex, not one color for each polygon.

So would I want 3 values for each color for each vertex? A red, green, and blue color values? So my array size would need to be something like where numVertices is the number of vertices in my object:

colors = (GLfloat *)malloc( numVertices * 3 * sizeof(GLfloat) );

Thanks for your continued help.

As Bob said, you need per vertex colors. That means you need a complete color defined for each vertex.

glDrawElements takes the index array and the number of indexes, not vertexes.

Your loop is totally insane, probably don’t even need it :wink: The point of DrawElements is to draw a big batch of primitives at one time. Decompose your polygons into a single list of triangles for example then make a single call to DrawElements on a per texture/shader basis.