1
\$\begingroup\$

I have an outline shader, which samples my texture 8 times to compute the outline.

The problem is, that there's transitional alpha values between picture and background. To cut them off I'm using the following function instead of just sampling my texture by calling texture2D().

vec4 texSample(sampler2D sampler, vec2 pos)
{
    vec4 color = texture2D(sampler, pos);

    if (color.a < 0.5)
    {
        color.a = 0.0;
    }

    return color;
}

The question is: are there any ways to optimize this check or even avoid it at all?

\$\endgroup\$
1
\$\begingroup\$

There's really not much room for optimization here, having divergent branches over such a small if body is probably not affecting your performance really at all.

You could use something like discard which might convey your intention better, but ultimately will not change your performance.

Taking from this post, here's an example usage.

if (color.a < 0.5)
{
    discard;
}

As a final side-note, if this shader is causing you performance issues you should look somewhere besides the shader. There's really nothing wrong here. You could make sure you're properly using mip-maps, I think that's a common source of slow down in OpenGL-ES because they're not generated by default.

This post has a link to a tutorial on mipmaps and how to generate them.

\$\endgroup\$
0
\$\begingroup\$

Use the built-in glsl function step to set any alpha value below 0.5 to 0.0.

color.a *= step(color.a, 0.5);
\$\endgroup\$
  • \$\begingroup\$ Is this actually correct? color.a = 0.25 in the OP gives 0 but in this solution gives 0.5. Additionally is this even faster? When the threads diverge over the branch, in effect they're all executing two instructions regardless of path, in this solution they're executing at least as much. \$\endgroup\$ – Alex Sherman Apr 19 '16 at 15:41
  • \$\begingroup\$ Just realised i understood the question wrong. Edited. \$\endgroup\$ – cozmic Apr 19 '16 at 15:46
  • \$\begingroup\$ OK but still this is as slow or slower right? It's now assignment, math operation and built in function whereas the OP is only conditional and assignment. \$\endgroup\$ – Alex Sherman Apr 19 '16 at 15:50
  • \$\begingroup\$ I'm not too sure, i would actually assume you are right as the OP is not really creating multiple branches which would cause slowdown. What I read everywhere is, that built-in functions should be used if possibl. Also it depends on how many invocations of this are done per frame to even make a noticable difference. I haven't tested it though, it's just my assumption. You are probably good either way. \$\endgroup\$ – cozmic Apr 19 '16 at 15:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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