February 11, 2014

Simplest VBO Program

For our class assignment we can use OpenGL VBO's for extra credit.  They're a lot more difficult to set up than glBegin() and glEnd() but they're supposed to be a lot more efficient.

Scouring the web for simple examples never really turns up any simple examples.. people always have to add fancy stuff.  Which is cool, except if I don't understand the basics, how am I going to understand all the more complicated things?

Here is an OpenGL program, using VBO's, that outputs a single point.  That's it.  Caused me a lot of trouble.

#include <stdio.h>
#include <stdlib.h>
#include <GL/glew.h>
#include <GL/glut.h>
#include <GL/gl.h>
#include <GL/glext.h>

float vertices[] = {0.0, 0.0};
GLubyte indices[1]= {0};

GLuint vboHandle[1];
GLuint indexVBO;
void InitVBO() {
  indices[0] = 0;

  glGenBuffers(1, vboHandle); // (1)
  glBindBuffer(GL_ARRAY_BUFFER, vboHandle[0]); // (2)
  glBufferData(GL_ARRAY_BUFFER, sizeof(float)*2, vertices, GL_STATIC_DRAW);
  glBindBuffer(GL_ARRAY_BUFFER, 0);

  glGenBuffers(1, &indexVBO);
  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexVBO);
  glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLubyte), indices, GL_STATIC_DRAW);
  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}

void display()
{
  glClear(GL_COLOR_BUFFER_BIT);
  glColor4f(1,1,0,1);
  glPointSize(10);

  glBindBuffer(GL_ARRAY_BUFFER, vboHandle[0]);
  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexVBO);

  glEnableClientState(GL_VERTEX_ARRAY);
  glVertexPointer(2, GL_FLOAT, 0, (char*)NULL + 0);
  glDrawElements(GL_POINTS, 1, GL_UNSIGNED_BYTE, (char*)NULL + 0);

  glDisableClientState(GL_VERTEX_ARRAY);

  glFlush();
}


///////////////////////////////////////////////////////////////

int main(int argc, char** argv)
{
  glutInit(&argc, argv);
  glutCreateWindow("simple");
  glewInit();
  glutDisplayFunc(display);

  InitVBO();
  glutMainLoop();
}

Don't fully understand any of it yet.  But hopefully I will soon.

The much anticipated image:

BAM.

Not quite worth it for all the trouble needed to hook it up.. but I'm sure for more objects it'll scale a lot better.