Last active
March 6, 2020 03:39
-
-
Save stash/892f0655e0a83be803f30018d94087b3 to your computer and use it in GitHub Desktop.
Branchless logic functions for HLSL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// NOTE: Apparently this whole "branchless" thing a Generally Bad Idea; it makes the code slower and complex in a lot of cases! | |
/// Conditional-move is a thing on GPUs too, and can make using these sort of gymnastics obsolete. | |
/// See this epic twitter thread: https://twitter.com/bgolus/status/1235254923819802626 | |
// from http://theorangeduck.com/page/avoiding-shader-conditionals | |
// TYPE needs to be defined before including this file | |
TYPE when_eq(TYPE x, TYPE y) { | |
return 1.0 - abs(sign(x - y)); | |
} | |
TYPE when_neq(TYPE x, TYPE y) { | |
return abs(sign(x - y)); | |
} | |
TYPE when_gt(TYPE x, TYPE y) { | |
return max(sign(x - y), 0.0); | |
} | |
TYPE when_lt(TYPE x, TYPE y) { | |
return max(sign(y - x), 0.0); | |
} | |
TYPE when_ge(TYPE x, TYPE y) { | |
return 1.0 - when_lt(x, y); | |
} | |
TYPE when_le(TYPE x, TYPE y) { | |
return 1.0 - when_gt(x, y); | |
} | |
TYPE and(TYPE a, TYPE b) { | |
return a * b; | |
} | |
TYPE and(TYPE a, TYPE b, TYPE c) { | |
return a * b * c; | |
} | |
TYPE and(TYPE a, TYPE b, TYPE c, TYPE d) { | |
return a * b * c * d; | |
} | |
TYPE or(TYPE a, TYPE b) { | |
return min(a + b, 1.0); | |
} | |
TYPE or(TYPE a, TYPE b, TYPE c) { | |
return min(a + b + c, 1.0); | |
} | |
TYPE or(TYPE a, TYPE b, TYPE c, TYPE d) { | |
return min(a + b + c + d, 1.0); | |
} | |
TYPE xor(TYPE a, TYPE b) { | |
return (a + b) % 2.0; | |
} | |
TYPE not(TYPE a) { | |
return 1.0 - a; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef BRANCHLESS_INCLUDED | |
#define BRANCHLESS_INCLUDED | |
#ifdef TYPE | |
#define BRANCHLESS_TYPE_SAVE TYPE | |
#undef TYPE | |
#endif | |
// Go through for each type of primitive that will work. | |
// The "undef TYPE" is needed to avoid redefinition template warnings. | |
#define TYPE float | |
#include "./branchless-template.hlsl" | |
#undef TYPE | |
#define TYPE float2 | |
#include "./branchless-template.hlsl" | |
#undef TYPE | |
#define TYPE float3 | |
#include "./branchless-template.hlsl" | |
#undef TYPE | |
#define TYPE float4 | |
#include "./branchless-template.hlsl" | |
#undef TYPE | |
#ifdef BRANCHLESS_TYPE_SAVE | |
#define TYPE BRANCHLESS_TYPE_SAVE | |
#endif | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment