GLSL sampler/TMU management and state changes


I’m wondering what’s the best way to handle the mapping of TMUs to GLSL samplers to minimize state changes.

From what I read at the OpenGL forum FAQ at

binding a texture is more expensive than changing a sampler uniform. How to deal with this when writing an engine or effects framework? I can think of several cases:

TMUs are assigned to samplers when the GLSL program object is first bound and not changed again.

-easy implentation

-possibly unneccessary calls to glBindTexture when a required texture is already bound to a TMU but not the right one

The application manages the current mapping of TMUs to texture objects and does this:

  1. First search all TMUs for the one that “contains” the texture to be used by a sampler.
    1.a) If a suitable TMU is found it is assigned to the sampler by glUniformi
    1.b) If not a free TMU is made active and the texture is bound to it.

-possibly less calls to glBindTexture

-possibly more complicated implementation
-possibly more work for something that never happens

What do you think is the better thing to do? May be there is an alternative solution to that?