原文地址: http://www.learnopengl.com/#!In-Practice/Debugging

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:


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)
 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;
16        }
17        std::cout << error << " | " << file << " (" << line << ")" << std::endl;
18    }
20    return errorCode;
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:

一个非常重要的事情必须被提及。GLEW库有一个长期存在的bug,在调用glewInit函数的地方,一直会把GL_INVALID_ENUM 标志位给设置。因而,在第一次调用glGetError的时候会一直返回这个值。解决这个bug很简单,在glewInit函数调用后,马上调用一次glGetError函数,如下:


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.


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).

从4.3版本开始,Debug output将作为OpenGL的内核存在。也就是说只要你运行OpenGL4.3以上的版本你可以直接使用它。如果运行低版本的OpenGL的话。可以通过查询ARB_debug_output或者AMD_debug_output这两个OpenGL扩展达到这个功能。注意在OS X中貌似不支持这个函数。(从网上得知,未经证实)。

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:



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);
5    // initialize debug output