23

I've tried my hardest to understand the functions of OpenGL in-depth, but I have an issue with glShaderSource's parameters:

void glShaderSource(
  GLuint shader,
  GLsizei count,
  const GLchar * const * string,
  const GLint * length);

I'm confused about the last two parameters. What do they actually mean in C++? Does it mean I give it a string, a const char or pointer of a string if thats even possible? And why?

3 Answers 3

39

glShaderSource expects two related sequences (C-style arrays) of values.

The first sequence is an array of C-strings, either zero-terminated or not.

The second sequence is an array of integers, indicating the length of each of the strings in the first sequence. This sequence is optional if the strings are zero-terminated, as the library will find the lengths by itself.

The GL-prefixed types are because the OpenGL specification needs to talk about types without tying itself into a particular language, so it introduces aliases of common C types.

GLchar is a type similiar to the C char, which serves to represent a narrow character. GLint is a signed integer type, commonly used to represent object handles and offsets. There's also others like GLenum and GLvoid.

GLchar const* is the OpenGL spelling of the char const* type. Apart from being used to point to a single character, it's commonly used to represent a string of characters. When used in that meaning, it shall point to a sequence of characters, ending with a sentinel value '\0' to know that the string ends.

The reason for making glShaderSource take more than one string is because OpenGL's shader compiler has exposed the concept of a file. Each of these strings represents the contents of one file, and it will compile as if these files are concatenated together. Note that this file is largely unrelated to the filesystem thing of the same name. glShaderSource only deals with strings containing text.

This is beneficial when you've got some fragments you want to assemble together into the full shader source, like if you want to prepend a #version statement or some common preamble, or have implemented some sort of include directive yourself.

As for an example of how to use it:

std::string v = "#version 150\n";
std::string c = ReadTextFile("common.glsl"); // read a string with the file contents
std::string s = ReadTextFile("mesh.vert");   // same here

GLchar const* files[] = { v.c_str(), c.c_str(), s.c_str() };
GLint lengths[]       = { v.size(),  c.size(),  s.size()  };

glShaderSource(id, 3, files, lengths);

Here we're combining three strings for OpenGL to consider as one large chunk of source text. Note that my convenience function ReadTextFile reads the content of a filesystem file into a string, no part of OpenGL ever touches the filesystem. If you want to get the contents of a text file, image file or mesh file into OpenGL structures, you need to read it in for yourself ahead of time.

1
  • 1
    Fantastic Answer Lars Viklund but would it be possible to explain it if you was using a .vert or .frag file instead of just strings and obscure gl data types that I've hardly used though this is very useful it's not in the right context I guess you could call it that!
    – Rose
    Feb 28, 2014 at 23:50
14

Let's go through this step by step:

  • const GLchar is an immutable (constant) character.
  • const GLchar * is a pointer to immutable GLchars, in this case your shader source.
  • const GLchar * const is an immutable pointer to immutable GLchars, that means the pointer itself can not be changed to point somewhere else.
  • const GLchar * const * is a pointer to an immutable pointer to immutable GLchars.
  • Finally string is just the name of the parameter.

That means it expects a pointer to a constant pointer to constant GLchars. You can use it like so (using NULL for the size, to let glShaderSource figure out the lengths):

const GLchar *source = "my awesome shader";
glShaderSource(myShader, 1, &source, NULL);

Or to specify more than one source:

const GLchar *sources[] = {
  "my awesome shader",
  "another awesome"
};
glShaderSource(myShader, sizeof(sources)/sizeof(*sources), sources, NULL);

I haven't actually tested the above code and there may be some casts necessary, but it should show how it works in principle.

2
  • Interesting immutable means what exactly?
    – Rose
    Feb 28, 2014 at 23:51
  • 1
    Basically it means that something can't be changed. In this case the glShaderSource promises to neither change the pointers you give it or the shader sources they point to.
    – kolrabi
    Mar 3, 2014 at 8:05
1

I was wondering how to read a (shader) file into a string to pass to glShaderSource(). But this is not even necessary.

The OpenGL docs (khronos.org) say:

If length is NULL, each string is assumed to be null terminated.

From which follows: the "string" does not have to be null terminated, but then you have to pass the correct length.

The command lets you pass more than one of these string/length pairs - that is the count parameter. Lars' answer has a good example. Here is the body of my function to read a shader file into a unterminated string. It is in C, quite simple and direct without any copying, just a open(), fstat() and mmap(). Only takes a bit of fiddling with the types, because I have count=1 and no extra array variables.

int fd = open(filename, O_RDONLY);
if (fd == -1) {
    printf("Error opening shader file %s", filename);
    exit(EXIT_FAILURE);
}

Normally I don't care too much about errors, but a filename can always be wrong, and the following commands would not like an fd of -1 or the results thereof...


struct stat stb;
fstat(fd, &stb);

This is to get the length (string length = file size).


const char *mm = mmap(NULL, stb.st_size, PROT_READ, MAP_PRIVATE, fd, 0);

mm now points to the start of the string. mm is the string, period. But the end is not defined(?), we only know the length. mm[stb.st_size] = '\0' does not work, because of...different reasons.


close(fd);

Can be done after mmap().


Instead of assigning mm (the address) into a one-sized array, I pass &mm:

glShaderSource(shader, 1, &mm, (int *)&stb.st_size);

Similar for the length/st_size; only here the value is inside a struct. Looks a bit scary. This is how fstat() and glShaderSource() collide. And gcc compiler: you can actually leave out the (int *) cast at the cost of a compiler warning.

Also void *mm = mmap(...) works, but produces an (instructive) warning.

The compiler needs both: the & and the correct types. The second const can be left out, at least.

Even replacing (int *)&stb.st_size) with NULL and hoping for null termination works in my case. A shader file of exactly 4096 bytes might be needed to provoke an error. Or some other kind of (in this case) well-deserved bad luck.


This I neglected - right after glShaderSource() has copied from mm, you can:

 munmap((void *)mm, stb.st_size);

So the correct type of mm does not really pay off, because it has to be recast back to prevent a warning...maybe just leave it void *mm and do the whole array-of-(pointer-to)-something job with the function parameters.

glShaderSource(shader, 1, (const char **)&mm, (int *)&stb.st_size)

On the other hand, with two extra arrays and four extra lines, most casts, stars and ampersands disappear:

const char *mm_arr[1];      // array of one (string aka char pointer)
mm_arr[0] = mm;             // first and only element is set; no cast needed even if 'void *mm'
int sz_arr[1];              // array of a single int
sz_arr[0] = stb.st_size;    // normal assignment of int to int

glShaderSource(shader, 1, mm_arr, sz_arr);

And why?

For flexibility - as if they thought (quite long ago!): These programmers might well read in their shader files with getline() or so, so let us not force them to merge the lines and/or null terminate them. They can pass it as they have it.

Not to specify more than one shader (as the other A suggests), but to specify one shader in more than one parts (lines or logical parts).


Here is a C++ example I found, doing quite exactly the same (but with null termination, not size):

fstram.open(shaderPath);    
sstream << fstram.rdbuf();
fstram.close(); 

id = glCreateShader(type);

auto data = sstream.str();
const char* dataPtr = data.c_str();

glShaderSource(id, 1, &dataPtr, NULL);

There is fstram.rdbuf() and sstream.str() and data.c_str(). This is not really much simpler. One way or the other, there is some run up until you can pass that &dataPtr pseudo array.

(The name dataPtr is very...defensive)


Official specs:

const GLchar **string

string

Specifies an array of pointers to strings containing the source code to be loaded into the shader.

I prefer:

strings -- specifies an array of char pointers. These strings contain...

This might seem trivial, but after "slurping" in the whole file into one string, you wonder about this plural, or array of, or pointer to, or ampersand.


I see only slang/vstest.c in mesa-demos using size:

  f = fopen (filename, "r");
   if (f == NULL)
      return;

   fseek (f, 0, SEEK_END);
   size = ftell (f);

   if (size == -1) {
      fclose (f);
      return;
   }

   fseek (f, 0, SEEK_SET);

   code = (char *) (malloc (size));
   if (code == NULL) {
      fclose (f);
      return;
   }
   size = fread (code, 1, size, f);
   fclose (f);

   glShaderSourceARB (vert, 1, (const GLcharARB **) (&code), &size);

I prefer fstat() and mmap(), and (const char **)&code.

4
  • Welcome! I know virtually nothing about this subject, but I'm struggling to see how this answers the question?
    – josephkibe
    Apr 22, 2021 at 20:36
  • It is about passing the contents of a file to the GPU-RAM. See Rose's comment on Lars' good A. "... if you was using a .vert or .frag file instead of just strings and obscure gl data types". So I show how to read in a file, and not an artificial array of three strings. "this subject": you are not talking about pointers and arrays in C I guess. And deduce the rest you cannot?
    – user15741790
    Apr 22, 2021 at 20:58
  • Q is asking about const GLchar ** ("obscure") so I simplify to char and explain why it has two stars and show different ways to pacify the compiler. This must translate 99% to C++.
    – user15741790
    Apr 22, 2021 at 21:03
  • @josephkibe This is very related stackoverflow.com/questions/6400985/…
    – user15741790
    Apr 23, 2021 at 10:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.