Fract - Built-in functions - Shader Learning

Built-in functions

Fract

Task

Create a shader program that divides the normalized coordinate range of [0, 1] into 10 equal intervals across the entire width of the texture. Each interval should be 0.1 of the total screen width. The left half of each interval should be black, and the right half should be red. As a result, the program should produce a sequence of alternating black and red intervals across the entire width of the texture.


Requirements


The shader should avoid using branching or conditional statements in its code, and instead rely on the fract and step functions to determine the color of each pixel.

Theory

The fract function is used to return the fractional part of a floating-point value. The function takes a single argument, which can be a float, vec2, vec3, or vec4, and returns a value between 0.0 and 1.0.


Function Signature

float fract(float x)

How It Works


The fract function works by subtracting the integer part of the input value, leaving only the fractional part. For example, fract(3.14) would return 0.14, as the integer part of 3.14 is 3.


Examples


Here are some examples of using the fract function in GLSL:

Single float input:

float x = 3.75;
float fractionalPart = fract(x); // will be 0.75

Vector input:

vec2 v = vec2(1.25, 2.75);
vec2 fractionalParts = fract(v); // will be vec2(0.25, 0.75)

HLSL Equivalent


In HLSL, the exact same function exists under the name frac. It behaves identically to fract in GLSL and supports scalar and vector inputs.


The fract function is particularly useful in procedural texture generation, animation, and other graphics applications where you need to work with periodic patterns or wrap-around effects.