Now that I got the full picture I was able to fix it. You messed up some things. When you call glutMainLoop(); ,your display function is called. There you set all your initial rgb values as TEMPORARY function variables. Then you call your rainbowcolor(r,g,b). Here you enter a while loop which increases g until it is 255 without sending your color value to the gpu or making a single openGL draw call. When your function is finished, you continue in your display function with
glColor3ub(r,g,b);
draw(x1,x2,y1,y2);
glutSwapBuffers();
glFlush();
At this point you actually send the color to your GPU, but here g is already 255. Then you draw your Line. Actually I checked your code and you did not set double buffering. So you don’t need glutSwapBuffers(). Even if you did, glFlush does the same. Since you called glutPostRedisplay in your rainbowcolor function, the main loop from glut knows that it has to call the display function again in the next loop iteration. But now you repeat the same thing as before, since your r,g,b values are temporaries and are set back to the initial values. Anyways, you can achieve what you want by deleting your rainbow function and replacing your display function with the following one:
void display()
{
float x1, x2, y1, y2;
static int r = 255, g = 0, b = 0;
static int incdec = 1;
g += incdec;
if (g == 255)
incdec = -1;
if (g == 0)
incdec = 1;
glLineWidth(5.5);
glColor3ub(r, g, b);
draw(x1, x2, y1, y2);
glFlush();
std::this_thread::sleep_for(5ms);
glutPostRedisplay();
}
What it does is the following:
The variables r,g,b are now static. That means the values stay the same when the function is called a second time. If g was 42 at the end of the first call, then it is 42 when you call the function a second time and so on. Only the first call sets it to 0. Then you add incdec to your g. The incdec variable is just introduced to let g grow until 255 and fall back to 0 afterwards. Now you upload the color, draw your line and tell OpenGL to finish the drawing with glFlush. Then you wait 5ms and call glutPostRedisplay, which lets the main loop call your display function again. Since g is static, it has now a value of 1. You increase it to 2 and draw all your stuff again… and again.
EDIT: After re-reading some stuff, forget the thing I said about the side effects of glutPostRedisplay. It just tells gluts main loop, that the display needs to be updated during the next loop iteration, which means calling the display function. But that happens when your current display function call is finished. I have deleted the wrong statements to avoid confusing others who might read this.