GLSL Learning

GLSL built-in function

abs()

Returns the absolute value of x: negative numbers become positive, positive numbers stay the same.

Syntax

float abs(float x)
vec2 abs(vec2 x)
vec3 abs(vec3 x)
vec4 abs(vec4 x)

Parameters

x
The value to take the absolute value of. Vectors are processed per component.

Return value

A value of the same type as x, with every component greater than or equal to 0.

Live example

Edit the code and the preview updates as you type.

How it works

abs(x) throws away the minus sign. abs(-0.7) is 0.7, abs(0.7) is also 0.7.

On a centered coordinate system (p from -1 to 1), abs(p.x) is 0 in the middle and grows toward both edges. That turns a straight ramp into a V shape, which is why the example draws a V.

float y = abs(p.x); // left edge 1.0, center 0.0, right edge 1.0

Typical uses

  • Mirror symmetry: abs(p.x) folds the left half of the canvas onto the right half, so anything you draw appears twice.
  • Distance to a line: abs(p.y - 0.3) is how far a pixel is from the horizontal line y = 0.3.
  • Box shapes: max(abs(p.x), abs(p.y)) gives square contours, the basis of rectangle SDFs.

Common mistakes

  • Using abs on integer literals in GLSL ES 1.0: write abs(-1.0), not abs(-1), because there is no integer overload.
  • Forgetting to center coordinates first. With uv in 0..1 every value is already positive, so abs(uv.x) does nothing.

Related functions

Tutorials that use abs()