# 现代的OpenGL调试方式（翻译）

## 1 Debugging

Graphics programming can be a lot of fun, but it can also be a large source of frustration whenever something isn’t rendering right or perhaps not even rendering at all! Seeing as most of what we do involves manipulating pixels it can be difficult to figure out the cause of error whenever something doesn’t work the way it’s supposed to. Debugging these kind of errors is different than what you’re used to when debugging errors on the CPU. We have no console to output text to, no breakpoints to set on our GLSL code and no way of easily checking the state of GPU execution.

In this tutorial we’ll look into several techniques and tricks of debugging your OpenGL program. Debugging in OpenGL is not too difficult to do and getting a grasp of its techniques definitely pays out in the long run.

## 2 glGetError()

The moment you incorrectly use OpenGL (like configuring a buffer without first binding any) it will take notice and generate one or more user error flags behind the scenes. We can query these error flags using a function named glGetError that simply checks the error flag(s) set and returns an error value if OpenGL indeed got abused.

1GLenum glGetError();


The moment glGetError is called it returns either an error flag or no error at all. The error codes that glGetError can return are listed below:

glGetError函数被调用的时候，它将会返回错误代码，或者不返回一个代表没有错误代码的GL_NO_ERROR的代码，返回的错误代码如下表所示：

Flag Code Description
Flag Code Description
GL_NO_ERROR 0 No user error reported since last call to glGetError.
GL_INVALID_ENUM 1280 Set when an enumeration parameter is not legal.
GL_INVALID_VALUE 1281 Set when a value parameter is not legal.
GL_INVALID_OPERATION 1282 Set when the state for a command is not legal for its given parameters.
GL_STACK_OVERFLOW 1283 Set when a stack pushing operation causes a stack overflow.
GL_STACK_UNDERFLOW 1284 Set when a stack popping operation occurs while the stack is at its lowest point.
GL_OUT_OF_MEMORY 1285 Set when a memory allocation operation cannot allocate (enough) memory.
GL_INVALID_FRAMEBUFFER_OPERATION 1286 Set when reading or writing to a framebuffer that is not complete.

Within OpenGL’s function documentation you can always find the error codes a function generates the moment it is incorrectly used. For instance, if you take a look at the documentation of the glBindTexture function you can find all the user error codes it could generate under the Errors section

The moment an error flag is set, no other error flags will be reported. Furthermore, the moment glGetError is called it clears all error flags (or only one if on a distributed system, see note below). This means that if you call glGetError once at the end of each frame and it returns an error you can’t conclude this was the only error and the source of the error could’ve been anywhere in the frame

Note that when OpenGL runs distributely like frequently found on X11 systems, other user error codes can still be generated as long as they have different error codes. Calling glGetError then only resets one of the error code flags instead of all of them. Because of this it is recommended to call glGetError inside a loop.

1glBindTexture(GL_TEXTURE_2D, tex);
2std::cout << glGetError() << std::endl; // returns 0 (no error)
3glTexImage2D(GL_TEXTURE_3D, 0, GL_RGB, 512, 512, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
4std::cout << glGetError() << std::endl; // returns 1280 (invalid enum)
5glGenTextures(-5, textures);
6std::cout << glGetError() << std::endl; // returns 1281 (invalid value)
7std::cout << glGetError() << std::endl; // returns 0 (no error)


The great thing about glGetError is that it makes it relatively easy to pinpoint where any error might be and to validate the proper use of OpenGL. Let’s say you get a black screen and you have no idea what’s causing it: is the framebuffer not properly set? Did I forget to bind a texture? By calling glGetError all over your codebase you can quickly catch the first place an OpenGL error starts showing up which means before that call something went wrong.

By default glGetError only prints the error numbers which isn’t easy to understand unless you memorize the error codes. It often makes sense to write a small helper function to easily print out the error strings together with where the error check function was called:

 1GLenum glCheckError_(const char *file, int line)
2{
3    GLenum errorCode;
4    while ((errorCode = glGetError()) != GL_NO_ERROR)
5    {
6        std::string error;
7        switch (errorCode)
8        {
9            case GL_INVALID_ENUM: error = "INVALID_ENUM"; break;
10            case GL_INVALID_VALUE: error = "INVALID_VALUE"; break;
11            case GL_INVALID_OPERATION: error = "INVALID_OPERATION"; break;
12            case GL_STACK_OVERFLOW: error = "STACK_OVERFLOW"; break;
13            case GL_STACK_UNDERFLOW: error = "STACK_UNDERFLOW"; break;
14            case GL_OUT_OF_MEMORY: error = "OUT_OF_MEMORY"; break;
15            case GL_INVALID_FRAMEBUFFER_OPERATION: error = "INVALID_FRAMEBUFFER_OPERATION"; break;
16        }
17        std::cout << error << " | " << file << " (" << line << ")" << std::endl;
18    }
19
20    return errorCode;
21}
22
23#define glCheckError() glCheckError_(__FILE__, __LINE__) glBindBuffer(GL_VERTEX_ARRAY, vbo);glCheckError();


This will give us the following output

One important thing left to mention is that GLEW has a long-existing bug where calling glewInit() always sets theGL_INVALID_ENUM error flag and thus the first glGetError will always return an error code which can throw you completely off guard. To fix this it’s advised to simply call glGetError after glewInit to clear the flag:

1glewInit();
2glGetError();
3glewInit();
4glGetError();


glGetError doesn’t help you too much as the information it returns is rather simple, but it does often help you catch typos or quickly pinpoint where in your code things went wrong; a simple but effective tool in your debugging toolkit.

glGetError函数只能简单地提供错误码。没法提供更多的帮助信息。但利用它可以快速地查询到代码哪里调用OpenGL函数发生了错误。这函数，简单，但是有效。

## 3 Debug output

A less common, but more useful tool than glCheckError is an OpenGL extension called debug output that became part of core OpenGL since version 4.3. With the debug output extension OpenGL itself will directly send an error or warning message to the user with a lot more details compared to glCheckError. Not only does it provide more information, it can also help you catch errors exactly where they occur by intelligently using a debugger.

Debug output is core since OpenGL version 4.3, which means you’ll find this functionality on any machine that runs OpenGL 4.3 or higher. If they’re not available its functionality can be queried from the ARB_debug_output or AMD_debug_output extension. Note that OS X does not seem to support debug output functionality (as gathered online; I haven’t tested it myself. Let me know if I’m wrong).

In order to start using debug output we have to request a debug output context from OpenGL at our initialization process. This process varies based on whatever windowing system you use; here we will discuss setting it up on GLFW, but you can find info on other systems in the additional resources at the end.

## 4 Debug output in GLFW

Requesting a debug context in GLFW is surprisingly easy as all we have to do is pass a hint to GLFW that we’d like to have a debug output context. We have to do this before we call glfwCreateWindow:

1glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);


Once we initialize GLFW we should have a debug context if we’re using OpenGL version 4.3 or higher, or else we have to take our chances and hope the system is still able to request a debug context. Otherwise we have to request debug output using its OpenGL extension(s).Using OpenGL in debug context can be significantly slower compared to a non-debug context so when working on optimizations or releasing your application you want to remove or comment GLFW’s debug request hint.

To check if we successfully initialized a debug context we can query OpenGL:

1GLint flags;
2glGetIntegerv(GL_CONTEXT_FLAGS, &flags);
3if (flags & GL_CONTEXT_FLAG_DEBUG_BIT)
4{
5    // initialize debug output
6}