iphoneobjective-copengl-eseaglvieweaglcontext

Using the same EAGLContext across different ViewControllers/EAGLViews


I'm having some issues using the same EAGLContext across EAGLViews. I have two View Controllers, each one has one EAGLView.

Each View Controller allocates a new EAGLContext, and a subsequent framebuffer/colorbuffer is created for each respective EAGLView, but this is a waste of memory resources.

I know that it is possible to use the same EAGLContext across ViewControllers by simply binding different framebuffers/colorbuffers to different EAGLViews:

Using Multiple OpenGL Views And UIKit

But i didnt manage to achieve that so far.

Any ideas?

Thanks in advance.


Solution

  • Finally managed to solve the problem.

    In one of the view controllers i was using:

    dispatch_async(openGLESContextQueue, ^{
    
            [(EAGLView *)self.view setFramebuffer];
    
            (...opengl draw code...)
    
            [(EAGLView *)self.view presentFramebuffer];
    
        });
    

    When using EAGLContext in a multithreading environment one must be cautious to prevent other threads from accessing it at the same time using:

    @syncronized(context) { ...opengl drawing here...}
    

    and to drain the current dispatch_queue before passing control to another ViewController (through presentViewController:), using:

    dispatch_sync(openGLESContextQueue, ^{});
    

    So, by using these two tricks i was able to just use one EAGLContext across multiple views. One must also pay extra attention to the current state of the EAGLContext. I was having unexpected results because in the first view i had:

    glVertexPointer(2, GL_FLOAT, 0, squareVertices);
    glEnableClientState(GL_VERTEX_ARRAY);
    glColorPointer(4, GL_UNSIGNED_BYTE, 0, squareColors);
    glEnableClientState(GL_COLOR_ARRAY);
    

    In the second view i had completely different drawing code, and i forgot to, of course, use:

    glDisableClientState(GL_VERTEX_ARRAY);
    glDisableClientState(GL_COLOR_ARRAY);
    

    And voilá!

    Thanks :)