NSOpenGLView Какао (снова) - PullRequest
       36

NSOpenGLView Какао (снова)

0 голосов
/ 22 марта 2011

Я новичок во всей макарии Cocoa / Objective-C (но у меня годы C / C ++ на * nix).

Я пытаюсь создать базовое приложение Какао, заполненное NSOpenGLView. У меня есть:

chink.mm

#import <OpenGL/gl.h>
#import "chink.h"

@implementation chinkView

@synthesize window;

- (void) applicationDidFinishLaunching : (NSNotification *)aNotification {
    NSLog(@"Danger, Will Robinson! Danger!");
}

- (void) dealloc
{
    [window release];
    [super dealloc];
}

@end

и chink.h

@interface chinkView : NSOpenGLView {

    NSWindow *window;

}


@property (assign) NSWindow *window;


@end

У меня есть один .xib настроенный как

https://skitch.com/cront/ri625/chinkxib

, где 'Chink View' установлен как делегат для Window и File Owner.

Я получаю ошибку «Недопустимое рисование» (даже до того, как приложение завершит запуск), что, насколько я понимаю, означает, что оно пытается создать представление opengl перед окном (хотя я, вероятно, ошибаюсь).

Я хочу решить эту проблему, создав окно и настроив в нем представление opengl. Как только это сделано, у меня нет абсолютно никаких проблем с написанием OGL (как я уже сказал, я знаю C ++), но все эти вызовы NS, gunk, мне чужды.

Я не ищу ответы «почему бы вам не сделать это в SDL / GLUT», пожалуйста. Просто код, чтобы заставить его правильно создать окно.

1 Ответ

0 голосов
/ 24 марта 2011

Хорошо, поэтому я уволил этот подход.

Прошел длинный маршрут и изменил на это:

chink.mm

#import <Cocoa/Cocoa.h>
#import <OpenGL/OpenGL.h>
#import <OpenGL/gl.h>
#import <OpenGL/glu.h>

#import "chink.h"


@implementation chinkNS

- (id)initWithFrame:(NSRect)frameRect
{
    NSOpenGLPixelFormat * pixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:(NSOpenGLPixelFormatAttribute[]) {
        NSOpenGLPFAWindow,
        NSOpenGLPFADoubleBuffer,
        NSOpenGLPFADepthSize, 32,
        nil
    }];
    if(pixelFormat == NULL)
        NSLog(@"pixelFormat == NULL");
    [pixelFormat autorelease];

    self = [super initWithFrame:frameRect pixelFormat:pixelFormat];
    if(self == NULL) {
        NSLog(@"Could not initialise self");
        return NULL;
    }

    [[self openGLContext] makeCurrentContext];
    [self initGL];

    return self;
}

- (void)awakeFromNib
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowWillMiniaturize:) name:NSWindowWillMiniaturizeNotification object:[self window]];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidMiniaturize:) name:NSWindowDidMiniaturizeNotification object:[self window]];

    animationTimer = [NSTimer scheduledTimerWithTimeInterval:1/60.0 target:self selector:@selector(timerFired) userInfo:NULL repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:animationTimer forMode:NSEventTrackingRunLoopMode];
    [[NSRunLoop currentRunLoop] addTimer:animationTimer forMode:NSModalPanelRunLoopMode];
    lastTime = [[NSDate date] timeIntervalSince1970];
}

- (void)drawRect:(NSRect)frame
{

    NSLog(@"Chink is up and running. Let's do this thing!");

    glClearColor(0.0, 0.0, 0.0, 0.0);
    glClear(GL_COLOR_BUFFER_BIT);
    glColor3f(1.0, 1.0, 1.0);
    glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0); 
    glFlush();

    [self drawGL];
    [[self openGLContext] flushBuffer];



}

#pragma mark OpenGL

- (void)initGL { }

- (void)reshapeGL { }

- (void)drawGL { }

- (void)animate:(float)dt { }

#pragma mark Event Handling

- (void)timerFired
{
    NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
    [self animate:currentTime-lastTime];
    lastTime = currentTime;
}


#pragma mark Loose ends

- (void)setFrame:(NSRect)frame
{
    [super setFrame:frame];
    [self reshapeGL];
}

// To get key events
- (BOOL)acceptsFirstResponder
{
    return YES;
}


@end

и chink.h

@interface chinkNS : NSOpenGLView
{

    NSTimer * animationTimer;
    NSTimeInterval lastTime;

}

- (void)initGL;
- (void)reshapeGL;
- (void)drawGL;
- (void)animate:(float)dt;

@end

Те же настройки в.xib за исключением того, что это стандартный NSView, который подклассирует мое представление opengl.

Я надеялся на более простую, более элегантную настройку, как указано выше, но вы не можете выиграть их все.

Закрыто.

...