NSOpengl视图不起作用

时间:2018-06-17 20:00:33

标签: objective-c macos cocoa opengl

您好我一直在尝试使用NSOpenGLView在cocoa中创建我的第一个opengl“app”。我想用蓝色清除背景并绘制红点但视图是白色的。并且它不会绘制红点。也许我应该使用核心视频来循环刷新它。这是“OpenGL Superbible”一书中的代码,所以我认为它是可可的错误。

#import <Cocoa/Cocoa.h>

@interface View : NSOpenGLView

@end

//---------------------------------

#import "View.h"
#include <OpenGL/gl3.h>

@implementation View

GLuint rendering_program;
GLuint VAO;


-(void)awakeFromNib{

    NSOpenGLPixelFormatAttribute pixelFormatAttributes[] =
    {
        NSOpenGLPFAOpenGLProfile, NSOpenGLProfileVersion3_2Core,
        NSOpenGLPFAColorSize    , 24                           ,
        NSOpenGLPFAAlphaSize    , 8                            ,
        NSOpenGLPFADoubleBuffer ,
        NSOpenGLPFAAccelerated  ,
        NSOpenGLPFANoRecovery   ,
        0
    };
    NSOpenGLPixelFormat *pixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:pixelFormatAttributes] ;
    NSOpenGLContext* glc = [[NSOpenGLContext  alloc]initWithFormat:pixelFormat shareContext:nil];
    [self setOpenGLContext:glc];


}


-(void)prepareOpenGL{
    GLuint vs;
    GLuint fs;
    const GLchar*vss[] = {
      "#version 330 core \n"
    "void main (void)\n"
    "{\n"
    "gl_Position = vec4(0.0,0.0,0.5,1.0);\n"
    "}\n"

    };

    vs = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vs, 1, vss, 0);
    glCompileShader(vs);
    int s;
    glGetShaderiv(vs, GL_COMPILE_STATUS, &s);
    if(!s)printf("ok");

    const GLchar*fss[] = {
        "#version 330 core \n"
        "out vec4 color;"
        "void main (void)\n"
        "{\n"
        "color = vec4(1.0,0.0,0.0,1.0);\n"
        "}\n"

    };

    fs = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fs, 1,fss, 0);
    glCompileShader(fs);
    int k;
    glGetShaderiv(fs, GL_COMPILE_STATUS, &k);
    if(!k)printf("okkk");

    rendering_program = glCreateProgram();
    glAttachShader(rendering_program,vs );
    glAttachShader(rendering_program,fs );
    glLinkProgram(rendering_program);
    int n;
    glGetProgramiv(rendering_program, GL_LINK_STATUS, &n);
    glDeleteShader(vs);
    glDeleteShader(fs);
    glGenVertexArrays(1, &VAO);
    glBindVertexArray(VAO);













}

-(void)drawRect:(NSRect)dirtyRect{
    glPointSize(40);
    glClearColor(0, 0, 1, 1);
    glClear(GL_COLOR_BUFFER_BIT);
    glUseProgram(rendering_program);
    glDrawArrays(GL_POINTS, 0, 1);
    glFlush();


}

@end

以下是截图: enter image description here

1 个答案:

答案 0 :(得分:1)

由于您正在使用双缓冲(NSOpenGLPFADoubleBuffer),因此您必须在渲染后交换缓冲区:

[[self openGLContext] flushBuffer]

如果没有双缓冲(单缓冲),glFlush()就足够了 另见glFlush() vs [[self openGLContext] flushBuffer]