Following both shaders assume uv is centered at (0.0, 0.0) with values from -1.0 to +1.0 (for instance, vec2 p = uv * 2.0 - 1.0; when starting from standard 0.0 to 1.0 coordinates). They use only basic arithmetic and if conditions, without relying on built-in GLSL helper functions.
1. Drawing a Square with if Conditions
A square aligned with the X and Y axes is defined by a simple rule: both its horizontal (x) and vertical (y) coordinates must stay within a chosen distance from the center.
How the Square Shader Works
- The coordinate grid: Every pixel runs
main()independently. Mappingpto a range from-1.0to+1.0puts(0.0, 0.0)right in the middle of the screen. - Testing horizontal walls:
p.xmust be greater than or equal to-halfSize(left edge) and less than or equal to+halfSize(right edge). - Testing vertical walls:
p.ymust be greater than or equal to-halfSize(bottom edge) and less than or equal to+halfSize(top edge). - Why nesting helps beginners: Putting the
ycheck inside thexcheck makes the logic read like two gates in sequence a pixel only gets colored if it passes both horizontal and vertical checks.
2. Drawing a Diamond with if Conditions
A diamond centered at (0.0, 0.0) follows a different rule: the sum of the absolute values of x and y must be less than or equal to a radius value.
How the Diamond Shader Works
- Flipping negative numbers: If
absXis less than0.0, multiplying or negating it (-absX) turns it positive. The exact same check runs forabsY. - Adding the distances (
absX + absY): Along the X axis (whereyis0.0), the edge hits atx = ±radius. Along the Y axis (wherexis0.0), the edge hits aty = ±radius. Along the diagonals (wherexandyare equal),absX + absYreachesradiussooner athalfRadiuson each axis which naturally creates diagonal edges and sharp corners. - Square vs. Diamond in plain math: A square checks
max(|x|, |y|) <= halfSize(both axes bounded independently), whereas a diamond checks|x| + |y| <= radius(their sum bounded together).
Tutorial Notes for Beginners
- Start with a mental picture of pixels: A fragment shader does not “draw a line” from point A to point B like a pen. Instead, it asks every single pixel: “Given your
(x, y)coordinate, what color should you be?” - Move the center or change the size easily:
- To shift a shape right by
0.3, subtract0.3fromp.x(for example,float x = p.x - 0.3;) before checking bounds. - To resize, change
halfSizeorradiuslarger numbers make the shape bigger, and smaller numbers shrink it. - A practical note as learners advance: Using
ifbranches is great for seeing how coordinates map to geometry, though in larger production shaders developers often replaceifconditions with smooth math expressions to keep GPU execution uniform.