![]() |
Tutorials > OpenGL > Color And Shading
Introduction
All colors in OpenGL are represented by 4 values. The first 3 values are red, green and blue intensities. The last value is the alpha. This specifies how transparent a color is. This will be dealt with in greater detail in a future tutorial. Contents of main.cpp : We will be switching between shaded and flat mode. A shaded variable has therefore been created to track what mode we are currently on. bool shaded = false; The glShadeModel function is used to change the current shading mode. The function accepts one parameter which can either be GL_FLAT or GL_SMOOTH. This specifies whether flat shading or smooth shading should be enabled respectively. This tutorial uses GL_FLAT as the initial value. As the default value is GL_SMOOTH, we need to make a call to glShadeModel. bool init() { . . glShadeModel(shaded ? GL_SMOOTH : GL_FLAT); return true; } In the display function, we render a triangle. Every vertex is given a new color. The current color is set by making a call to a glColor function. Many variations of the glColor function exist, including glColor3f, glColor4f, glColor3i, glColor4d and many others. The number after the glColor specifies how many parameters are passed i.e. 3 or 4. The letter after the number indicates what type the parameters are e.g. float, double, int, etc. In flat-shaded mode, the triangle will be rendered with the color that was given to the last vertex specified. In smooth-shaded mode, the colors are interpolated between the vertices where each vertex can be given a different color. void display() { glClear(GL_COLOR_BUFFER_BIT); glBegin(GL_TRIANGLES); glColor3f(1.0f, 0.0f, 0.0f); glVertex3f(0.25f, 0.25f, 0.0f); glColor3f(0.0f, 1.0f, 0.0f); glVertex3f(0.75f, 0.25f, 0.0f); glColor3f(0.0f, 0.0f, 1.0f); glVertex3f(0.25f, 0.75f, 0.0f); glEnd(); glFlush(); } In this tutorial, we modify the idle function. When the 'S' key is pressed, the shading mode is toggled. The 'S' key is reset when detected to prevent the key press being registered more than once. void idle() { if (opengl->isKeyDown('S')) { opengl->keyUp('S'); shaded = !shaded; glShadeModel(shaded ? GL_SMOOTH : GL_FLAT); } } Well done. You should now be able to add color and shading to your OpenGL primitives. This is essential for most OpenGL applications that you will create. Please let me know of any comments you may have : Contact Me
Last Updated : 14 October 2005
All Rights Reserved, © Zeus Communication, Multimedia & Development 2004-2005 Read the Disclaimer |
|