Intrinsics1 min read

normalize

Returns a unit vector in the same direction.

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

Test normalize in a live shader

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

Open Playground

Live Demo

The normalize function returns a unit vector (length 1) pointing in the same direction as the input vector.

Signature

bwsl
normalize :: (vecN v) -> vecN {...}

Where vecN can be float2, float3, or float4.

Parameters

ParameterTypeDescription
vvecNThe vector to normalize

Return Value

Returns v / length(v), a unit vector in the direction of v.

Example

bwsl
pipeline BasicLighting {
fragment {
// Normalize interpolated vectors
float3 normal = normalize(input.normal);
float3 viewDir = normalize(cameraPos - input.worldPos);
float3 lightDir = normalize(lightPos - input.worldPos);
// Calculate lighting with normalized vectors
float diffuse = max(dot(normal, lightDir), 0.0);
float3 halfDir = normalize(lightDir + viewDir);
float specular = pow(max(dot(normal, halfDir), 0.0), 32.0);
float3 color = ambient + diffuse * diffuseColor + specular * specularColor;
output.color = float4(color, 1.0);
}
}

Common Use Cases

Direction Vectors

bwsl
// Get direction from A to B
float3 direction = normalize(targetPos - currentPos);

Lighting Calculations

bwsl
// All lighting vectors should be normalized
float3 N = normalize(normal);
float3 L = normalize(lightDirection);
float3 V = normalize(viewDirection);

Reflection/Refraction

bwsl
// Normalize before reflection
float3 incident = normalize(rayDir);
float3 normal = normalize(surfaceNormal);
float3 reflected = reflect(incident, normal);

Spherical Coordinates

bwsl
// Normalize to get point on unit sphere
float3 spherePoint = normalize(position);
float2 uv = float2(atan2(spherePoint.z, spherePoint.x), asin(spherePoint.y));

Interpolation of Directions

bwsl
// Renormalize after linear interpolation
float3 blendedNormal = lerp(normal1, normal2, t);
blendedNormal = normalize(blendedNormal);

Zero Vector

Normalizing a zero-length vector produces undefined results (typically NaN or infinity). Check for zero vectors: if (length(v) > 0.0001) v = normalize(v);

Interpolated Normals

Normals interpolated across a surface may not be unit length. Always normalize interpolated normals in the fragment shader before lighting calculations.

Compiled Output

When compiled to GLSL:

glsl
normalize(v)

When compiled to HLSL:

hlsl
normalize(v)

See Also

  • length - Vector magnitude
  • dot - Dot product
  • rsqrt - Inverse square root