Skip to content

Instantly share code, notes, and snippets.

@TomMinor
Created May 26, 2015 02:18
Show Gist options
  • Save TomMinor/9ba51bff313da121699f to your computer and use it in GitHub Desktop.
Save TomMinor/9ba51bff313da121699f to your computer and use it in GitHub Desktop.
#define BUFFER_OFFSET(offset) ((GLvoid*) NULL + offset)
#define NumberOf(array) (sizeof(array)/sizeof(array[0]))
void main()
{
// Temporary vertex data
GLfloat cubeVerts[][3] = {
{ -1.0, -1.0, -1.0 },
{ -1.0, -1.0, 1.0 },
{ -1.0, 1.0, -1.0 },
{ -1.0, 1.0, 1.0 },
{ 1.0, -1.0, -1.0 },
{ 1.0, -1.0, 1.0 },
{ 1.0, 1.0, -1.0 },
{ 1.0, 1.0, 1.0 },
};
// Temporary colour data
GLfloat cubeColors[][3] = {
{ 0.0, 0.0, 0.0 },
{ 0.0, 0.0, 1.0 },
{ 0.0, 1.0, 0.0 },
{ 0.0, 1.0, 1.0 },
{ 1.0, 0.0, 0.0 },
{ 1.0, 0.0, 1.0 },
{ 1.0, 1.0, 0.0 },
{ 1.0, 1.0, 1.0 },
};
// Temporary index data
GLubyte cubeIndices[] = {
0, 1, 3, 2,
4, 6, 7, 5,
2, 3, 7, 6,
0, 4, 5, 1,
0, 2, 6, 4,
1, 5, 7, 3
};
enum {
Vertices = 0,
Colors = 1,
Elements = 2,
NumVBOs = 3
};
/* ---------------------------- Setup vertex array and buffers ---------------------------- */
// Store our buffers
GLuint buffers[NumVBOs];
// Store our VAO
GLuint VAO;
// Create a VAO
glGenVertexArrays(1, &VAO);
// Make the VAO current
glBindVertexArray(VAO);
// Generate enough buffers to satisfy NumVBOs
glGenBuffers(NumVBOs, buffers);
/* ---------------------------- Pass Vertex Data ---------------------------- */
// Set active VBO to vertex
glBindBuffer(GL_ARRAY_BUFFER, buffers[Vertices]);
// Pass vertex data to GPU
glBufferData(GL_ARRAY_BUFFER, sizeof(cubeVerts), cubeVerts, GL_STATIC_DRAW);
// Vertex data starts at the beginning of it's buffer
glVertexPointer(3, GL_FLOAT, 0, BUFFER_OFFSET(0));
// Enable vertex array drawing
glEnableClientState(GL_VERTEX_ARRAY);
/* ---------------------------- Pass Colour Data ---------------------------- */
// Set active VBO to colours
glBindBuffer(GL_ARRAY_BUFFER, buffers[Colors]);
// Pass colour data to GPU
glBufferData(GL_ARRAY_BUFFER, sizeof(cubeColors), cubeColors, GL_STATIC_DRAW);
// Colour data starts at the beginning of it's buffer
glColorPointer(3, GL_FLOAT, 0, BUFFER_OFFSET(0));
// Enable colour array drawing
glEnableClientState(GL_COLOR_ARRAY);
/* ---------------------------- Pass Index Data ---------------------------- */
// Set the active VBO to the cube index data (for DrawElements)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers[Elements]);
// Pass index data to GPU
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(cubeIndices), cubeIndices, GL_STATIC_DRAW);
// Render loop
while(true)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Make VAO active
glBindVertexArray(VAO);
// Draw
glDrawElements(GL_QUADS, NumberOf(cubeIndices), GL_UNSIGNED_BYTE, BUFFER_OFFSET(0));
// Make VAO unactive
glBindVertexArray(0);
glutSwapBuffers();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment