Here is my init
- (id)initWithFrame: (NSRect)frame
{
self = [super initWithFrame: frame];
if (self)
{
doDraw = NO;
doInit = YES;
NSOpenGLPixelFormatAttribute attrs[] = {
NSOpenGLPFADoubleBuffer,
NSOpenGLPFADepthSize, 32,
0 };
m_PixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes: attrs];
/* Check if initWithAttributes succeeded. */
if( m_PixelFormat == nil )
{
/* initWithAttributes failed. Try to alloc/init with a different list of attributes. */
NSLog(@"ERROR: Pixel Formal NOT supported");
}
m_Context = [[NSOpenGLContext alloc] initWithFormat:m_PixelFormat shareContext:nil];
if( m_Context == nil )
{
/* initWithAttributes failed. Try to alloc/init with a different list of attributes. */
NSLog(@"ERROR: GL Context not created");
} else
{
[m_Context makeCurrentContext];
[m_Context setView:self];
}
}
return self;
}
and here is the drawRect
- (void)drawRect:(NSRect)rect
{
[m_Context makeCurrentContext];
[m_Context setView:self];
if( [self inLiveResize] )
{
// Not sure yet :-)
doDraw = YES;
}
// Only draw if timer fires
if (doDraw)
{
doDraw = NO;
[self draw];
[m_Context flushBuffer];
}
}
I use a Timer to set the doDraw BOOL as not to force a drawRect. I also still need to read more about inLiveResize to see if I can still update the engine or not.
Here I setup the timer and a default scene, this function is called in applicationDidFinishLaunching, as you can see my engine is C++ and I'm finding that mixing ObjC and C++ is working very well.
-(void)startup
{
NSLog(@"startup: Init game...");
[m_Context makeCurrentContext];
[m_Context clearDrawable];
[m_Context setView:self];
// cpp code: Create our demoapp
// This sets up the engine and keeps the custom view clean
default_scene = new DefaultScene();
if( default_scene )
{
// cpp code: init our app, needs active GL context
default_scene->InitEngine( 60.0 );
default_scene->InitGame();
}
// Add engine update timer
m_Timer = [NSTimer scheduledTimerWithTimeInterval:1.0/60.0
target:self selector:@selector(triggerGameDraw:)
userInfo:nil repeats:YES];
}
I'm posting this in the hope it will help someone else having issues with Cocoa/OpenGL.