Working on optimizing a fragment shader which is slowing down my OpenGL ES 2.0 shader based game. This is used with a shadow buffer to determine if the fragment/pixel is inside a shadow volume.

The problem/slowdown is the fact I need a branch if or function to determine a 1.0 (no shadow) or 0.0 (shadowed) based on comparison of the frag's shadow Z and shadow buffer Z.

    // SLOWEST
    if ( shadowValue > shadowTexZ ) return 1.0; else return 0.0;

    // ALSO SLOW
    return clamp( 1.0 + (shadowValue - shadowTexZ) * 1000.0, 0.0, 1.0 );

    return max(sign(shadowValue - shadowTexZ), 0.0);

    // ALSO SLOW
    return sign( shadowValue - shadowTexZ ) * 0.5 + 0.5;

If I disable the shadow test all together, GPU time in Xcode is 12ms and solid 60fps. With the test on it jumps to 26ms and drops the framerate unacceptably to 40fps.


  • $\begingroup$ I wonder if it's the texture read(s?) that are slow. If you don't use the value that results from the texture read, it probably isn't even doing the texture read. You could try doing dummer math with those values to see if it's still slow. like maybe return shadowValue + shadowTexZ; $\endgroup$
    – Alan Wolfe
    Sep 23, 2016 at 23:22
  • $\begingroup$ I also think the compiler may be optimizing out some parts of your code if you comment this line. Please check the lower level generated code to be sure. Moreover, you should check the step function documentation for optimizing out this particular branch. $\endgroup$
    – vgs
    Sep 24, 2016 at 4:42

1 Answer 1


I think the most efficient way might be either

return float(shadowValue > shadowTexZ);


return step(shadowTexZ, shadowValue);
  • 2
    $\begingroup$ Could you share you reasons for settling on these approaches? The logic behind it or profiling evidence perhaps? $\endgroup$ Sep 25, 2016 at 11:40
  • $\begingroup$ The first one to me seems like the most straightforward approach to obtain the desired result and the second one is something the GPU potentially might be better suited for than comparisons and type casting. Maybe I'm completely wrong, but it's worth a try at least. $\endgroup$
    – Detheroc
    Sep 25, 2016 at 14:30
  • 2
    $\begingroup$ These seem like points worth expanding your answer with. $\endgroup$ Sep 25, 2016 at 18:55

Your Answer

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

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