Created
November 8, 2020 16:06
-
-
Save MrTelanie/34aac261ba6dd28ebe4348b6dcb400cd to your computer and use it in GitHub Desktop.
glsl: dynamic index expression (and branchless)
This file contains hidden or 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
| /** | |
| * vec[index] throws an error: | |
| * '[]' : Index expression must be constant | |
| * get(vec, index) works fine | |
| * branchless implementation | |
| **/ | |
| float get(vec2 vec, int index) { | |
| vec2 mult = vec2(float(index == 0), float(index == 1)); | |
| vec2 bet = mult * vec; | |
| return bet.x + bet.y; | |
| } | |
| float get(vec3 vec, int index) { | |
| vec3 mult = vec3(float(index == 0), float(index == 1), float(index == 2)); | |
| vec3 bet = mult * vec; | |
| return bet.x + bet.y + bet.z; | |
| } | |
| float get(vec4 vec, int index) { | |
| vec4 mult = vec4(float(index == 0), float(index == 1), float(index == 2), float(index == 3)); | |
| vec4 bet = mult * vec; | |
| return bet.x + bet.y + bet.z + bet.w; | |
| } | |
| vec3 get(mat3 mat, int index) { | |
| vec3 mult = vec3(float(index == 0), float(index == 1), float(index == 2)); | |
| return mult.x * mat[0] + mult.y * mat[1] + mult.z * mat[2]; | |
| } | |
| vec4 get(mat4 mat, int index) { | |
| vec4 mult = vec4(float(index == 0), float(index == 1), float(index == 2), float(index == 3)); | |
| return mult.x * mat[0] + mult.y * mat[1] + mult.z * mat[2] + mult.w * mat[3]; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment