Home > database >  OpenGL Alpha Channel not affective
OpenGL Alpha Channel not affective

Time:03-15

Trying to make objects that fade over time in openGL.

I am doing this by decreasing the value of the Alpha in the color I am using to draw the object. But this does not seem to have any effect on the object, it still draws it as solid.

I have simplified the code to simply drawing three rectangles. Each rectangle is drawn with the same color but a different alpha value.

#include <GLUT/glut.h>
#include <stdlib.h>


void display(void)
{
    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

    // Set the color to red, with alpha at 100%
    float   f1[] = {1.0, 0, 0, 1.0};
    glColor4fv(f1);
    glRecti(10, 10, 110, 110);

    // Set the color to red, with alpha at 50%
    float   f2[] = {1.0, 0, 0, 0.5};
    glColor4fv(f2);
    glRecti(120, 10, 220, 110);

    // Set the color to red, with alpha at 20%
    float   f3[] = {1.0, 0, 0, 0.2};
    glColor4fv(f3);
    glRecti(230, 10, 330, 110);

    glFlush();
}

void reshape(int w, int h)
{
    glViewport(0, 0, w, h);␣
    glFrustum(-1.0, 1.0, -1.0, 1.0, 1.5, 5000.0);
    gluLookAt(0, 0, 500, 0, 0, 0, 0, 100, 0);
}

void keyboard(unsigned char key, int x, int y)
{
   switch (key) {
      case 27:
         exit(0);
         break;
   }
}

int main(int argc, char* argv[])
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_ALPHA);

    glutInitWindowPosition(100, 100);
    glutInitWindowSize(1200, 1200);
    int id = glutCreateWindow(argv[0]);

    // Set up call back
    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutKeyboardFunc(keyboard);

    glutMainLoop();

    glutDestroyWindow(id);
}

The code that does the display is all in display(). I have included all the other functions openGL functions I use as I am probably not setting something up correctly.

CodePudding user response:

You need to enable blending and set an appropriate blend function (see Blending). To run an OpenGL instruction, you need an OpenGL Context. The context is create when the OpenGL window is created with glutCreateWindow. Therefore you must add the instructions after glutCreateWindow.

int main(int argc, char* argv[])
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_ALPHA);

    glutInitWindowPosition(100, 100);
    glutInitWindowSize(1200, 1200);
    int id = glutCreateWindow(argv[0]);


    //
    // After the window has been created set the window
    // To enable the alpha part of the color.
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); 
    glEnable(GL_BLEND);
    // DONE    



    // Set up call back
    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutKeyboardFunc(keyboard);

    glutMainLoop();

    glutDestroyWindow(id);
}
  • Related