2

我想在 中显示一些东西NSOpenGLView,但由于它总共有零字节的文档,并且示例代码与文档一样大和复杂我无法从中获得任何明智。到目前为止,这是我的代码,我ANOpenGLView的代码NSOpenGLView在一个 NIB 中,子类为ANOpenGLView

@implementation ANOpenGLView
@synthesize animationTimer;

// MEM
- (void)dealloc {
  [animationTimer release];

  [super dealloc];
}

// INIT
- (id)initWithFrame:(NSRect)frameRect {
  if (self = [super initWithFrame:frameRect]) {
    NSOpenGLPixelFormatAttribute pixelFormatAttributes[] = {
      NSOpenGLPFADoubleBuffer,
      NSOpenGLPFADepthSize, 32,
      0
    };
    NSOpenGLPixelFormat *format = [[NSOpenGLPixelFormat alloc] initWithAttributes:pixelFormatAttributes];

    [self setOpenGLContext:[[[NSOpenGLContext alloc] initWithFormat:format shareContext:nil] autorelease]];
  }

  return self;
}

- (void)awakeFromNib {

  /* 60 FPS */
  animationTimer = [[NSTimer timerWithTimeInterval:(1.0f/60.0f) target:self selector:@selector(redraw:) userInfo:nil repeats:YES] retain];
  [[NSRunLoop currentRunLoop] addTimer:animationTimer forMode:NSDefaultRunLoopMode];
}

// DRAW
- (void)redraw:(NSTimer*)theTimer {
  [self drawRect:[self bounds]];
}

- (void)drawRect:(NSRect)dirtyRect {
  NSLog(@"Redraw");

  [[self openGLContext] clearDrawable];
  [[self openGLContext] setView:self];
  [[self openGLContext] makeCurrentContext];
  glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
  glDisable(GL_DEPTH_TEST);
  glClear(GL_COLOR_BUFFER_BIT);
  glLoadIdentity();

  glViewport(0, 0, [self frame].size.width, [self frame].size.height);  
  glMatrixMode(GL_PROJECTION); glLoadIdentity();
  glMatrixMode(GL_MODELVIEW); glLoadIdentity();

  glTranslatef(-1.5f, 0.0f, -6.0f);
  glBegin( GL_TRIANGLES );
  glColor3f(1.0f, 0.0f, 0.0f);
  glVertex2f(0.0f, 1.0f);
  glColor3f(0.0f, 1.0f, 0.0f);
  glVertex2f(-1.0f, -1.0f);
  glColor3f(0.0f, 0.0f, 1.0f);
  glVertex2f(1.0f, -1.0f);
  glEnd();

  [[self openGLContext] flushBuffer];
  [NSOpenGLContext clearCurrentContext];
}

@end

我怎样才能让三角形出现?我唯一得到的是一个空白的白色屏幕。


PS我想画2D。


编辑我已经更新了我的代码,这就是我现在所拥有的: 截屏

4

3 回答 3

1

我不确定这是唯一的问题,但是:

  1. 你还没有定义像素格式
  2. 您尚未在代码中设置矩阵
  3. 您尚未设置视口

这里http://www.cocoadev.com/index.pl?NSOpenGLView是一个简短的例子,它几乎是你所需要的,但是当你需要正交以在 2D 空间中渲染时设置了透视矩阵(函数 glOrtho)。在这种情况下,World & View 可以是身份。

由于 2D 是您的目标,因此您不会过多地处理此矩阵,只需设置一次即可。

于 2010-10-17T15:51:10.360 回答
1

一方面,您请求了一个双缓冲上下文,但您从未交换它们,因此您可能总是在绘制看不见的后台缓冲区。glSwapAPPLE()刷新后添加调用。

我也有点不确定你所有的直接[self openGLContext]电话。通常 NSOpenGLView 应该为你处理这些东西,但在这种情况下,你通过drawRect直接从你的计时器调用绕过了视图的设置,所以事情可能有点混乱。

您是否尝试过从[self setNeedsDisplay:YES]您的计时器方法调用并让正常的视图设置发生?我希望这样重绘仍然足够快,它会让生活更轻松......

于 2010-10-18T12:52:46.213 回答
0

编辑:@Peter 是对的,仍然是一个很好的资源,只是不适用于这个问题。

Jeff Lamarche 的 openGL 帖子是一个很好的介绍,其中包含一个项目模板,可以为您处理大部分设置。

http://iphonedevelopment.blogspot.com/2009/05/opengl-es-from-ground-up-table-of.html

于 2010-10-17T15:55:29.787 回答