Search code examples
opengllibgdx

Should I call GL_BLEND on create once


I want to enable transparency for my graphic objects. I have found out that just setting alpha to value between 0 and 1 is not enough, and that I have to call Gdx.gl.glEnable(GL20.GL_BLEND) before calling shapeRenderer.begin() and after the render call glDisable(GL20.GL_BLEND) below shapeRenderer.end(). However, my question is, can I call this method Gdx.gl.glEnable(GL20.GL_BLEND) in create method, instead in render, and enable it for game runtime? I have tried once to disable it, but I haven't face any errors nor performance issues. So what are the use cases, and when should I use this glDisable(GL20.GL_BLEND), or is there another way of setting alpha to shapes without calling that GL function ?


Solution

  • Blending in OpenGL is not independent of order. It also doesn't work well with objects that are not convex. As such, you generally don't just throw objects at the GPU with blending on.

    Also, having blending enabled has a performance cost. Typically more on mobile hardware than desktop, but it's not exactly free even on desktop hardware.

    Therefore, the general rule is to render all opaque surfaces first, then sort the transparent ones back-to-front, then render the transparent ones in that order. Also, when doing the blended rendering, you need to turn off depth writes; depth testing is still needed, but writes will cause problems.