Pixel Position - Built-in functions - Shader Learning

Built-in functions

Pixel Position

Task

Every pixel has an $X$ position - how far it is from the left side of the screen. Let's use that value and if statement to decide how to color the pixel:

  • If the $X$ position is less than 200.0, we'll color it red.
  • Otherwise, we'll leave it black.

This way, the first 200 pixels from the left will form a red stripe, and the rest of the screen will stay black.

Theory

GLSL

void main() {
  vec2 screenPosition = gl_FragCoord.xy;
}

• gl_FragCoord is a built-in variable that gives the position of the pixel on the screen.

• It is a vec4 (a group of 4 numbers), but we usually use just .x and .y - the horizontal and vertical position.


HLSL


1. Define the Input

struct PSInput {
    float4 position : SV_Position;
};

• This struct is like a container that holds data for each pixel.

• The field position is tagged with SV_Position, which tells the GPU that this is the pixel's position on the screen.

• It's automatically filled in by DirectX - you don't have to set it yourself.


2. Write the Pixel Shader Function

float4 main(PSInput input) : SV_Target {
    float2 screenPosition = input.position.xy;
}

• The main function takes PSInput as input, so you can access the pixel's position using input.position.

• .xy gives you the horizontal and vertical screen coordinates.