Search code examples
c#openglsharpgl

How to use GetActiveUniform?


Generally, question is in header.

I cannot understand how to use GetActiveUniform function.

public void GetActiveUniform(uint program, 
                             uint index, 
                             int bufSize, 
                             int[] length, 
                             int[] size, 
                             uint[] type, 
                             string name);

My attempt looks like this (everything is compiled and linked):

        int[] numberOfUniforms = new int[1];
        Gl.GetProgram(programId, ProgramParameter.ActiveUniforms, numberOfUniforms);

        int[] uniformNameMaxLength = new int[1];
        Gl.GetProgram(programId, ProgramParameter.ActiveUniformMaxLength, uniformNameMaxLength);

        int unifromCount = numberOfUniforms[0];

        for (uint i = 0; i < unifromCount; i++)
        {
            var uniformSize = new int[1];
            var unifromLength = new int[1];
            var uniformType = new uint[1];
            string uniformName = "";

            Gl.GetActiveUniform(programId, i, uniformNameMaxLength[0], unifromLength, uniformSize, uniformType, uniformName);
        }

Vertex shader:

#version 150 core

in vec3 in_Position;
out vec3 pass_Color;
uniform vec3 color;

void main(void) {
    gl_Position = vec4(in_Position, 1.0);
    pass_Color = color;
}

After call I get proper uniformSize, length and type, but not name.


Solution

  • In terms of OpenGL usage, you're doing this correctly. The problem comes from the SharpGL bindings you are using. Since the last parameter is declared to be of type string and strings are (mostly) immutable in .NET, the function has no way to output the name to you. Short of modifying the bindings yourself, you have two options:

    • Check if SharpGL offers another overload of GetActiveUniform which takes a mutable object as the name parameter, such as a StringBuilder, a char[] or maybe even an out string (by reference).
    • Use another bindings library. OpenTK is a really good, clean and well-maintained one. It uses ref parameters instead of having you create tons of one-element arrays. I highly recommend it.