Last active
January 11, 2023 21:41
-
-
Save jarble/efb39304ba756606b2cf8080a5a08a11 to your computer and use it in GitHub Desktop.
Generic programming in GLSL (parametric polymorphism, template metaprogramming) https://www.reddit.com/r/glsl/comments/mmxves/generic_programming_parametric_polymorphism/
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
//I wish there were a better way to do this! | |
#define func(type,name,param1,param2,body) type name(type param1,type param2) {body} | |
#define generic(name,param1,param2,body) func(float,name,param1,param2,body) func(vec2,name,param1,param2,body) func(vec3,name,param1,param2,body) func(vec4,name,param1,param2,body) | |
//define two "generic" functions using this macro | |
generic(add,a,b, | |
return a + b; | |
) | |
generic(sub,a,b, | |
return a - b; | |
) | |
//but this can also be done using a "tagged union": | |
const int int_ = 1; | |
const int float_ = int_+1; | |
const int bool_ = float_+1; | |
struct Object | |
{ | |
bool bool_; | |
int int_; | |
float float_; | |
int type; | |
}; | |
#define define_new(type1,type1_) Object new(type1 a){Object return1; return1.type = type1_; return1.type1_ = a ; return return1; } | |
define_new(float,float_) | |
define_new(bool,bool_) | |
define_new(int,int_) | |
Object new(Object a){ | |
return a; | |
} | |
Object And(Object a, Object b){ | |
return new(a.bool_ && b.bool_); | |
} | |
Object Or(Object a, Object b){ | |
return new(a.bool_ || b.bool_); | |
} | |
Object Not(Object a){ | |
return new(!a.bool_); | |
} | |
bool example(bool a,bool b){ | |
//convert bool to Object and vice-versa | |
{ | |
Object a = new(a),b=new(b); | |
return Or(a,b).bool_; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment