For drawing two squares we need to make two things. First, add extra 3 vertices
// We initialize a buffer on CPU
float vertices[]{
-0.5f, -0.5f, // 0
0.5f, -0.5f, // 1
0.5f, 0.5f, // 2
0.5f, 0.5f, // 3
-0.5f, -0.5f, // 4
-0.5f, 0.5f // 5
};
and the second one is to add those extra vertices to the draw command
// we draw two triangle
glDrawArrays(GL_TRIANGLES, 0, 6);
As you can see these two triangles have adjacent 2 vertices. Instead of supplying these two extra vertices, we can supply a list for the order of vertices. So OpenGL can use the list for drawing triangles. We call the list as Index Buffer
Index Buffer
// |>----------<>----------<>----------<>----------<>----------<|
// |> DEFINE VERTICES <|
// |>----------<>----------<>----------<>----------<>----------<|
float vertices[]{
-0.5f, -0.5f, // 0 - bottom left
0.5f, -0.5f, // 1 - bottom right
0.5f, 0.5f, // 2 - top right
-0.5f, 0.5f, // 3 - top left
};
unsigned int indices[] = { // note that we start from 0!
0, 1, 2, // first Triangle
0, 2, 3 // second Triangle
};
unsigned int VBO;
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
unsigned int EBO;
glGenBuffers(1, &EBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
// we give meanings to our data. Because it is just a bunch of byte
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// |>----------<>----------<>----------<>----------<>----------<|
// |> RENDER LOOP <|
// |>----------<>----------<>----------<>----------<>----------<|
while (!glfwWindowShouldClose(window)) {
glClearColor(0.2f, 0.2f, 0.2f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// we draw two triangle
// glDrawArrays(GL_TRIANGLES, 0, 6);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glfwSwapBuffers(window);
glfwPollEvents();
}
Leave a Reply