3

These are common glsl fragment shaders:

#version 450
#extension GL_ARB_separate_shader_objects : enable
layout(location = 0) in vec3 inColor;
layout(location = 0) out vec4 outColor;
void main(){
    outColor = vec4(inColor, 1.0);
}

I know that the vertex shader is executed once per vertex, and the fragment shader is executed once per fragment.

But why the outColor is vec4, which is only one pixel size (vec4 == rgba). If it is to output a fragment, shouldn't the outColor be larger?

1
  • 2
    outColor sets the color of 1 fragment. It addresses the the currently processed fragment in the framebuffer. Since the fragment shader runs per fragment, it can set the colors of all fragments. The fragment shader runs many times in parallel and each instance puts its result in the right place in the framebuffer. The result of an fragment shader instance is specified by setting the fragment shader output. Commented Jul 18, 2021 at 7:05

1 Answer 1

5

I think you are misunderstanding what a fragment actually is.

A fragment is a pixel... sort of. In the most basic sense, you can think of a fragment as a "potential pixel". Is has an rgba value, which is the value that will be drawn to the screen if it is rendered.

Imagine the simplest scenario: you are rendering a quad over the full screen, and your screen's size is 100x100. In this case, your fragment shader runs once for every fragment within that quad. For this program, that means 100 * 100 = 10000 times, once for every pixel on your screen.

However, not every fragment rendered in the shader has to be displayed on the screen. Let's make the scenario slightly more complex: you have two quads, once behind the other. You are just rendering these two quads, with depth testing enabled. Even though one quad is entirely behind the other, and won't be seen as it is occluded by the first quad, you still need to run the fragment shader for every "potential pixel" in the second quad. Just because a fragment isn't seen, doesn't mean you don't run the fragment shader for it. Unless you have early depth testing enabled, a fragment is only discarded after you run the fragment shader. In this case, the frag shader would run once for every fragment in both quads, so 20000 times.

So, in essence, you can think of a fragment as a pixel that may or may not end up being displayed. (This is quite a simplification but works to understand the basics)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.