2

I have encountered a problem when simulation transparency in OpenGL. Here is the scenario:

I have a ship which is represented by a sphere. Now I though about adding a shield around the ship. I chose a sphere too, but with a larger radius and set the alpha factor 0.5 ( opacity ). However, the shield doesn't appear and the colors don't blend( as if it was not there ).

The camera is located in the center of the 1st sphere. I think the problem is that I'm inside the sphere, so opengl will just ignore it(not draw it).

The code looks like this:

//ship colors setup with alpha 1.0f
glutSolidSphere(1, 100, 100); original sphere ( ship )
//shield colors setup with alpha 0.5f
glutSolidSphere(3, 100, 100); //the shield whose colors should blend with the rest of  the scene

I have though to simulate the shield with a parallelepiped in front of the ship. However this is not what I want...

EDIT: I have found the mistake. I was setting the near param of gluPerspective() too high, so even though i was setting the alpha value correctly, the camera was in front of the object all the time so there was no way of seeing it.

Dan Lincan
  • 1,065
  • 2
  • 14
  • 32

1 Answers1

0

Seems to work here:

#include <GL/glut.h>

void display()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glTranslatef(0, 0, -5);

    glDisable(GL_BLEND); 
    glColor4ub(255,0,0,255);
    glutSolidCube(1.0);

    glEnable(GL_BLEND); 
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glColor4ub(0,255,0,64);
    glutSolidSphere(1.5, 100, 100);

    glFlush();
    glutSwapBuffers();
}

void reshape(int w, int h)
{
    glViewport(0, 0, w, h);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective( 60, (double)w / (double)h, 0.01, 100 );
}

int main(int argc, char **argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE);

    glutInitWindowSize(800,600);
    glutCreateWindow("Blending");

    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutMainLoop();
    return EXIT_SUCCESS;
}
genpfault
  • 51,148
  • 11
  • 85
  • 139
  • well the camera is not outside the sphere, it's right in the center of the ship.. However it seems to work too if I move the camera on the center of the cube in your example. Can you explain what happens when inside an object? – Dan Lincan Jan 04 '12 at 17:37
  • Well, assuming `glEnable(GL_DEPTH_TEST)` and if you're inside the inner (=first drawn) sphere looking out your depth buffer will be filled a certain (near) Z value. Attempting to draw the second sphere further out will cause the depth test to fail for every pixel in the second sphere, since they'll all be "further away" than the inner sphere. My example works because I don't enable `GL_DEPTH_TEST` and it defaults to off. – genpfault Jan 04 '12 at 20:02