{steinsoft.net}
 
 
 
 
 
Home/News
Code Snippets
Board
Projects
What's That?
I am using it actively
I planning to use/learn it
I don't plan to lean/use it
5th option
Leipzig
Home :: Programming :: Code Snippets :: OpenGL :: Fading

[ Fading ]

Fading with OpenGL is very easy. In this code snippet I will show you how to fade from the current image on the screen to any other color. This function will also be cpu speed indepentent which means that the fade will take allways the same time whatever processor you have.

I use the STimer class from the code section to calculate the time. You could also use any other time function or class.

//For the STimer class (if you use it)
#include "STimer.h"
 
void FadeOut(int delay)
{
   STimer timer;
   timer.create();
   float time = 0.0f;
   float alpha = 0.0f;
 
   glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
   glEnable(GL_BLEND);
   glDisable(GL_DEPTH_TEST);
 
   for (;;)
   {
      time += timer.getTime();
 
      //Draw Quad that fits the screen
      //(found the coords with try-and-error principle;))
      glBegin(GL_QUADS);
         glColor4f(0.0f,0.0f,0.0f,alpha);
         glVertex3f(1.15f,1.15f,-2.0f);
         glVertex3f(-1.15f,1.15f,-2.0f);
         glVertex3f(-1.15f,-1.15f,-2.0f);
         glVertex3f(1.15f,-1.15f,-2.0f);
      glEnd();
      glFlush();
    
      //INSERT YOUR FUNCTION THAT SWAPS
      //BACK/FRONT BUFFER
      GLSwapBuffers();
 
      //calculate alpha
      alpha = (time/delay)/1000;
      
      //We're done when as soon as alpha has reached 1.0
      if (alpha >= 1.0f)
      {
         break;
      }
   }
 
   glDisable(GL_BLEND);
   glEnable(GL_DEPTH_TEST);
   glBlendFunc(GL_ONE,GL_ONE);
}

So this function will generate a fade to black that will take exactly 'delay' milliseconds. You can use this function everywhere in your code. Notice that the screen won't be updated/animated during the fade. The screen that is in the window when the fade starts will be "overdrawn" until it has reached the desired color. You can also fade to white or red or whatever you want. You only have to specify the color in the code.

If you want the screen being updated during the fade, insert the appropriate drawing function before the quad is drawn. Also don't forget to add winmm.lib to your project if you are using STimer. Otherwise there might be some problems ..

That's all! If you have problems or questions simply m@il me. Happy Coding!

 Last edited 2002-12-07 20:03:03 by André Stein - printable version
» copyright by andré stein
» using stCM v1.0
» steinsoft.net revision 5.0