View Full Version : Dynamically change the material color

12-15-2012, 07:05 AM
Before the glutMainLoop I define the lights and material colors:


glMaterialfv(GL_FRONT, GL_AMBIENT, (const GLfloat[]){1,0.2,0} );
glMaterialfv(GL_FRONT, GL_DIFFUSE, (const GLfloat[]){1,0.6,0} );
glMaterialfv(GL_FRONT, GL_SPECULAR, (const GLfloat[]){1,0.8,0} );
glMaterialfv(GL_FRONT, GL_SHININESS, (const GLfloat[]){1,1,0} );

glLightfv(GL_LIGHT0, GL_AMBIENT, (const GLfloat[]){1,1,1});
glLightfv(GL_LIGHT0, GL_DIFFUSE, (const GLfloat[]){1,1,1});
glLightfv(GL_LIGHT0, GL_SPECULAR, (const GLfloat[]){1,1,1});


And that's ok, but now I need to change the color material at runtime, when the user presses a key.
I still haven't studied shaders so I think that I'll first do it this way, and study shaders later because I need to finish a project in short time.
So when the user presses a key I just change the material this way:

glMaterialfv(GL_FRONT, GL_AMBIENT, (const GLfloat[]){0,0.2,1} );
glMaterialfv(GL_FRONT, GL_DIFFUSE, (const GLfloat[]){0,0.6,1} );
glMaterialfv(GL_FRONT, GL_SPECULAR, (const GLfloat[]){0,0.8,1} );
glMaterialfv(GL_FRONT, GL_SHININESS, (const GLfloat[]){0,1,1} );

I may also change only the ambient light or whatever, depending on the key pressed,After this I call glutPostRedisplay().
At the start of the program all is fine and I see a teapot drawn with glutSolidTeapot, being displayed with the right material.But whenever I press a key instead of changing the material, the teapot disappears, why?

12-17-2012, 02:52 PM
From just this info, I can't say very much. A few things though:

Why are you setting GL_SHININESS to a vector/array? GL_SHININESS takes a single scalar value, which you'd pass either through glMaterialfv with a one element array or glMaterialf as a plain GLfloat.

If you have trouble with this sort of thing, try changing your clear color (since most likely the teapot doesn't "disappear", but simply changes to the same color as the background) and comment out lines one by one, until you find the offending line. That's a pretty good "quick fix" for tackling bugs like this, since OpenGL errors generally keep to themselves unless you use glGetError().