How does OpenGL interpolate variable variables on a fragment shader, even if they are set three times in the vertex shader?

Since the vertex shader is launched once per vertex (which means a triangle 3 times), how is a variable variable calculated for each fragment if it is 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 the system behind this knows how to calculate the v_Color variable for each fragment, since this shader assigns v_Color only 3 times (in the triangle).

+7
shader opengl glsl
source share
2 answers

All outputs of the vertex shader correspond to the vertices. When you set v_Color to the vertex shader, it sets it to the current vertex. When a fragment fragmenter is executed, it reads the v_Color value for each vertex in the primitive and interpolates between them based on the location of the fragment.

+4
source share

First of all, it is a mistake to assume that the vertex shader runs once per vertex. Using indexed rendering, a primitive assembly can typically access the Post T & L cache (the result of previous vertex shader calls) based on the vertex index to prevent vertex estimation more than once. However, new things, such as geometric shaders, can easily lead to its destruction.

As for how the fragment shader gets its value, which is usually done during rasterization. These per-vertex attributes are interpolated along the surface of the primitive (in this case, a triangle) based on the distance of the fragment relative to the vertices that were used to construct the primitive. In DX11, interpolation can be delayed until the fragment shader itself is executed (called pull-model interpolation), but traditionally this is what happens during rasterization.

+3
source share

All Articles