Skip to content

How to retrieve a GL2 instance?

I am currently writting a game with the JOGL bindings to use OpenGL but I am so struggling on this.

I need to initialize my vaos and vbos (for each component) using the GL2 variable that I collected in the init method in the class that implements GLEventListener. Like so,

public abstract class Scene implements GLEventListener {
    private GL2 gl;

    @Override
    public void init(GLAutoDrawable drawable) {
        gl = drawable.getGL().getGL2();
        ...

But this variable is null when I want to use it because it appears it’s before the call of the method init (which is strange to me). I also checked GLContext.getCurrent() to maybe retrieve a GL instance but the context is also null.

So I wonder where is the context created and what triggers the init function above ?

Maybe I could simply make a boolean that tells when a component as been initialized in my render function, so maybe the GL init method would have been called.

Answer

The GL context usually gets created when the window is made visible for the first time, but it’s platform specific – could be when the window is created, could be immediately before your program starts drawing. The init() method will get invoked before the first display() but again there’s no guarantee about exactly when this happens.

My advice for JOGL is not to store the GL context permanently. Instead every init(), display(), reshape() starts with

GL2 gl = drawable.getGL().getGL2();

On some platforms trying to use the GL context outside of one of these methods won’t work/crashes the program, so making the context local also stops you writing code that could do so.

It’s also possible that the context could change, if the user say moves the window onto a display controlled by a different GPU.