0
votes

What is the easiest way to join more shaders (sources) to a glsl program? Normally when a vertex shader and fragment shader are attached to a program does something like this:

  vertex   = glCreateShader(GL_VERTEX_SHADER);
  fragment = glCreateShader(GL_FRAGMENT_SHADER);
  programa = glCreateProgram();

  char *vsFuente = LEE_SHADER(rutaVert);
  char *fsFuente = LEE_SHADER(rutaFrag);

  if(vsFuente == NULL)return GL_FALSE;
  if(fsFuente == NULL)return GL_FALSE;

  const char *vs = vsFuente;
  const char *fs = fsFuente;

  glShaderSource(vertex  ,1,&vs,NULL);
  glShaderSource(fragment,1,&fs,NULL);

  delete [] vsFuente;
  delete [] fsFuente;

  glCompileShader(vertex);
  glCompileShader(fragment);

  glAttachShader(programa,vertex);
  glAttachShader(programa,fragment);

  glLinkProgram(programa);

Well, if I want to join another pair of shader (vertex and fragment) to the same program, how do I do it? I use version 2.0 of OpenGL

1
Another pair of shaders to the program? You are not trying to do multiple passes are you? Programs do not work that way, they contain a single executable for every stage in the pipeline that is run when you draw something after an appropriate glUseProgram (...) call.Andon M. Coleman

1 Answers

2
votes

Exactly the same way you added the shaders you already have in your code. You create more shaders, call glCompileShader() and glAttachShader() for them, and then call glLinkProgram().

You need to be aware of what this is doing, though. While it is perfectly legal to add multiple shaders of the same type to a program, only one of the shaders of each type can have a main() function.

The typical setup I have seen when multiple shaders of the same type are attached to a program (which is not very common) is that some of the shaders contain collections of "utility" functions, and then there's one shader of each type type that contains the main() function, and implements the overall shader logic. This setup can be useful for complex shaders, since the shaders with the utility functions can be compiled once, and then attached to multiple different programs without having to compile them each time.

I'm not sure if this is what you're after. If you really just want to use different sets of shaders, the much more common setup is that you create a program for each pair of vertex/fragment shaders, and then switch between them during your rendering by calling glUseProgram() with the program you need for each part of the rendering.