slicedpan's picture

Can't get uniform locations using GL.GetUniformLocation

Hi, I am using the following code to load a vertex and fragment shader from files and then link them into a shader program.
The compiling/linking doesn't raise any errors, however I can't get the location of any of the uniforms defined in the shaders.

GL.CompileShader(vertexHandle);	
GL.CompileShader(fragHandle);
 
_glHandle = GL.CreateProgram();
GL.AttachShader(_glHandle, vertexHandle);
GL.AttachShader(_glHandle, fragHandle);
GL.LinkProgram(_glHandle);
 
Console.WriteLine(GL.GetProgramInfoLog(_glHandle));	//this does not generate any error message
 
GL.UseProgram(_glHandle);
 
int count;
GL.GetProgram(_glHandle, ProgramParameter.ActiveUniforms, out count);
Console.WriteLine(count.ToString() + " active uniforms");
 
int uniformLocation = GL.GetUniformLocation(_glHandle, "blah");
if (uniformLocation < 0)
	throw new Exception("couldn't get uniform location!");    //this exception gets thrown every time

The shader in question looks like this:

#version 330
 
layout(location = 0) in vec3 Position;
layout(location = 1) in vec3 Normal;
layout(location = 2) in vec2 TexCoord;
 
uniform float blah;
 
out vec3 out_Color;
 
void main()
{
    gl_Position = vec4(Position, 1);        
}

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
c2woody's picture

Depending on the shader compiler the "blah" uniform may be optimized away so the location is not accessible.

tksuoran's picture

Unused uniforms will not get location assigned to them.

You can use following code to see what uniforms you have:

int size;
ActiveUniformType type;
int uniformCount;
 
GL.GetProgram(ProgramObject, ProgramParameter.ActiveUniforms, out uniformCount);
for(int i = 0; i < uniformCount; ++i)
{
    string  name = GL.GetActiveUniform(ProgramObject, i, out size, out type);
    int slot = GL.GetUniformLocation(ProgramObject, name);
}
slicedpan's picture

Thanks guys!

It actually was being optimized away since I didn't actually use the uniform in the shaders.
Thanks for the code tksuoran, some of that might end up in my project!