How to draw to NSOpenGLView from a view controller object?

3.6k views Asked by At

In IB I placed an NSOpenGLView instance into the window.

I have all of my drawing code inside a custom NSViewController like so:

// MyOpenGLViewController.h

@interface MyOpenGLViewController : NSViewController 
{
    IBOutlet NSOpenGLView *glView;  
}

// MyOpenGLViewController.m

-(void)awakeFromNib
{
    [self drawFrame];
}

-(void)drawFrame
{
    [[glView openGLContext] makeCurrentContext];
    glClearColor(0, 0, 0, 1);
}

Everything is linked up and "drawFrame" gets called but I don't get anything on the screen. It's always white. What should I be checking for?

3

There are 3 answers

2
Mark On BEST ANSWER

Typically one subclasses NSOpenGLView and installs a timer to update your data model and if anything changes then draw the changes. The controller shouldn't be doing the drawing. Apple has some good documentation on getting something working. Start with the OpenGl Programming Guide for Mac OS X.

I seem to remember a bug with using the NSOpenGLView object in Interface Builder. What I always do is add a generic NSObject where you want the view and set its class to be your NSOpenGLView subclass.

1
genpfault On

Not sure about cocoa, but glClearColor() just sets some state. glClear(GL_COLOR_BUFFER_BIT) will actually clear the framebuffer.

0
JFT On

A bit late to answer, but as I was wondering the same thing and found out this thread I thought I should update it with some missing bits :P

As someone else mentioned glClearColor() only set an attribute, the actual clear must be done with glClear (note that in addition to the color buffer it can also clear the Z-Buffer, accumulator & stencil).

Finally your OpenGL commands stream need to be actually flushed. This can be done with either glFlush(), if you are single buffered, or glSwapAPPLE() if you are double-buffered.