Search code examples
pythonopenglpygame3dpyopengl

glColor4fv Alpha Value Not Working in PyOpenGL


I'm using glColor4fv to set the color of the stuff I'm drawing in PyOpenGL, but the alpha value is not affecting anything. It sets the color correctly, but everything is drawn as if the alpha value is 1.0.

glColor4fv((0.2, 1.0, 0.6, 0.5))
gluSphere(gluNewQuadric(), .1, 64, 64)

Here's the init() function if it helps, I'm assuming I'm missing something in there. According to ChatGPT, enabling GL_BLEND should do it, but it isn't making a difference.

def init():
    pygame.init()
    display_info = pygame.display.Info()
    display = (display_info.current_w, display_info.current_h)
    pygame.display.set_mode(display, DOUBLEBUF | OPENGL)
    gluPerspective(45, (display[0] / display[1]), 0.1, 50.0)
    glEnable(GL_DEPTH_TEST)

    # Enable Alpha Values (Supposedly)
    glEnable(GL_BLEND)

    glClearColor(0.0, 0.0, 0.0, 1.0)
    glTranslatef(0, 0, -1)
    glMatrixMode(GL_MODELVIEW)

Solution

  • The default blending function is glBlendFunc(GL_ONE, GL_ZERO):

    fragment_color = source_color * 1 + destination_color * 0 
    

    You need to use a different blend function:

    fragment_color = source_color * source_alpha + destination_color * (1-source_alpha)
    
    glEnable(GL_BLEND)
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
    

    See Blending