I'd like to declare GLSL shader strings inline using macro stringification:
#define STRINGIFY(A) #A const GLchar* vert = STRINGIFY( #version 120\n attribute vec2 position; void main() { gl_Position = vec4( position, 0.0, 1.0 ); } );
This builds and runs fine using VS2010 but fails to compile on gcc
with:
error: invalid preprocessing directive #version
Is there a way to use stringification like this in a portable manner?
I'm trying to avoid per-line quotes:
const GLchar* vert = "#version 120\n" "attribute vec2 position;" "void main()" "{" " gl_Position = vec4( position, 0.0, 1.0 );" "}" ;
...and/or line continuation:
const GLchar* vert = "\ #version 120\n \ attribute vec2 position; \ void main() \ { \ gl_Position = vec4( position, 0.0, 1.0 ); \ } \ ";
In GLSL, you apply modifiers (qualifiers) to a global shader variable declaration to give that variable a specific behavior in your shaders. In HLSL, you don't need these modifiers because you define the flow of the shader with the arguments that you pass to your shader and that you return from your shader.
One way to speed up GLSL code, is by marking some variables constant at compile-time. This way the compiler may optimize code (e.g. unroll loops) and remove unused code (e.g. if hard shadows are disabled). The drawback is that changing these constant variables requires that the GLSL code is compiled again.
The OpenGL Shading Language (GLSL) is the principal shading language for OpenGL. While, thanks to OpenGL Extensions, there are several shading languages available for use in OpenGL, GLSL (and SPIR-V) are supported directly by OpenGL without extensions.
GLSL has most of the default basic types we know from languages like C: int , float , double , uint and bool .
Can you use C++11? If so you could use raw string literals:
const GLchar* vert = R"END( #version 120 attribute vec2 position; void main() { gl_Position = vec4( position, 0.0, 1.0 ); } )END";
No need for escapes or explicit newlines. These strings start with an R (or r). You need a delimiter (I chose END) between the quote and the first parenthesis to escape parenthesis which you have in the code snippet.
Unfortunately, having preprocessor directives in the argument of a macro is undefined, so you can't do this directly. But as long as none of your shaders need preprocessor directives other than #version
, you could do something like:
#define GLSL(version, shader) "#version " #version "\n" #shader const GLchar* vert = GLSL(120, attribute vec2 position; void main() { gl_Position = vec4( position, 0.0, 1.0 ); } );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With