问题
I'm trying to write a shader that uses many bit operations. In fact they are supported since glsl 1.30, but I'm only on OpenGL 2.1.
Is there any way to use bit operations with my OpenGL version?
回答1:
All SM3 compatible (~OpenGL 2.1) hardware supports limited integer functionality. This is usually done by emulating integers with floats and does not include bit operations.
For bit operations, you need either GLSL 1.3 or EXT_gpu_shader4.
If the reason that you have only OpenGL 2.1 is that your driver is somewhat outdated, you may be lucky to still have EXT_gpu_shader4 (updating drivers might be a good idea though, in that case).
If the reason is that your graphics card simply does not support anything better, you are out of luck.
If you do have EXT_gpu_shader4 (check extension string), you can add:
#extension EXT_gpu_shader4 : require
to your GLSL 1.2 shaders, and it should work.
回答2:
This should help you get started.
lowp ivec4 imod4_2(lowp ivec4 x)
{
return x - (2 * (x/2));
}
lowp ivec4 parselowbits(lowp int x)
{
// Implement (x % y) where y is known to be the constant 2
// by first dividing x by (8, 4, 2, 1) and then doing a mod
// by (2, 2, 2, 2) to generate an int vector.
lowp ivec4 numerator = ivec4(x);
lowp ivec4 denominator = ivec4(8, 4, 2, 1);
lowp ivec4 modNumerator = numerator / denominator;
lowp ivec4 modResult = imod4_2(modNumerator);
return modResult;
}
lowp ivec4 parsehighbits(lowp int x)
{
// Implement (x % y) where y is known to be the constant 2
// by first dividing by (8*16, 4*16, 2*16, 1*16) and then doing a mod
// by (2, 2, 2, 2) to generate an int vector.
lowp ivec4 numerator = ivec4(x);
lowp ivec4 denominator = ivec4(8*16, 4*16, 2*16, 1*16);
lowp ivec4 modNumerator = numerator / denominator;
lowp ivec4 modResult = imod4_2(modNumerator);
return modResult;
}
The above functions work on the high a low nibble (4 bits) of a component like .r .g of an input vector. You will of course need to read values in and multiply by 255 to denormalize. Then, implementing AND is easy:
lowp ivec4 and4(lowp ivec4 a, lowp ivec4 b)
{
lowp ivec4 a_and_b = a * b;
return a_and_b;
}
来源:https://stackoverflow.com/questions/6634519/how-to-use-bit-operations-in-glsl-1-3-with-opengl-2-1