Search code examples
c#openglopentk

GetUniformLocation() returns -1


The code

GL.GetUniformLocation();

returns -1 for the uniform "transform" in the glsl code

#version 420

layout(location = 0) in vec3 position;

uniform mat4 transform;
void main()
{
    gl_Position = transform * vec4(position, 1.0);
}

The only other post I could find about this talked about the optimizer compiling it out, but I don't see how it could do that as it is essential in the final output of the shader. I am using Windows and the normal compiler. When I run GL.GetError() I get a InvalidOperation error.

The full code is

C# code:

    public void AddUniform(string Uniform)
    {
        int tries = 6;
        Start:
        int UniLocation = GL.GetUniformLocation(Program, Uniform);

#if DEBUG
        tries--;
        if(UniLocation == -1)
        {
            Console.WriteLine(this.ToString() + " Failed DEBUG AddUniform check");
            if (tries > 0)
            {
                goto Start;
            }
        }
#endif
        Uniforms.Add(Uniform, UniLocation);
    }

Uniforms is a Dictionary<string, int>

Shader code:

#version 420

layout(location = 0) in vec3 position;

uniform mat4 transform = mat4(1.0);
void main()
{

    gl_Position = transform * vec4(position, 1.0);
}

The Implementation:

        NewWindow.Init(() =>
        {
            mesh = new MobiusEngine.NewSystems.Mesh();
            shader = new MobiusEngine.NewSystems.Shader();

            mesh.AddVerticies(new MobiusEngine.NewSystems.Vertex(new OpenTK.Vector3d(-1, -1, 0)), new MobiusEngine.NewSystems.Vertex(new OpenTK.Vector3d(0, 1, 0)), new MobiusEngine.NewSystems.Vertex(new OpenTK.Vector3d(1, -1, 0)));

            shader.AddVertexShader(MobiusEngine.NewSystems.ShaderFunctions.LoadShader("BasicVertex.vert"));
            shader.AddFragmentShader(MobiusEngine.NewSystems.ShaderFunctions.LoadShader("BasicFrag.frag"));
            shader.AddUniform("transform");

            shader.ComplieShader();

        });
        double temp = 0d;
        NewWindow.Render(() =>
        {
            shader.Bind();
            shader.SetUniformM("transform", Matrix4.CreateTranslation((float)(Math.Abs(Math.Sin(temp))), 0, 0));
            temp += Time.DeltaTime.TotalSeconds;

            mesh.Draw();
        });

Solution

  • You obviously try to query the location before the shader is compiled and the program is linked here:

           shader.AddUniform("transform");
    
           shader.ComplieShader();
    

    Uniform locations are assigned during linking.