ddy
Computes the partial derivative with respect to screen-space y.
Test ddy in a live shader
Open the playground, start from a visual preset, and wire ddy into the fragment stage to see how it behaves with real values.
Open PlaygroundLive Demo
The ddy function computes the partial derivative of a value with respect to the screen-space y coordinate. This is only available in fragment shaders.
Signature
ddy :: (T x) -> T {...}
Where T can be float, float2, float3, or float4.
Parameters
| Parameter | Type | Description |
|---|---|---|
x | T | The value to differentiate |
Return Value
Returns the rate of change of x per screen pixel in the vertical direction.
Example
pipeline FlatNormals {
@fragment_only
fragment {
// Calculate face normal from world position derivatives
float3 dPdx = ddx(input.worldPos);
float3 dPdy = ddy(input.worldPos);
float3 flatNormal = normalize(cross(dPdx, dPdy));
// Use flat normal for faceted look
float3 lightDir = normalize(lightPos - input.worldPos);
float diffuse = max(dot(flatNormal, lightDir), 0.0);
output.color = float4(baseColor * diffuse, 1.0);
}
}Common Use Cases
Face Normal Calculation
// Flat shading from interpolated positions
float3 dPdx = ddx(worldPos);
float3 dPdy = ddy(worldPos);
float3 geometryNormal = normalize(cross(dPdx, dPdy));Mipmap Selection
// Calculate optimal mip level
float2 dUVdx = ddx(texCoord);
float2 dUVdy = ddy(texCoord);
float delta = max(dot(dUVdx, dUVdx), dot(dUVdy, dUVdy));
float mip = 0.5 * log2(delta);Gradient Calculation
// Get screen-space gradient direction
float2 gradient = float2(ddx(value), ddy(value));
float gradientMagnitude = length(gradient);Normal Map Detail
// Blend normal map based on view angle
float3 dTdx = ddx(tangent);
float3 dTdy = ddy(tangent);
float detailFade = saturate(1.0 / (1.0 + length(dTdx) + length(dTdy)));Depth Gradient
// Calculate depth slope for shadow bias
float depthDx = ddx(depth);
float depthDy = ddy(depth);
float slopeBias = max(abs(depthDx), abs(depthDy)) * biasScale;Y Direction
Note that the y direction in screen space typically points downward (increasing y = lower on screen), though this can vary by API and framebuffer configuration.
Fragment Shader Only
Derivative functions are only available in fragment shaders. Using them elsewhere will cause a compilation error.
Compiled Output
When compiled to GLSL:
Uses the target backend's native y-derivative operation.
When compiled to HLSL:
ddy(x)
When compiled to SPIR-V:
Uses OpDPdy instruction.