Thomas Faulhaber
Thomas Faulhaber

Reputation: 73

Pyglet ignores alpha channel

I'm trying to make a level editor for a game I'm writing in Python using Pyglet. I want to be able to modify the darkness of any block I place. As such, I have added a darkness attribute to the Block class. Here is that class:

class Block:
    def __init__(self, name, image, wall):
        self.name = name
        self.image = image
        self.wall = wall
        self.darkness = 0

    def set_darkness(self, darkness):
        self.darkness = darkness

    def draw(self, x, y):
        self.image.blit(x, y)
        pyglet.graphics.draw(4, GL_QUADS, ('v2i', (x, y, x + block_width, y, x + block_width, y + block_height, x, y + block_width)), ('c4B', (0, 0, 0, self.darkness) * 4))

I am trying to darken an image by drawing a black rectangle on top of it, and then adjusting the transparency of that rectangle. However, no matter what I set self.darkness to in __init__, the rectangle continues to be completely opaque. I tried enabling color blending with pyglet.gl by adding this code to the top of my program:

from pyglet.gl import *
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

This changed nothing. I also tried using Pyglet's SolidColorImagePattern class to create a black rectangle with the alpha channel set to self.darkness, but that also did nothing. How do I make this rectangle transparent?

Upvotes: 1

Views: 353

Answers (1)

Rabbid76
Rabbid76

Reputation: 211176

For any OpenGL instruction, a valid and current OpenGL Context is of need. Of course pyglet provides an OpenGL context, but the context is created and made current when the pyglet (OpenGL) window is created (see pyglet.window).

Create the window, before setting up Blending to solve the issue:

from pyglet.gl import *

window = pyglet.window.Window(400, 400, "OpenGL window")

glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

Upvotes: 1

Related Questions