Here is an example on how to create a OpenGL debug context (using GLFW). This is necessary if you want to enable OpenGL debug output:
https://www.khronos.org/opengl/wiki/Debug_Output
Main.cpp
#define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <iostream>
#include <vector>
#include "Graphics.h"
using namespace std;
using namespace glm;
struct DebugUserParams {
bool ShowNotifications = true;
} debuguserparams;
void error_callback(int error, const char* description)
{
cout << "GLFW Error: " << description << endl;
cin.get();
}
void drop_callback(GLFWwindow* window, int pathcount, const char** paths)
{
for (unsigned int i = 0; i < pathcount; i++)
cout << "dropped file: " << paths[i] << endl;
}
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
Graphics::ResizeFramebuffer(uvec2(width, height));
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (action == GLFW_PRESS)
{
if (key == GLFW_KEY_ESCAPE)
glfwSetWindowShouldClose(window, GLFW_TRUE);
}
}
void cursor_position_callback(GLFWwindow* window, double xpos, double ypos)
{
}
void mouse_button_callback(GLFWwindow* window, int button, int action, int mods)
{
if (action == GLFW_PRESS)
{
if (button == GLFW_MOUSE_BUTTON_RIGHT)
{
}
}
}
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
}
/* debug */
void APIENTRY OpenGLDebugCallback(
GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userparam)
{
/* debug user params */
DebugUserParams* params = (DebugUserParams*)userparam;
/* filter out unnecessary warnings */
if (!params->ShowNotifications)
if (severity == GL_DEBUG_SEVERITY_NOTIFICATION)
return;
/* source */
string str_source;
if (source == GL_DEBUG_SOURCE_API) str_source = "API";
if (source == GL_DEBUG_SOURCE_WINDOW_SYSTEM) str_source = "Window System";
if (source == GL_DEBUG_SOURCE_SHADER_COMPILER) str_source = "Shader Compiler";
if (source == GL_DEBUG_SOURCE_THIRD_PARTY) str_source = "Third Party";
if (source == GL_DEBUG_SOURCE_APPLICATION) str_source = "Application";
if (source == GL_DEBUG_SOURCE_OTHER) str_source = "Other";
/* type */
string str_type;
if (type == GL_DEBUG_TYPE_ERROR) str_type = "Error";
if (type == GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR) str_type = "Deprecated Behavior";
if (type == GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR) str_type = "Undefined Behavior";
if (type == GL_DEBUG_TYPE_PORTABILITY) str_type = "Portability";
if (type == GL_DEBUG_TYPE_PERFORMANCE) str_type = "Performance";
if (type == GL_DEBUG_TYPE_MARKER) str_type = "Marker";
if (type == GL_DEBUG_TYPE_PUSH_GROUP) str_type = "Push Group";
if (type == GL_DEBUG_TYPE_POP_GROUP) str_type = "Pop Group";
if (type == GL_DEBUG_TYPE_OTHER) str_type = "Other";
/* severity */
string str_severity;
if (severity == GL_DEBUG_SEVERITY_HIGH) str_severity = "High";
if (severity == GL_DEBUG_SEVERITY_MEDIUM) str_severity = "Medium";
if (severity == GL_DEBUG_SEVERITY_LOW) str_severity = "Low";
if (severity == GL_DEBUG_SEVERITY_NOTIFICATION) str_severity = "Notification";
/* print message */
cout << "OpenGL Debug Message:" << endl;
cout << "----------------------------------" << endl;
cout << "ID: \t\t" << id << endl;
cout << "Source: \t" << str_source << endl;
cout << "Type: \t\t" << str_type << endl;
cout << "Severity: \t" << str_severity << endl;
cout << "Message: \t" << message << endl;
cout << "----------------------------------" << endl << endl;
}
int main(int argc, char* argv[])
{
bool fullscreen = false;
bool debugcontext = true;
bool compatibilityprofilecontext = false;
bool vsync = true;
/* Initialize GLFW */
if (!glfwInit())
return 1;
/* Create a window and its OpenGL context */
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, debugcontext ? GLFW_TRUE : GLFW_FALSE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, compatibilityprofilecontext ? GLFW_TRUE : GLFW_FALSE);
glfwWindowHint(GLFW_OPENGL_PROFILE, compatibilityprofilecontext ? GLFW_OPENGL_COMPAT_PROFILE : GLFW_OPENGL_CORE_PROFILE);
GLFWmonitor* monitor = fullscreen ? glfwGetPrimaryMonitor() : NULL;
GLFWwindow* window = glfwCreateWindow(800, 600, "OpenGL", monitor, NULL);
if (!window)
{
glfwTerminate();
return 1;
}
/* Make the window's context current */
glfwMakeContextCurrent(window);
/* Set V-sync */
glfwSwapInterval(vsync ? 1 : 0);
/* Set callback functions */
glfwSetErrorCallback(error_callback);
glfwSetDropCallback(window, drop_callback);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
glfwSetKeyCallback(window, key_callback);
glfwSetCursorPosCallback(window, cursor_position_callback);
glfwSetMouseButtonCallback(window, mouse_button_callback);
glfwSetScrollCallback(window, scroll_callback);
/* Initialize GLEW */
if (glewInit() != GLEW_OK)
{
glfwTerminate();
return 2;
}
/* Register debug callback if debug context is available */
GLint contextflags = 0;
glGetIntegerv(GL_CONTEXT_FLAGS, &contextflags);
if (contextflags & GL_CONTEXT_FLAG_DEBUG_BIT)
{
glEnable(GL_DEBUG_OUTPUT);
glDebugMessageCallback(OpenGLDebugCallback, &debuguserparams);
}
/* Initialize graphics */
int width = 0, height = 0;
glfwGetFramebufferSize(window, &width, &height);
if (!Graphics::Initialize(uvec2(width, height)))
{
glfwTerminate();
return 3;
}
/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
/* Render here */
Graphics::Render();
/* Swap front and back buffers */
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
/* Clean up graphics */
Graphics::CleanUp();
glfwTerminate();
return 0;
}
Graphics.h
#pragma once
#define GLEW_STATIC
#define GLM_ENABLE_EXPERIMENTAL
#include <GL/glew.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/transform.hpp>
#include <string>
#include <vector>
#define CheckForGLErrors Graphics::CheckForGLErrors__(__FILE__, __LINE__)
struct Vertex
{
glm::vec3 Position = { 0, 0, 0 };
glm::vec3 Normal = { 0, 0, 0 };
glm::vec2 Texcoord = { 0, 0 };
};
struct Mesh
{
std::vector<Vertex> Vertices;
std::vector<glm::uvec3> Faces;
};
struct MeshRef
{
GLuint BaseVertex = 0;
GLuint BaseElement = 0;
GLuint ElementCount = 0;
};
namespace Graphics
{
bool Initialize(const glm::uvec2& framebuffer_size);
void Render();
void CleanUp();
int AddMesh(const Mesh& mesh);
void ResizeFramebuffer(const glm::uvec2& framebuffer_size);
std::string LoadTextFile(const std::string& filepath);
std::string ShaderTypeName(GLuint shader);
bool CompileShader(GLuint shader, const std::string& sourcecode);
std::string ShaderInfoLog(GLuint shader);
bool LinkProgram(GLuint program, const std::vector<GLuint>& shaders);
std::string ProgramInfoLog(GLuint program);
void CheckForGLErrors__(const char* file, unsigned int line);
}
Graphics.cpp
#include "Graphics.h"
#include <iostream>
#include <fstream>
using namespace std;
using namespace glm;
GLuint program = 0;
GLuint vertexarray = 0;
GLuint vertexbuffer = 0;
GLuint elementbuffer = 0;
vector<Vertex> vertices;
vector<GLuint> elements;
vector<MeshRef> mesh_refs;
int meshref_quad = -1;
bool Graphics::Initialize(const glm::uvec2& framebuffer_size)
{
/* create all objects */
program = glCreateProgram();
glCreateVertexArrays(1, &vertexarray);
glCreateBuffers(1, &vertexbuffer);
glCreateBuffers(1, &elementbuffer);
/* setup framebuffer */
ResizeFramebuffer(framebuffer_size);
/* setup program */
//----------------------------------------
string vertexshader_source = {
"#version 460 core\n"
"layout (location = 0) uniform mat4 projection = mat4(1);"
"layout (location = 4) uniform mat4 modelview = mat4(1);"
"layout (location = 0) in vec3 in_position;"
"layout (location = 1) in vec3 in_normal;"
"layout (location = 2) in vec2 in_texcoord;"
"out VS_FS {"
"smooth vec3 position;"
"smooth vec3 normal;"
"smooth vec2 texcoord;"
"} vs_out;"
"void main() {"
"gl_Position = projection * modelview * vec4(in_position, 1);"
"vs_out.position = (modelview * vec4(in_position, 1)).xyz;"
"vs_out.normal = (modelview * vec4(in_normal, 0)).xyz;"
"vs_out.texcoord = in_texcoord;"
"}"
};
string fragmentshader_source = {
"#version 460 core\n"
"in VS_FS {"
"smooth vec3 position;"
"smooth vec3 normal;"
"smooth vec2 texcoord;"
"} fs_in;"
"layout (location = 0) out vec4 out_color;"
"void main() {"
"vec3 color = vec3(1, 1, 1) * dot(vec3(0, 0, 1), fs_in.normal);"
"out_color = vec4(color, 1);"
"}"
};
bool success = true;
GLuint vertexshader = glCreateShader(GL_VERTEX_SHADER);
GLuint fragmentshader = glCreateShader(GL_FRAGMENT_SHADER);
if (!CompileShader(vertexshader, vertexshader_source))
success = false;
if (!CompileShader(fragmentshader, fragmentshader_source))
success = false;
if (!LinkProgram(program, { vertexshader, fragmentshader }))
success = false;
glDeleteShader(vertexshader);
glDeleteShader(fragmentshader);
if (!success)
return false;
//----------------------------------------
/* setup vertex array */
//----------------------------------------
// element buffer for indexed rendering
glVertexArrayElementBuffer(vertexarray, elementbuffer);
// per-vertex attributes
glVertexArrayAttribFormat(vertexarray, 0, 3, GL_FLOAT, GL_FALSE, 0);
glVertexArrayAttribFormat(vertexarray, 1, 3, GL_FLOAT, GL_FALSE, 0);
glVertexArrayAttribFormat(vertexarray, 2, 2, GL_FLOAT, GL_FALSE, 0);
glVertexArrayVertexBuffer(vertexarray, 0, vertexbuffer, offsetof(Vertex, Position), sizeof(Vertex));
glVertexArrayVertexBuffer(vertexarray, 1, vertexbuffer, offsetof(Vertex, Normal), sizeof(Vertex));
glVertexArrayVertexBuffer(vertexarray, 2, vertexbuffer, offsetof(Vertex, Texcoord), sizeof(Vertex));
glEnableVertexArrayAttrib(vertexarray, 0);
glEnableVertexArrayAttrib(vertexarray, 1);
glEnableVertexArrayAttrib(vertexarray, 2);
//----------------------------------------
/* setup mesh */
//----------------------------------------
Mesh mesh;
mesh.Vertices = {
{ { -0.5f, -0.5f, 0 }, { 0, 0, 1 }, { 0, 1 } },
{ { +0.5f, -0.5f, 0 }, { 0, 0, 1 }, { 1, 1 } },
{ { +0.5f, +0.5f, 0 }, { 0, 0, 1 }, { 1, 0 } },
{ { -0.5f, +0.5f, 0 }, { 0, 0, 1 }, { 0, 0 } },
};
mesh.Faces = {
{ 0, 1, 2 },
{ 0, 2, 3 },
};
meshref_quad = AddMesh(mesh);
//----------------------------------------
/* successfully initialized */
return true;
}
void Graphics::Render()
{
/* clear frame buffer */
glClearColor(0, 0, 0.5f, 0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
/* draw triangle */
glUseProgram(program);
glBindVertexArray(vertexarray);
//glUniformMatrix4fv(0, 1, GL_FALSE, value_ptr(projection));
//glUniformMatrix4fv(4, 1, GL_FALSE, value_ptr(modelview));
MeshRef meshref = mesh_refs.at(meshref_quad);
glDrawElementsBaseVertex(
GL_TRIANGLES,
meshref.ElementCount,
GL_UNSIGNED_INT,
reinterpret_cast<GLvoid*>(meshref.BaseElement* sizeof(GLuint)),
meshref.BaseVertex);
glBindVertexArray(0);
glUseProgram(0);
CheckForGLErrors;
}
void Graphics::CleanUp()
{
/* destroy all objects */
glDeleteProgram(program);
glDeleteVertexArrays(1, &vertexarray);
glDeleteBuffers(1, &vertexbuffer);
glDeleteBuffers(1, &elementbuffer);
}
int Graphics::AddMesh(const Mesh& mesh)
{
MeshRef mesh_ref;
mesh_ref.BaseVertex = vertices.size();
mesh_ref.BaseElement = elements.size();
mesh_ref.ElementCount = mesh.Faces.size() * 3;
mesh_refs.push_back(mesh_ref);
vertices.insert(vertices.begin(), mesh.Vertices.begin(), mesh.Vertices.end());
for (auto& face : mesh.Faces)
{
elements.push_back(face.x);
elements.push_back(face.y);
elements.push_back(face.z);
}
glNamedBufferData(
vertexbuffer,
vertices.size() * sizeof(Vertex),
vertices.data(),
GL_DYNAMIC_DRAW);
glNamedBufferData(
elementbuffer,
elements.size() * sizeof(GLuint),
elements.data(),
GL_DYNAMIC_DRAW);
return mesh_refs.size() - 1;
}
void Graphics::ResizeFramebuffer(const glm::uvec2& framebuffer_size)
{
glViewport(0, 0, framebuffer_size.x, framebuffer_size.y);
}
std::string Graphics::LoadTextFile(const std::string& filepath)
{
string result;
fstream f(filepath.c_str(), ios::in);
while (f.good())
{
string line;
getline(f, line);
result += line + '\n';
}
return result;
}
std::string Graphics::ShaderTypeName(GLuint shader)
{
if (glIsShader(shader))
{
GLint type = 0;
glGetShaderiv(shader, GL_SHADER_TYPE, &type);
if (type == GL_VERTEX_SHADER)
return "Vertex Shader";
if (type == GL_TESS_CONTROL_SHADER)
return "Tessellation Control Shader";
if (type == GL_TESS_EVALUATION_SHADER)
return "Tessellation Evaluation Shader";
if (type == GL_GEOMETRY_SHADER)
return "Geometry Shader";
if (type == GL_FRAGMENT_SHADER)
return "Fragment Shader";
if (type == GL_COMPUTE_SHADER)
return "Compute Shader";
}
return "invalid shader";
}
bool Graphics::CompileShader(GLuint shader, const std::string& sourcecode)
{
if (!glIsShader(shader))
{
cout << "ERROR: shader compilation failed, no valid shader specified" << endl;
return false;
}
if (sourcecode.empty())
{
cout << "ERROR: shader compilation failed, no source code specified (" << ShaderTypeName(shader) << ")" << endl;
return false;
}
const char* sourcearray[] = { sourcecode.c_str() };
glShaderSource(shader, 1, sourcearray, NULL);
glCompileShader(shader);
// check compile status
GLint status = 0;
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
// successfully compiled shader
if (status == GL_TRUE)
return true;
// show compile errors
cout
<< "ERROR: shader compilation failed (" << ShaderTypeName(shader) << ")" << endl
<< ShaderInfoLog(shader) << endl;
return false;
}
std::string Graphics::ShaderInfoLog(GLuint shader)
{
if (glIsShader(shader))
{
GLint logsize = 0;
GLchar infolog[1024] = { 0 };
glGetShaderInfoLog(shader, 1024, &logsize, infolog);
return string(infolog);
}
return "invalid shader";
}
bool Graphics::LinkProgram(GLuint program, const std::vector<GLuint>& shaders)
{
if (!glIsProgram(program))
{
cout << "ERROR: shader linking failed, no valid program specified" << endl;
return false;
}
// attach all shaders to the program
for (auto& shader : shaders)
{
if (glIsShader(shader))
glAttachShader(program, shader);
}
// link program
glLinkProgram(program);
// detach all shaders again
for (auto& shader : shaders)
{
if (glIsShader(shader))
glDetachShader(program, shader);
}
GLint status = 0;
glGetProgramiv(program, GL_LINK_STATUS, &status);
// successfully linked program
if (status == GL_TRUE)
return true;
// show link errors
cout
<< "ERROR: shader linking failed" << endl
<< ProgramInfoLog(program) << endl;
return false;
}
std::string Graphics::ProgramInfoLog(GLuint program)
{
if (glIsProgram(program))
{
GLint logsize = 0;
GLchar infolog[1024] = { 0 };
glGetProgramInfoLog(program, 1024, &logsize, infolog);
return string(infolog);
}
return "invalid program";
}
void Graphics::CheckForGLErrors__(const char* file, unsigned int line)
{
string errorstring;
for (GLenum error; (error = glGetError()) != GL_NO_ERROR;)
{
if (error == GL_INVALID_ENUM)
errorstring += " GL_INVALID_ENUM";
if (error == GL_INVALID_VALUE)
errorstring += " GL_INVALID_VALUE";
if (error == GL_INVALID_OPERATION)
errorstring += " GL_INVALID_OPERATION";
if (error == GL_STACK_OVERFLOW)
errorstring += " GL_STACK_OVERFLOW";
if (error == GL_STACK_UNDERFLOW)
errorstring += " GL_STACK_UNDERFLOW";
if (error == GL_OUT_OF_MEMORY)
errorstring += " GL_OUT_OF_MEMORY";
if (error == GL_INVALID_FRAMEBUFFER_OPERATION)
errorstring += " GL_INVALID_FRAMEBUFFER_OPERATION";
if (error == GL_CONTEXT_LOST)
errorstring += " GL_CONTEXT_LOST";
}
if (!errorstring.empty())
{
cout
<< (char)7
<< "OpenGL Error: " << endl
<< "\tLine: \t" << line << endl
<< "\tFile: \t" << file << endl
<< "\tErrors: \t" << errorstring << endl << endl;
cin.get();
}
}