Intrinsics1 min read

saturate

Clamps a value to the range [0, 1].

Reading Time
1 min
Word Count
133
Sections
10
Try It Live

Test saturate in a live shader

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

Open Playground

Live Demo

The saturate function clamps a value to the range [0, 1]. It's equivalent to clamp(x, 0.0, 1.0) but is more readable and may be more optimized on some platforms.

Signature

bwsl
saturate :: (T x) -> T {...}

Where T can be float, float2, float3, or float4.

Parameters

ParameterTypeDescription
xTThe value to clamp

Return Value

Returns the input value clamped to the range [0, 1].

Example

bwsl
fragment {
// Calculate fresnel effect
float3 viewDir = normalize(-input.worldPos);
float3 normal = normalize(input.normal);
float NdotV = dot(normal, viewDir);
float fresnel = saturate(1.0 - NdotV); // Clamp to [0, 1]
// Use fresnel for rim lighting
float3 rimColor = float3(0.0, 0.8, 1.0) * pow(fresnel, 3.0);
output.color = float4(rimColor, 1.0);
}

Common Use Cases

Preventing Negative Values

bwsl
// Diffuse lighting should never be negative
float diffuse = saturate(dot(normal, lightDir));

Normalizing Computed Values

bwsl
// Ensure blend factor stays in valid range
float blend = saturate(height / maxHeight);

Fresnel Calculations

bwsl
// Standard Schlick fresnel
float fresnel = saturate(pow(1.0 - dot(normal, viewDir), 5.0));

Performance Note

On most GPUs, saturate is essentially free when applied to the result of another operation, as it can be folded into the instruction modifier.

Compiled Output

When compiled to GLSL:

glsl
clamp(x, 0.0, 1.0)

When compiled to HLSL:

hlsl
saturate(x)

See Also

  • clamp - Clamp to arbitrary range
  • smoothstep - Smooth hermite interpolation
  • lerp - Linear interpolation