Search code examples
glslwebgl

Is it possible to define a function once for different argument types in GLSL?


Suppose I have a function such as this,

vec2 myFun(vec2 v){
   return vec2(length(v));
}

Is it possible to avoid defining exactly same functions for vec2 and vec3 -valued arguments and respectively outputs? Or more generally, if my function body only contains other genType functions, can I define it just once for all argument types?


Solution

  • GLSL itself doesn't support this, but you could use a macro to have the preprocessor do the work for you:

    #define _(TYPE)\
    TYPE myFun(TYPE v){\
        return TYPE(length(v));\
    }
    // define above functions for gentypes
    _(float)_(vec2)_(vec3)_(vec4)
    

    Note that you have to escape line breaks in the macro, so you probably want your host application to stitch it together that way.