Question

I want to set a uniform Vector in my Vertex Shader.

int loc = glGetUniformLocation(shader, "LightPos");
if (loc != -1)
{
    //do Stuff
}

The problem is that loc is -1 all the time. I tried it with a variable from the Fragment Shader, that actually worked. The Vertex Shader:

uniform vec3 LightPos;
varying vec2 UVCoord;
varying float LightIntensity;

void main()
{           
    UVCoord = gl_MultiTexCoord0.st;
    gl_Position = ftransform();
    vec3 Normal = normalize(gl_NormalMatrix * gl_Normal);
    LightIntensity = max(dot(normalize(vec3(0, -10, 0)), Normal), 0.0);
}

The Fragment Shader:

uniform sampler2D tex1;
varying vec2 UVCoord;
varying float LightIntensity;

void main()
{
    vec3 Color = vec3(texture2D(tex1, UVCoord));
    gl_FragColor = vec4(Color * LightIntensity, 1.0);
}

Does anybody have an idea what I am doing wrong?

Was it helpful?

Solution

Unfortunately, you misunderstood how glGetUniformLocation (...) and uniform location assignment in general works.

Locations are only assigned after your shaders are compiled and linked. This is a two-phase operation that effectively identifies only the used inputs and outputs between all stages of a GLSL program (vertex, fragment, geometry, tessellation). Because LightPos is not used in your vertex shader (or anywhere else for that matter) it is not assigned a location when your program is linked. It simply ceases to exist.

This is where the term active uniform comes from. And glGetUniformLocation (...) only returns the location of active uniforms.


Name

glGetUniformLocation — Returns the location of a uniform variable

[...]

Description

glGetUniformLocation returns an integer that represents the location of a specific uniform variable within a program object. name must be a null terminated string that contains no white space. name must be an active uniform variable name in program that is not a structure, an array of structures, or a subcomponent of a vector or a matrix. This function returns -1 if name does not correspond to an active uniform variable in program, if name starts with the reserved prefix "gl_", or if name is associated with an atomic counter or a named uniform block.

OTHER TIPS

you don't actually use LightPos in the shader, so the optimiser didn't allocate any registers for it

the compiler is free to optimize uniforms and attribute out if they are not used

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top