简体   繁体   中英

Draw OpenGL Vertex Array on Mac OSX

I am relatively new to OpenGL and would like to get it to draw within the cocoa framework. I played around with apple's example code from the developer page, and this worked quite well. However, now I would like to be able to draw from a vertex struct in order to get to grips with that concept. When I use the following code for my OpenGLView, I just get a black Window (instead of a fancy colored triangle...).

#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

What am I missing here?

OS X 10.9 says it's running OpenGL 4.1

Well, right there is your problem.

Though I don't understand why you aren't getting an "Access violation" error, because you should because you're using deprecated functions in OpenGL.

The following functions are some of the functions deprecated in OpenGL version 3.1, which you're using.

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

The reason behind why all the gl*Pointer() functions are deprecated is because they are a part of the fixed-function pipeline. Everything is shader based now and now you're suppose to use VAOs with VBOs (and IBOs).

The functions which goes along with VAOs are.

Creating

  • glEnableVertexAttribArray()
  • glVertexAttribPointer()

Rendering

  • glBindVertexArray()
  • glDrawArrays()
  • glDrawElements()

Yes, glDrawArrays() and glDrawElements() are still used and when you need to create and bind the VBOs for the VAOs, you still do that in the same way as before.

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

should be

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

This specifies that 2 floats are to be read, in blocks of 12 bytes, starting at 0(the first 2 floats in the block)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM