Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GLSL equivalent of HLSL clip()?

Tags:

glsl

The HLSL clip() function is described here.

I intend to use this for alpha cutoff, in OpenGL. Would the equivalent in GLSL simply be

if (gl_FragColor.a < cutoff)
{
    discard;
}

Or is there some more efficient equivalent?

like image 603
Engineer Avatar asked Oct 06 '12 20:10

Engineer


1 Answers

OpenGL has no such function. And it doesn't need one.

Or is there some more efficient equivalent?

The question assumes that this conditional statement is less efficient than calling HLSL's clip function. It's very possible that it's more efficient (though even then, it's a total micro-optimization). clip checks if the value is less than 0, and if it is, discards the fragment. But you're not testing against zero; you're testing against cutoff, which probably isn't 0. So, you must call clip like this (using GLSL-style): clip(gl_FragColor.a - cutoff)

If clip is not directly support by the hardware, then your call is equivalent to if(gl_FragColor.a - cutoff < 0) discard;. That's a math operation and a conditional test. That's slower than just a conditional test. And if it's not... the driver will almost certainly rearrange your code to do the conditional test that way.

The only way the conditional would be slower than clip is if the hardware had specific support for clip and that the driver is too stupid to turn if(gl_FragColor.a < cutoff) discard; into clip(gl_FragColor.a - cutoff). If the driver is that stupid, if it lacks that basic pinhole optimization, then you've got bigger performance problems than this to deal with.

In short: don't worry about it.

like image 90
Nicol Bolas Avatar answered Nov 13 '22 04:11

Nicol Bolas