PDA

View Full Version : Regarding use of uniform variables in Frag Shaders



Mukund
08-06-2011, 09:57 AM
Hello Everyone,

I needed a small clarification w.r.t the following:

Say we have something like this:


// Fragment Shader
uniform float val;

void main(void)
{
float intensity = dot(vec3(gl_LightSource[0].position),normal);

if (intensity > 0.9)
gl_FragColor = vec4(val, val, val, 1);
}

Now, i could not understand why the uniform variables were used in this way. The "val" passed was a constant. So, wouldn't if make more sense with this:


if (intensity > 0.9)
gl_FragColor = vec4(0.5, 0.5, 0.5, 1); // assume val=0.5

Or, is there any specific reason behind using uniforms in Fragment shaders? I understand that using varying variables from vertex to fragment shader yields interpolation. But, is there any particular reason for using uniforms in Fragment shaders or is it just a way of passing data to the fragment shader?

Can anyone please clarify this for me?
Thanks.

Ilian Dinev
08-06-2011, 10:02 AM
If you write it as 0.5 , then it's forever-and-ever going to be 0.5
If you use an uniform, in one drawcall you can set it to 0.5, in the next drawcall you can set it to 0.6

Mukund
08-06-2011, 10:45 AM
Thanks for the reply Ilian Dinev. That's just what i wanted to know. So, for each fragment, the same value is passed right?

Is it possible for me to send different values for each fragment? Without using varying variables? in the same drawcall?

Ilian Dinev
08-06-2011, 11:07 AM
a uniform - constant throughout a drawcall, for all vertices and fragments and primitives
attributes - different values per vertex
varyings - interpolated values between processed vertex attributes.
textures - 2D arrays of constants
internals like gl_InstanceID, gl_PrimitiveID, gl_VertexID, - different and predictable on instance/primitive/vertex

To produce different fragment colors next to each other (from the same triangle, meaning from the same 3 processed vertices), you use the varyings (produced by attributes) to sample into textures, compare/multiply/add with constants.

And to produce different vertices from the same attributes, you use the instanceID/primitiveID/vertexID as a mutating factor, and possibly textures/uniforms as a second factor.

Mukund
08-06-2011, 11:22 AM
Thanks a lot Ilian Dinev for the detailed explanation.