GLSL Problem: Multiple shaders in one program

Nightshade picture Nightshade · Aug 29, 2011 · Viewed 14.3k times · Source

I must have misunderstood something with shaders:

I thought that as you can attach multiple shaders to one program, you'd be able to simply attach more than one fragment shader, as an example: A crate texture rendered with a color modulation and refraction.

But apparently this is not the case, as you can have only one main function per program.

  • How can I work around the main function limit and allow for any dynamic combination of multiple fragment shaders which are in the same program and called after each other?

Answer

kvark picture kvark · Aug 30, 2011

You can have a set of entry points pre-defined. Suppose you have a limited number of effects (diffuse, specular, environment, etc). None of them is applied at most once, so you just need to create a managing shader like that one:

void apply_diffuse();
void apply_specular();
void apply_environment();

void main(){ ...
     apply_diffuse();
     apply_specular();
     apply_environment();
...}

Then, when it's time to link the shader program you attach the corresponding implementations as separate GLSL objects. Some implementations may be dummies if you don't want the effect. This approach doesn't require source text parsing and has next to no performance penalty.