macoscocoaopenglnsviewnsopenglview

Rendering OpenGL within an NSView subclass does not render


I have existing code that uses an NSOpenGLView. I would like to instead utilise a subclassed NSView controller, and I'm hiting a few walls (not least since OpenGL is long deprecated on Mac. I am persisting still).

I figured to explore this example code from Apple, which seems like it would cover my needs quite well as reference. The left window shows an NSOpenGLView while the right window shows an NSView approach. Better yet, this example code still compiles and runs!

Unfortunately, this example also fails to render the subclassed NSView, while the NSOpenGLView continues to render just fine.

Here's how it renders on an M2 Mac.. enter image description here

While I appreciate that Apple has long ago deprecated OpenGL on Mac, I would love to be able to follow this sample as a reference for the NSView aspect.

I can see that the only code being hit within 'MyOpenGLView' is the initWithFrame method. The class does not appear to receive any subsequent messages at all.

It's quite possible this is a simple fix for this example, and it just might help me identify what I'm doing wrong in my own code..

Would greatly appreciate any pointers to getting this example to behave correctly (or even just to get the right side rendering instead of the left).


Solution

  • The demo can be made to work, but requires changing several lines of code in MyOpenGLView.m. I'm not sure that I can recall every change that was made; basically correct every error message and REM out things that aren't essential, eg filling in the text fields. Method -lockFocus was never called, so I copy/pasted the following two lines of code to the bottom of -initWithFrame() which was called:

    [self prepareOpenGL];
    [[self openGLContext] setView:self];
    

    Also when it uses [self bounds].width and .height in method -drawView substitute the actual values as shown below:

    glViewport(0,0,640,400);
    [renderer makeOrthographicForWidth:640 height:400];
    
    

    Output: enter image description here