Showing results for 
Search instead for 
Did you mean: 

OpenGL & Vulkan

Journeyman III

GLSL issue: findMSB of zero with clamp

Working on TheDarkMod game, we have bumped into an issue which looks like a driver bug.

Note that we have also found various workarounds, so we don't need any help with it. "Civic duty" is the only reason behind this post 😃

We have a SSAO shader on GLSL 1.40 with GL_ARB_gpu_shader5 enabled (sorry for such an old version). Here is a small excerpt from the code:

    #define LOG_MAX_OFFSET (3)

    int mipLevel = clamp(findMSB(int(ssR)) - LOG_MAX_OFFSET, 0, u_maxMipLevel);

When ssR is between 0.0 and 1.0, conversion to int should yield zero, and findMSB of zero should yield -1. The final value of mipLevel should be 0. However, it seems that in our case it equals u_maxMipLevel instead. Like if findMSB returned 0xffffffff instead of -1.

Interestingly, merely saving the result of findMSB into a variable solves the problem:

    int msb = findMSB(int(ssR));
    int mipLevel = clamp(msb - LOG_MAX_OFFSET, 0, u_maxMipLevel);

I have attached full code for the shaders. The code causing the problem is at line 84 of ssao.frag.glsl.

Sorry for no complete MWE.

2 Replies
Adept II

>0xffffffff instead of -1.

sorry for obvious tip/question

are you sure you do clamp(val, min, max) where min < max

clamp return INF when min>=max


Well, I am "pretty sure" from what I see.

From what I read, clamp with minVal > maxVal should return maxVal.

But it is a bug either way because extracting a subexpression into a separate variable should not change the outcome.