clamp
Clamps a value between a minimum and maximum.
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 PlaygroundLive 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
clamp :: (T x, T minVal, T maxVal) -> T {...}
Where T can be float, float2, float3, float4, int, int2, int3, or int4.
Parameters
| Parameter | Type | Description |
|---|---|---|
x | T | Value to clamp |
minVal | T | Minimum bound |
maxVal | T | Maximum bound |
Return Value
Returns min(max(x, minVal), maxVal).
Example
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
// Ensure lighting doesn't exceed valid range
float3 finalLight = clamp(ambient + diffuse + specular, float3(0.0), float3(1.0));Integer Index Clamping
// Clamp array index to valid range
int index = clamp(computedIndex, 0, arraySize - 1);UV Coordinate Clamping
// Clamp UVs to prevent texture wrapping
float2 clampedUV = clamp(input.uv, float2(0.0), float2(1.0));Audio/Signal Processing
// Soft clipping for audio-like visualization
float amplitude = clamp(signal * gain, -1.0, 1.0);Color Channel Constraints
// 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:
clamp(x, minVal, maxVal)
When compiled to HLSL:
clamp(x, minVal, maxVal)
When compiled to Metal:
clamp(x, minVal, maxVal)