51

I'm trying to send a boolean to an OpenGL glsl shader.

Currently I have this in the shader:

uniform bool foo;

And I use this to set it:

glUniform1i(glGetUniformLocation(shader, "foo"), true);

There doesn't seem to be a glUniform1b, so I'm setting it as an integer. This seems to work fine.

Is there any problem with this approach? Is it portable, or could it break on other graphics cards / drivers? I'm using OpenGL 4.3 at the moment.

2
  • As far as I know it has something to do with 4-byte alingment (boolean is 1 byte so either way 3 additional padding bytes will be added at the end) so using boolean is not efficient and maby even deprecated in OpenGL
    – Amadeusz
    Nov 13, 2015 at 10:09
  • @Amadeusz it's certainly not deprecated. Nov 13, 2015 at 10:39

2 Answers 2

52

§ 4.1 Basic Types The OpenGL Shading Language supports the following basic data types, grouped as follows:

  • bool a conditional type, taking on values of true or false
  • bvec2 a two-component Boolean vector
  • bvec3 a three-component Boolean vector
  • bvec4 a four-component Boolean vector

...

§ 4.1.2 Booleans To make conditional execution of code easier to express, the type bool is supported. There is no expectation that hardware directly supports variables of this type. (...)

As for setting:

§ 2.2.1 (...) When state values are specified using a different parameter type than the actual type of that state, data conversions are performed as follows:

  • When the type of internal state is boolean, zero integer or floating-point values are converted to FALSE and non-zero values are converted to TRUE.
2
  • 4
    Thanks. 4.1 means that I can use bool in my glsl shader. 4.1.2 doesn't really help me. What is still not answered is if I can set a boolean uniform using glUniform1i...
    – Jan Rüegg
    Nov 13, 2015 at 10:40
  • 2
    @JanRüegg Added a quote for that as well Nov 13, 2015 at 10:44
0

The size of a glsl bool is 32-bits which is identical to an int, so yes, you can set it like that.

And no, it won't break on other graphics cards / drivers for OpenGL.

1
  • 5
    "integer below or equal to zero is considered false" The other answer claims that non-zero integers are always false. "bool occupies 1-byte" I'm not sure about it, the other answer claims that "no expectation that hardware directly supports variables of this type". Jul 21, 2021 at 7:22

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.