Reputation: 329
I want to build a fragment shader, and I realized that the comparison between two int in glsl 1.5.0 will return always false. I am using integers as an enumeration in a method parameter. This is the problem in a simple way and this code has the same result.
void main(){
int x = 5;
#if(x == 5)
gl_FragColor = vec4(1.0);
#else
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
#endif
}
I tried this code and the condition x == int(2)
will return always true!
void main(){
int x = 5;
#if(x == int(2))
gl_FragColor = vec4(1.0);
#else
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
#endif
}
So, what should I do to compare two integers in the right way?
Upvotes: 2
Views: 1856
Reputation: 210948
#if
, #else
and #endif
are preprocessor statements. But int x = 5;
is a local variable. The preprocessor processes the source string, it is part of the comoilation process, but it is done before the actual compilation. The variable x
has no meaning for the preprocessor.
A x
for the preprocessor can be defines a follow:
#define x 5
#if(x == 5)
gl_FragColor = vec4(1.0);
#else
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
#endif
But a glsl if
statement start with the keyword if
followed by a bool-expression and a statement. Optional followed by the keyword else
and another statement:
int x = 5;
if (x == 5)
{
gl_FragColor = vec4(1.0);
}
else
{
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
In this case the curly braces can be skipped, because in each case there is only a single statement.
Note, a ternary operator can be used, too:
gl_FragColor = x==5 ? vec4(1.0) : vec4(1.0, 0.0, 0.0, 1.0);
This all can be read in the OpenGL Shading Language 1.50 Specification in detail. The preprocessor is explained in chapter "3.3 Preprocessor", the if
statement is specified in chapter "6.2 Selection" and and the Ternary operator in chapter "5.8 Assignments"
Upvotes: 2