Search code examples
javaopenglglsllwjgluniform

Why is my uniform not initializing in openGL?


Why are my uniform vector and float not being initialized? My shader code compiles correctly, my shader is compiling properly, but when I try to get the uniform location of my vec4 lightDirection, and floats specularFactor and diffuseFactor, it gives me an error. Note I haven't actually used these uniforms for anything yet, however, that shouldn't matter.

Here is my vertex shader, which gets all uniform locations properly:

#version 330
layout (location = 0) in vec3 position;
layout (location = 1) in vec2 texture_coord;
layout (location = 2) in vec3 normal;
layout (location = 3) in vec3 fNormal;

uniform mat4 worldMat;
uniform mat4 projection;
uniform mat4 transform;

out vec2 tex;
out vec3 n;
out vec3 fn;

void main() {
    fn=fNormal;
    n=normal;
    tex = texture_coord;
    gl_Position = projection * worldMat * transform * vec4(position, 1);

}

Here is my fragment shader, which only gets the texture sample uniform location:

#version 330
uniform sampler2D sampleTexture;
uniform vec4 lightDirection;
uniform float specularFactor;
uniform float diffuseFactor;


in vec2 tex;
in vec3 n;
in vec3 fn;

out vec4 fragColor;

void main() {
    fragColor=texture(sampleTexture, tex);

}

Here is the method I use to get uniform locations (I am using Java):

public int loadUniform(String uniformName)throws Exception{
        int iD= glGetUniformLocation(program,uniformName);
        System.out.println("PROGRAM: "+program+" UNIFORM: "+uniformName+" "+iD);
        if(iD==-1) {
                throw new Exception("uniform:"+uniformName+" not initialized");
        }
        return iD;
}

Now, here is what is printed in console by print statment/exception. Am confusion. Numbers definitely seem wrong, but whatevs. I don't understaaaaand.

java.lang.Exception: uniform:lightDirection not initialized
    at shader_src.Shader.loadUniform(Shader.java:273)
    at shader_src.StaticShader.initValues(StaticShader.java:51)
    at application.Main.main(Main.java:94)
PROGRAM: 4 UNIFORM: worldMat 9
PROGRAM: 4 UNIFORM: projection 5
PROGRAM: 4 UNIFORM: transform 0
PROGRAM: 4 UNIFORM: sampleTexture 4
PROGRAM: 4 UNIFORM: lightDirection -1

Solution

  • The glsl compiler and linker optimizes the code. Unnecessary code will be removed, and unnecessary uniforms and attributes will not become active program resources. If uniform variables are not used or are only used in a part of the code that is itself optimized out, they do not become active program resources. lightDirection, specularFactor and diffuseFactor are unused variables and therefore not active resources thus no active resources and therefore you cannot get a uniform location for these variables.