Random color function for a simple triangle

Hello everyone,

I discover jogl and it a pleasure for me to use openGL with Java. I tried with C++ and I was quickly blocked because of my knowledge lack with this language.

Now I face another problem, that I will expose here. It seems very easy to resolve.

I draw a triangle with glBegin(GL_Triangle) and glEnd()

		
gl.glBegin(GL.GL_TRIANGLES);
			if (changeColor) SetRandomColor(gl);
			gl.glVertex3f( 0.0f, 1.5f,0.0f);
			if (changeColor) SetRandomColor(gl);
			gl.glVertex3f(-1.0f,-1.0f,0.0f);
			if (changeColor) SetRandomColor(gl);
			gl.glVertex3f( 1.0f,-1.0f,0.0f);
		gl.glEnd();

and I change the color with the simple following function:

	
public void SetRandomColor(GL gl){
		float c1, c2, c3;
		
		c1 = new Float(Math.random()).floatValue();
		c2 = new Float(Math.random()).floatValue();
		c3 = new Float(Math.random()).floatValue();
		gl.glColor3f(c1,c2,c3);
		
		System.out.println(c1 +" "+c2+" "+c3);
	}

The boolean changeColor is set to True in the resize function and set to false at the end of the draw function. So I guess that every vertex of the triangle would have a different color each time I resize de window. But in fact, each vertex change color well at resizeing but they have all the same color even if in the System.out.println() the values are differents ???

Where is the problem ?

Thx in advance, Machiiine

just a guess, but you probably need to change the shading model that is being used. Its probably set to GL_FLAT right now, if you use glShadeModel(GL_SMOOTH) then the colors will be interpolated.

Despite the shade-model, there is a more serious thing wrong with the code.

Let’s assume changeColor is true:
Every vertex has it’s own random color.

Let’s assume changeColor is false:
Every vertex has the last stored color with glColor.

The flow of the program is like:


// changeColor = true
glColor(1,0,0); // red
glVertex(...);
glColor(0,1,0); // green
glVertex(...);
glColor(0,0,1); // blue
glVertex(...);

// changeColor = false
glVertex(...); // still blue
glVertex(...); // still blue
glVertex(...); // still blue

Hope this helps.

Please use:
c1 = (float) Math.random();

instead of:
c1 = new Float(Math.random()).floatValue();

It hurts my eyes to see such missuse of objects :’(

Well, then use

private static final long seed = 0xFEEDCAFEBABEBEEFL;
private static final Random random = new Random(seed);

...

c1 = random.nextFloat();

That hurts the eyes even less! and should be twice as fast, right?

Riven’s right of the problem that changeColor == false.

I’ve tested the program on Linux, for the most time the vertices change color well and for a few times the three vertices will have the same color for the problem Riven pointed out.

I think a better way is to put the changed color in an array instead of this method.

Or compiled in a displaylist.