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 requiresmax(x, 0.0).
Related functions
min()
Returns the smaller of x and y. With vectors, each component is compared separately.
clamp()
Limits x to the range between minVal and maxVal, computed as min(max(x, minVal), maxVal).
dot()
Returns the dot product of two vectors. For unit vectors it measures how much they point the same way: 1.0 same direction, 0.0 perpendicular, -1.0 opposite.
Tutorials that use max()
- Shape CompositionCombine circle and rectangle masks to build more complex shapes using min/max or simple compositing.
- Ambient + DiffuseLearn core lighting terms (diffuse/specular/rim) on a simple sphere.
- Rim LightLearn core lighting terms (diffuse/specular/rim) on a simple sphere.
- Fake ShadowLearn core lighting terms (diffuse/specular/rim) on a simple sphere.
- Toon LightingLearn core lighting terms (diffuse/specular/rim) on a simple sphere.
- Point Light FalloffAdd distance falloff to a point light so illumination changes naturally over space.