step
Generates a step function by comparing two values.
Test step in a live shader
Open the playground, start from a visual preset, and wire step into the fragment stage to see how it behaves with real values.
Open PlaygroundLive Demo
The step function returns 0 if x < edge, otherwise it returns 1. This creates a hard threshold or step transition at the edge value.
Signature
step :: (T edge, T x) -> T {...}
Where T can be float, float2, float3, or float4.
Parameters
| Parameter | Type | Description |
|---|---|---|
edge | T | Threshold value |
x | T | Value to test |
Return Value
Returns 0.0 if x < edge, otherwise returns 1.0.
Example
pipeline ThresholdEffect {
fragment {
// Convert grayscale to black and white
float4 texColor = sample(inputTex, input.uv);
float gray = dot(texColor.rgb, float3(0.299, 0.587, 0.114));
// Hard threshold at 0.5
float bw = step(0.5, gray);
output.color = float4(float3(bw), 1.0);
}
}Common Use Cases
Cel Shading Bands
// Create distinct lighting bands
float NdotL = dot(normal, lightDir);
float band1 = step(0.0, NdotL);
float band2 = step(0.5, NdotL);
float lighting = 0.3 + 0.35 * band1 + 0.35 * band2;Sharp Cutoff
// Clip pixels below alpha threshold
float visible = step(0.5, texColor.a);
if (visible < 0.5) discard;Grid Lines
// Draw grid lines
float2 grid = abs(fract(input.uv * 10.0) - 0.5);
float line = 1.0 - step(0.45, min(grid.x, grid.y));Distance Field Shapes
// Hard-edged circle from distance field
float dist = length(input.uv - 0.5);
float circle = 1.0 - step(0.25, dist);Branchless Selection
The step function is useful for branchless conditional selection: a * step(threshold, x) + b * (1.0 - step(threshold, x)) selects a when x >= threshold, otherwise b.
Parameter Order
Note that the parameter order is step(edge, x), not step(x, edge). The edge comes first, then the value being tested.
Compiled Output
When compiled to GLSL:
step(edge, x)
When compiled to HLSL:
step(edge, x)
See Also
- smoothstep - Smooth threshold transition
- select - Conditional select
- clamp - Clamp to range