# GLSL, all in one or many shader programs?

I am doing some 3D demos using OpenGL and I noticed that GLSL is somewhat "limited" (or is it just me?). Anyway I have many different types of materials. Some materials have ambient and diffuse color, some materials have ambient occlusion map, some have specular map and bump map etc.

Is it better to support everything in one vertex/fragment shader pair or is it better to create many vertex/fragment shaders and select them based on currently selected material? What is the usual shader strategy in OpenGL or D3D?

• – Patryk Czachurski Aug 23 '12 at 14:22
• This is a false dichotomy, that you must choose one or the other approach to managing shaders. In fifteen years in the industry, I've never worked on a project where we adhered to either extreme, but always struck a balance between the two approaches to managing shaders, using each where it made sense to do so. – Trevor Powell Sep 22 '12 at 2:04

The answer is, it kinda depends.

Basically there are two schools of thought; small, optimal shaders for everything and the uber-shader camp.

The small shaders are just that; do one thing, and do it well. Uber-shaders either control their functionality at runtime through uniforms, or compile into a bunch of different shaders through preprocessor macros (and/or generated shader sources).

The optimal solution is probably neither, but some kind of hybrid. Perhaps a few uber-shaders or uber-shaders combined with specialized shaders for some cases.

Pros:

• Likely to be faster/more optimal
• Does just what you want it to do
• Can do weird, custom stuff easily

Cons:

• Easily gets out of hand, especially when the number of features grows
• Probably more work, unless you have a very small number of shaders

Pros:

• Everything in one place
• More artist-friendly (using feature A with feature X for the first time doesn't necessarily require coder time)

Cons:

• Less optimal results (esp. if uniforms are used to switch features on/off)
• May be more difficult to debug/optimize
• Uber-shader in this representation is not a good thing :) I would propose to write good shaders manager based on predefines - so we will have uber-shader code with many #ifdefs which will be toggled for various materials. – brigadir Sep 21 '12 at 15:33
• I'd add that another pro of an uber-shader is that switching shaders has a cost in terms of performance, so if you're switching less often, you may be able to improve performance. – Jherico Apr 6 '16 at 18:02