4.2 Draw Elements
https://www.khronos.org/opengl/wiki/Vertex_Specification#Index_buffers
https://www.khronos.org/opengl/wiki/Vertex_Rendering#Basic_Drawing
https://www.khronos.org/opengl/wiki/Post_Transform_Cache
Complete Source Code:
Graphics.cpp
#include "Graphics.h"
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>
#include <iostream>
#include <vector>
#include "Shader.h"
#include "DrawCommands.h"
using namespace std;
using namespace glm;
struct Vertex
{
vec3 Position;
vec4 Color;
};
uvec2 framebuffersize(0, 0);
GLuint program = 0;
GLuint vertexshader = 0;
GLuint fragmentshader = 0;
GLuint vertexarray = 0;
GLuint vertexbuffer = 0;
GLuint elementbuffer = 0;
DrawElements drawelements_triangle;
bool Graphics::Initialize(unsigned int width, unsigned int height)
{
/* set view port */
Resize(width, height);
/* general settings */
glClearColor(0.3f, 0.3f, 0.3f, 0.0f); /* background gray */
glEnable(GL_DEPTH_TEST);
/* create all objects */
program = glCreateProgram();
vertexshader = glCreateShader(GL_VERTEX_SHADER);
fragmentshader = glCreateShader(GL_FRAGMENT_SHADER);
glGenVertexArrays(1, &vertexarray);
glGenBuffers(1, &vertexbuffer);
glGenBuffers(1, &elementbuffer);
/* shader source */
string vertexshader_source(
"#version 450 core\n"
"layout (location = 0) in vec3 in_position;"
"layout (location = 1) in vec4 in_color;"
"layout (location = 0) uniform mat4 Model = mat4(1);"
"layout (location = 4) uniform mat4 View = mat4(1);"
"layout (location = 8) uniform mat4 Projection = mat4(1);"
"smooth out vec4 color;"
"void main() {"
"mat4 MVP = Projection * View * Model;"
"gl_Position = MVP * vec4(in_position, 1);"
"color = in_color;"
"}"
);
string fragmentshader_source(
"#version 450 core\n"
"smooth in vec4 color;"
"layout (location = 0) out vec4 out_color;"
"void main() {"
"out_color = color;"
"}"
);
/* compile shaders */
if (!CompileShader(vertexshader, vertexshader_source))
return false;
if (!CompileShader(fragmentshader, fragmentshader_source))
return false;
/* link program */
if (!LinkProgram(program, { vertexshader, fragmentshader }))
return false;
/* setup vertexarray */
glBindVertexArray(vertexarray);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast<void*>(offsetof(Vertex, Position)));
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast<void*>(offsetof(Vertex, Color)));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
/* NOTE: the elementbuffer is also part of the vertex array */
/* while the VAO is bound, bind the element buffer */
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer);
glBindVertexArray(0);
/* anf after VAO is setup and unbound, savely unbind the elementbuffer again */
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
/* in OpenGL 4.5, there is a more "modern" way to do that */
/* glVertexArrayElementBuffer(vertexarray, elementbuffer); */
/* ... and another way to specify vertexbuffer: */
/* https://www.khronos.org/opengl/wiki/Vertex_Specification#Separate_attribute_format */
/* create vertices and indices*/
vector<Vertex> vertices;
vector<GLuint> indices;
vertices.push_back({ { 0, 0, 0}, { 1, 0, 0, 1 } });
vertices.push_back({ { 1, 0, 0}, { 0, 1, 0, 1 } });
vertices.push_back({ { 0, 1, 0}, { 0, 0, 1, 1 } });
indices.push_back(0); /* index 0: first triangle vertex */
indices.push_back(1); /* index 1: second triangle vertex */
indices.push_back(2); /* index 2: third triangle vertex */
/* the parameters for a "glDrawElements(...)" call */
drawelements_triangle = { GL_TRIANGLES, 3, GL_UNSIGNED_INT, nullptr };
/* setup vertexbuffer */
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * vertices.size(), vertices.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
/* setup elementbuffer */
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint) * indices.size(), indices.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
/* successfully initialized */
return true;
}
void Graphics::CleanUp()
{
/* destroy all objects */
glDeleteProgram(program);
glDeleteShader(vertexshader);
glDeleteShader(fragmentshader);
glDeleteVertexArrays(1, &vertexarray);
glDeleteBuffers(1, &vertexbuffer);
glDeleteBuffers(1, &elementbuffer);
}
void Graphics::Render(const Scene& scene)
{
float aspectratio= (float)framebuffersize.x / framebuffersize.y;
mat4 View = scene.camera.View();
mat4 Projection = scene.camera.Projection(aspectratio);
/* view and projection matrix */
glProgramUniformMatrix4fv(program, 4, 1, GL_FALSE, value_ptr(View));
glProgramUniformMatrix4fv(program, 8, 1, GL_FALSE, value_ptr(Projection));
/* clear framebuffer */
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
/* draw triangles */
glUseProgram(program);
glBindVertexArray(vertexarray);
for (auto& object : scene.triangles)
{
mat4 Model = object.Transformation();
glUniformMatrix4fv(0, 1, GL_FALSE, value_ptr(Model));
/* render triangle */
Draw(drawelements_triangle);
}
glBindVertexArray(0);
glUseProgram(0);
CheckForGLError();
}
void Graphics::Resize(unsigned int width, unsigned int height)
{
framebuffersize = uvec2(width, height);
glViewport(0, 0, width, height);
}
GLContextInfo Graphics::GetContextInfos()
{
GLContextInfo infos;
glGetIntegerv(GL_MAJOR_VERSION, &infos.Version.Major);
glGetIntegerv(GL_MINOR_VERSION, &infos.Version.Minor);
infos.Version.Driver = (const char*)glGetString(GL_VERSION);
infos.Vendor = (const char*)glGetString(GL_VENDOR);
infos.Renderer = (const char*)glGetString(GL_RENDERER);
infos.Version.ShadingLanguage = (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION);
GLint numberofextensions = 0;
glGetIntegerv(GL_NUM_EXTENSIONS, &numberofextensions);
for (int i = 0; i < numberofextensions; i++)
infos.SupportedExtensions.push_back((const char*)glGetStringi(GL_EXTENSIONS, i));
GLint numberofsupportedglslversions = 0;
glGetIntegerv(GL_NUM_SHADING_LANGUAGE_VERSIONS, &numberofsupportedglslversions);
for (int i = 0; i < numberofsupportedglslversions; i++)
infos.SupportedGLSLVersions.push_back((const char*)glGetStringi(GL_SHADING_LANGUAGE_VERSION, i));
return infos;
}
void Graphics::CheckForGLError()
{
for (GLenum error; (error = glGetError()) != GL_NO_ERROR;)
{
cout << "OpenGL Error: \t";
if (error == GL_INVALID_ENUM)
cout << "GL_INVALID_ENUM";
if (error == GL_INVALID_VALUE)
cout << "GL_INVALID_VALUE";
if (error == GL_INVALID_OPERATION)
cout << "GL_INVALID_OPERATION";
if (error == GL_STACK_OVERFLOW)
cout << "GL_STACK_OVERFLOW";
if (error == GL_STACK_UNDERFLOW)
cout << "GL_STACK_UNDERFLOW";
if (error == GL_OUT_OF_MEMORY)
cout << "GL_OUT_OF_MEMORY";
if (error == GL_INVALID_FRAMEBUFFER_OPERATION)
cout << "GL_INVALID_FRAMEBUFFER_OPERATION";
if (error == GL_CONTEXT_LOST)
cout << "GL_CONTEXT_LOST";
cout << (char)7 << endl; /*play sound*/
cin.get();
}
}