在Mac OSX上绘制OpenGL顶点阵列

时间:2013-11-04 08:01:52

标签: macos cocoa opengl

我对OpenGL相对较新,并希望在cocoa框架内绘制它。我在开发者页面中使用了Apple的示例代码,这非常有效。但是,现在我希望能够从顶点结构中绘制以便掌握该概念。当我为OpenGLView使用以下代码时,我只得到一个黑色的窗口(而不是花哨的彩色三角形......)。

#import "MyOpenGLView.h" 
#include <OpenGL/gl.h>
#include <GLUT/GLUT.h>

@implementation MyOpenGLView

    typedef struct _vertexStruct{
        GLfloat position[2];
        GLubyte color[4];
    } vertexStruct;

- (void)drawRect:(NSRect) bounds
{
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_COLOR_ARRAY);
    drawAnObject();
    glFlush();
}

static void drawAnObject()
{
    const vertexStruct vertices[] = {
        {{0.0f, 1.0f},{1.0, 0.0,0.0,1.0}},
        {{1.0f, -1.0f},{0.0, 1.0,0.0,1.0}},
        {{-1.0f , -1.0f},{0.0, 0.0,1.0,1.0}}
    };

    const GLshort indices[] = {0,1,2};
    glVertexPointer(2, sizeof(vertexStruct),0,&vertices[0].position);
    glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(vertexStruct), &vertices[0].color);
    glDrawElements(GL_TRIANGLES, sizeof(indices)/sizeof(GLshort), GL_SHORT, indices);
}

@end

我在这里缺少什么?

2 个答案:

答案 0 :(得分:1)

  

OS X 10.9表示它正在运行OpenGL 4.1

嗯,这是你的问题。

虽然我不明白为什么你没有收到“访问冲突”错误,因为你应该因为你在OpenGL中使用了弃用的函数。

以下函数是您正在使用的OpenGL 3.1版中不推荐使用的一些函数。

  • glEnableClientState()
  • glVertexPointer()
  • glColorPointer()

为什么不推荐使用所有gl*Pointer()函数的原因是因为它们是固定功能管道的一部分。现在一切都是着色器,现在你假设VAOsVBOs(以及IBO)一起使用。

与VAO一起使用的功能是。

创建

  • glEnableVertexAttribArray()
  • glVertexAttribPointer()

渲染

  • glBindVertexArray()
  • (4,8)
  • glDrawElements()

是的,仍然使用glDrawArrays()glDrawElements(),当您需要为VAO创建和绑定VBO时,您仍然可以像以前一样使用它。

答案 1 :(得分:0)

glVertexPointer(2, sizeof(vertexStruct),0,&vertices[0].position);

应该是

glVertexPointer(2, GL_FLOAT,sizeof(vertexStruct),0);

这指定要读取2个浮点数,以12个字节为单位,从0开始(块中的前2个浮点数)