1

I am starting to learn OpenGL; I tried to display a few number of vertices in order to render a polygon. My display function succeeds if I use the following code:

glBegin(GL_POLYGON);
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(0.5, 0.0, 0.0);
glVertex3f(0.5, 0.5, 0.0);
glVertex3f(0.0, 0.5, 0.0);
glEnd();

But I am unable to display an array of vertices by using glDrawArrays. Following is the complete program (developed on OS X).

#include <OpenGL/gl.h>
#include <OpenGl/glu.h>

#ifdef __APPLE__
  #include <GLUT/glut.h>
#else
  #include <GL/glut.h>
#endif

#ifdef __APPLE__
  #define glGenVertexArrays glGenVertexArraysAPPLE
  #define glBindVertexArrays glBindVertexArraysAPPLE
  #define glBindVertexArray glBindVertexArrayAPPLE
  #define glDeleteVertexArrays glDeleteVertexArraysAPPLE
#endif

/** Triangle vertices. */
GLuint handleVertex;
const float vertex[] = 
{
  0.75f, 0.75f, 0.0f, 1.0f,
  0.75f, -0.75f, 0.0f, 1.0f,
  -0.75f, -0.75f, 0.0f, 1.0f,
};

static void init_vertices()
{
  glGenBuffers(1, &handleVertex);
  glBindBuffer(GL_ARRAY_BUFFER, handleVertex);
  glBufferData(GL_ARRAY_BUFFER, sizeof(vertex), vertex, GL_STATIC_DRAW);
  glBindBuffer(GL_ARRAY_BUFFER, 0);
}

static void display()
{
  glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
  glClear(GL_COLOR_BUFFER_BIT);

  /*glBegin(GL_POLYGON);
  glVertex3f(0.0, 0.0, 0.0);
  glVertex3f(0.5, 0.0, 0.0);
  glVertex3f(0.5, 0.5, 0.0);
  glVertex3f(0.0, 0.5, 0.0);
  glEnd();*/

  glBindBuffer(GL_ARRAY_BUFFER, handleVertex);
  glEnableVertexAttribArray(0);
  glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);
  glDrawArrays(GL_TRIANGLES, 0, 3);
  glDisableVertexAttribArray(0);

  glutSwapBuffers();
  glFlush();
}

int main(int argc, char** argv)
{
  glutInit(&argc, argv);

  unsigned displayMode = GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH | GLUT_STENCIL;
  glutInitDisplayMode(displayMode);
  glutInitWindowSize(500, 500); 
  glutInitWindowPosition(300, 200);
  glutCreateWindow(argv[0]);

  init_vertices();

  glutDisplayFunc(display); 
  glutMainLoop();

  return 0;
}

I am wondering what I am doing wrong.

Nick
  • 10,309
  • 21
  • 97
  • 201
  • 2
    Where are your shaders? You can't use generic vertex attributes (`glVertexAttribPointer()` and friends) without them. – genpfault Feb 20 '15 at 21:06
  • Well, on my machine, your program works very well. If Iḿ not wrong, apple don't have a compatible mode and you will need to instantiate a basic shader (vertex and fragment) – Amadeus Feb 20 '15 at 23:42
  • @genpfault: the generic vertex attribute 0 is guaranteed to alias the builtin "vertex" attribute of the fixed-function pipeline, as per the spec. – derhass Feb 21 '15 at 01:56
  • @PequiAmarelo: Apple supports "legacy GL" up to GL 2.1. As this code does not request a >= 3.2 core profile, the legacy context should be created. And the code should actually work. – derhass Feb 21 '15 at 01:59

0 Answers0