If you have been using OpenGL for a while, you probably have a lot of shader files, maybe one for each programmable stage of the pipeline. At some point during development the directory that contains the shaders becomes a mess, managing and opening shader files in your editor becomes tedious. Luckily there’s a way to cram all the programmable shader stages in a single file, reducing the number of files at least by half and calm the neat freak inside.
These are the two things that make this trick possible.
The idea is to separate different shader stages inside an #ifdef blocks and setting the corresponding #define directive for the shader stage.
Here’s an example of what a shader might look like using this method.
|
|
Shader compilation looks something like this:
|
|
Notice that before calling glShaderSource we create an array of two pointers to char, the first one contains glsl’s #version preprocessor directive and the token that defines each shader. In the case of the vertex shader the first string looks like this “#version 330 core\n#define VERTEX_SHADER\n”. Sadly the #version directive needs to be the first line in a shader or else compilation fails. Setting the shader version like this is not as pretty or tidy as we may want but it’s a tradeoff i’m willing to make. When calling glShaderSource we set the second parameter to “2” indicating 2 strings and set the string to our newly created array.
I hope you find this useful.