Search code examples
openglglslshadervarying

How does OpenGL interpolate varying variables on the fragment shader even if they are only set three times on the vertex shader?


Since vertex shader is run once per vertex (that mean in triangle 3 times), how does the varying variable gets computed for every fragment, if it's assigned (as in the example) only three times?

Fragment shader:

precision mediump float;
varying vec4 v_Color;

void main() {
    gl_FragColor = v_Color;
}

Vertex shader:

attribute vec4 a_Position;
attribute vec4 a_Color;

varying vec4 v_Color;

void main() {
    v_Color = a_Color;
    gl_Position = a_Position;
}

So, the question is, how does the system behind this know, how to compute the variable v_Color at every fragment, since this shader assigns v_Color only 3 times (in a triangle).


Solution

  • All outputs of the vertex shader are per vertex. When you set v_Color in the vertex shader, it sets it on the current vertex. When the fragment shader runs, it reads the v_Color value for each vertex in the primitive and interpolates between them based on the fragment's location.