Intrinsics1 min read

clamp

Clamps a value between a minimum and maximum.

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

Test clamp in a live shader

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

Open Playground

Live Demo

The clamp function constrains a value to lie within a specified range. If the value is less than the minimum, the minimum is returned; if greater than the maximum, the maximum is returned.

Signature

bwsl
clamp :: (T x, T minVal, T maxVal) -> T {...}

Where T can be float, float2, float3, float4, int, int2, int3, or int4.

Parameters

ParameterTypeDescription
xTValue to clamp
minValTMinimum bound
maxValTMaximum bound

Return Value

Returns min(max(x, minVal), maxVal).

Example

bwsl
pipeline ColorCorrection {
fragment {
float4 texColor = sample(inputTex, input.uv);
// Apply exposure and clamp to valid range
float3 exposed = texColor.rgb * exposure;
float3 clamped = clamp(exposed, float3(0.0), float3(1.0));
output.color = float4(clamped, texColor.a);
}
}

Common Use Cases

Keeping Values in Bounds

bwsl
// Ensure lighting doesn't exceed valid range
float3 finalLight = clamp(ambient + diffuse + specular, float3(0.0), float3(1.0));

Integer Index Clamping

bwsl
// Clamp array index to valid range
int index = clamp(computedIndex, 0, arraySize - 1);

UV Coordinate Clamping

bwsl
// Clamp UVs to prevent texture wrapping
float2 clampedUV = clamp(input.uv, float2(0.0), float2(1.0));

Audio/Signal Processing

bwsl
// Soft clipping for audio-like visualization
float amplitude = clamp(signal * gain, -1.0, 1.0);

Color Channel Constraints

bwsl
// Ensure each color channel stays valid
float3 color = clamp(processedColor, float3(0.0), float3(1.0));

Use saturate for [0,1]

When clamping to the range [0, 1], prefer saturate(x) over clamp(x, 0.0, 1.0). It's more readable and may be faster on some GPUs.

Integer Types

When using clamp with integer types, the appropriate SPIR-V operation (SClamp for signed, UClamp for unsigned) is selected automatically.

Compiled Output

When compiled to GLSL:

glsl
clamp(x, minVal, maxVal)

When compiled to HLSL:

hlsl
clamp(x, minVal, maxVal)

When compiled to Metal:

metal
clamp(x, minVal, maxVal)

See Also

  • saturate - Clamp to [0, 1]
  • min - Minimum of values
  • max - Maximum of values