GLSL built-in function
normalize()
Returns a vector pointing in the same direction as x but with length 1.0. Keeps the direction, drops the size.
Syntax
vec2 normalize(vec2 x)
vec3 normalize(vec3 x)
vec4 normalize(vec4 x)Parameters
- x
- The vector to normalize. Must not be a zero vector.
Return value
x / length(x), a unit vector with the same type as x.
Live example
Edit the code and the preview updates as you type.
How it works
A vector has a direction and a length. normalize keeps the direction and sets the length to exactly 1:
normalize(vec2(3.0, 4.0)) // vec2(0.6, 0.8), length 1.0
The example colors each pixel by a vector from the center. On the left the raw vector is used, so colors fade toward gray near the middle where the vector is short. On the right the same vectors are normalized: every pixel has full-strength color and only the direction matters, which gives clean color sectors.
Typical uses
- Lighting directions: light and view directions must be unit vectors for
dotto give a proper 0..1 brightness. - Surface normals: after computing or interpolating a normal,
normalizeit before using it. - Ray directions:
normalize(vec3(p, -1.0))builds a camera ray in a raymarcher.
Common mistakes
- Normalizing a zero vector.
normalize(vec2(0.0))divides by zero and returns NaN, typically a black pixel at the exact center. Add a tiny offset or check the length first. - Normalizing colors.
normalize(color)changes brightness in a way that rarely looks right; it is meant for directions. - Forgetting to re-normalize after adding two unit vectors.
normalize(lightDir + viewDir)is the half vector; the sum alone is too long.
Related functions
length()
Returns the length of a vector, its distance from the origin. length(p) is the starting point for drawing circles.
dot()
Returns the dot product of two vectors. For unit vectors it measures how much they point the same way: 1.0 same direction, 0.0 perpendicular, -1.0 opposite.
faceforward()
Returns N or -N, whichever points against the incoming direction I. Makes normals face the viewer for two-sided lighting.
Tutorials that use normalize()
- Ambient + DiffuseLearn core lighting terms (diffuse/specular/rim) on a simple sphere.
- Half-LambertLearn core lighting terms (diffuse/specular/rim) on a simple sphere.
- Normal VisualizerLearn core lighting terms (diffuse/specular/rim) on a simple sphere.
- Rim LightLearn core lighting terms (diffuse/specular/rim) on a simple sphere.
- Fake ShadowLearn core lighting terms (diffuse/specular/rim) on a simple sphere.
- Toon LightingLearn core lighting terms (diffuse/specular/rim) on a simple sphere.