GLSL Learning

GLSL built-in function

max()

Returns the larger of x and y. With vectors, each component is compared separately.

Syntax

float max(float x, float y)
vec2 max(vec2 x, vec2 y)
vec2 max(vec2 x, float y)
vec3 max(vec3 x, vec3 y)
vec3 max(vec3 x, float y)

Parameters

x
The first value.
y
The second value. Can be a float even when x is a vector.

Return value

The larger value, with the same type as x.

Live example

Edit the code and the preview updates as you type.

How it works

max(x, y) returns whichever value is larger. max(0.3, 0.8) is 0.8.

With signed distance fields, a pixel is inside a shape when its distance is below 0. max of two distances is below 0 only if both are, so the example draws the intersection of two circles: the lens-shaped area where they overlap.

float d = max(da, db); // intersection of two shapes

Typical uses

  • Clamping lighting to zero: max(dot(normal, lightDir), 0.0) stops surfaces facing away from the light from going negative. This line appears in almost every lighting shader.
  • Intersecting shapes: max(sdfA, sdfB).
  • Cutting a shape: max(sdfA, -sdfB) removes B from A.

Common mistakes

  • Forgetting max(..., 0.0) around a dot product, which produces negative light and dark artifacts on the back of objects.
  • Writing max(x, 0) with an integer. GLSL ES 1.0 requires max(x, 0.0).

Related functions

Tutorials that use max()