2006/02/25
Quartz Musings (III): OpenGL Context
Here is my sample code. I'm inheriting from the AppKit-provided NSOpenGLView
for convenience (the super class defines some convienence methods and behaviors). But it should
be noted that you can associate an OpenGL context with any NSView (there's some sample code).
A side note: you can also very easily create a texture from a NSView.
@interface TSGLWorldView : NSOpenGLView
{
CGContextRef context;
}
@end
@implementation TSGLWorldView
- (void)drawRect:(NSRect)rect
{
if (context==NULL)
{
CGSize size = CGSizeMake([self bounds].size.width,
[self bounds].size.height);
CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB();
context = CGGLContextCreate([[self openGLContext] CGLContextObj],
size, cs);
}
/* My drawing code, using 'context' */
CGContextFlush(context);
}
- (void)update
{
glViewport(0, 0,[self bounds].size.width,[self bounds].size.height );
if (context!=NULL)
CGGLContextUpdateViewportSize (context,
CGSizeMake([self bounds].size.width,[self bounds].size.height));
[super update];
}
@end
The update method is here to handle window resizing, by keeping in sync the view bounds, gl viewport
and CGGLContext. Again, no change in my drawing code.
Although this is a very cool addition to the CoreGraphics arsenal, I have to say that it is apparently one of the less common uses for CoreGraphics, can be occasionally buggy and might be made obsolete in the future if Quartz 2D Extreme is some time enabled by default, making basically everything rendered through an OpenGL pipe, without having to use CGGLContext explicitely (but you can play with it right now through QuartzDebug).