Creating an OpenGL Context
Introduction
OpenGL is a state machine for updating content of a framebuffer. The openGL state machine controls the transformation of primitives, images and bitmaps into pixels. The openGL state is collected into a data structure called Graphics Context. A Graphic Context is allocated/deallocated by a window system. Rendering on a screen can not occur if a Context has not been allocated.
In this post, you will learn how to allocate a Context in OpenGL ES for mobile devices.
Allocating an OpenGL ES Context
In iPhone and iPad devices, an EAGLContext object manages all rendering information. Line 1 in listing 1, allocates memory for the EAGLContext object, it then initializes the context by calling the initWithAPI method. The method initWithAPI initializes and returns a newly allocated rendering context with the specified version of OpenGL ES. In line 1, the context is initialized with OpenGL ES version 3.0.
The context is then checked if it was successfully created (line 2). If so, the newly created context is set to current with the method setCurrentContext (line 4). After this, the context is ready to accept OpenGL commands.
Note: In order for OpenGL ES commands to execute on the newly created context, you must first make the context current by caling the method setCurrentContext.
Listing 1. Allocating an OpenGL Context.
- (void)viewDidLoad
{
[super viewDidLoad];
//1, Allocate a EAGLContext object and initialize a context with a specific version.
self.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES3];
//2. Check if the context was successful
if (!self.context) {
NSLog(@"Failed to create ES context");
}
//3. Set the view's context to the newly created context
GLKView *view = (GLKView *)self.view;
view.context = self.context;
//4. Make the newly created context the current context.
[EAGLContext setCurrentContext:self.context];
//Context is ready
}