Intrinsics1 min read

max

Returns the maximum of two or more values.

Reading Time
1 min
Word Count
154
Sections
12
Try It Live

Test max in a live shader

Open the playground, start from a visual preset, and wire max into the fragment stage to see how it behaves with real values.

Open Playground

Live Demo

The max function returns the largest of the input values. It supports both two-argument and variadic forms, accepting any number of arguments.

Signature

bwsl
max :: (T a, T b) -> T {...}
max :: (T a, T b, T c, ...) -> T {...}

Where T can be float, float2, float3, float4, int, int2, int3, int4, uint, uint2, uint3, or uint4.

Parameters

ParameterTypeDescription
a, b, ...TValues to compare

Return Value

Returns the maximum value among all inputs.

Example

bwsl
pipeline BloomEffect {
fragment {
// Extract bright areas for bloom
float4 color = sample(sceneTex, input.uv);
// Find the brightest channel
float brightness = max(color.r, color.g, color.b);
// Threshold for bloom
float bloomMask = max(brightness - bloomThreshold, 0.0);
output.color = color * bloomMask;
}
}

Common Use Cases

Preventing Negative Values

bwsl
// Ensure diffuse lighting is never negative
float diffuse = max(dot(normal, lightDir), 0.0);

Finding Brightest Channel

bwsl
// Get luminance approximation via max
float maxChannel = max(color.r, max(color.g, color.b));

Distance Field Operations

bwsl
// Intersection of two shapes (SDF)
float shape = max(sphereDist, boxDist);

Safe Division Denominator

bwsl
// Prevent division by zero
float safeValue = value / max(abs(denominator), 0.0001);

Depth Buffer Comparisons

bwsl
// Find furthest depth
float maxDepth = max(depth1, depth2, depth3, depth4);

Variadic Support

BWSL's max function accepts 2 to 255 arguments. When more than 2 arguments are provided, they are combined pairwise during compilation.

Vector Operations

When used with vectors, max operates component-wise. Use with a scalar to floor all components: max(color, float3(0.0)).

Compiled Output

When compiled to GLSL:

glsl
max(a, b)

When compiled to HLSL:

hlsl
max(a, b)

See Also

  • min - Minimum of values
  • clamp - Clamp to range