Mod
Task
Create a pattern of alternating black and red columns, with 9 columns of each color. Then, hide every third column that is colored red.
Requirements
The shader should avoid using branching or conditional statements in its code, and instead rely on the mod and step functions to determine the color of each pixel.
Theory
The mod function is used to calculate the remainder of a division operation between two numbers. This function is particularly useful in graphics programming for creating repeating patterns, among other applications.
Function Signature
float mod(float x, float y);
How It Works
The mod function takes two arguments:
- Dividend: the number being divided
- Divisor: the number by which the dividend is being divided.
The function returns the remainder of the division operation.
Comparison with Modulo Operator
The mod function works similarly to the modulo operator (%) found in many programming languages. However, there are some differences in how negative numbers are handled. In GLSL, the mod function always returns a non-negative result.
Examples
Basic usage with positive numbers:
float result = mod(10.0, 3.0); // Result will be 1.0 (10 / 3 has a remainder of 1)
Handling negative numbers:
float result = mod(-10.0, 3.0); // Result will be 2.0 (-10 / 3 has a remainder of 2)
HLSL Equivalent
In HLSL, the exact same function exists under the name fmod. It behaves identically to mod in GLSL.
Practical Applications
• Creating Repeating Patterns: By using the mod function, you can create seamless, repeating textures or patterns.
• Animation: It can be used to loop animations by wrapping values within a certain range.
• Grid Systems: Useful for creating grid-based effects or dividing the screen into segments.