GLSL built-in function
reflect()
Returns the direction a ray bounces to after hitting a surface: reflect(I, N) = I - 2.0 * dot(N, I) * N.
Syntax
vec2 reflect(vec2 I, vec2 N)
vec3 reflect(vec3 I, vec3 N)Parameters
- I
- The incoming direction, pointing toward the surface.
- N
- The surface normal. Must be normalized.
Return value
The reflected direction, with the same length as I.
Live example
Edit the code and the preview updates as you type.
How it works
Throw a ball at a wall and it bounces off at the same angle it came in. reflect(I, N) computes that bounce for a direction I hitting a surface with normal N:
vec3 r = reflect(I, N); // I - 2.0 * dot(N, I) * N
The part of I that goes into the surface is flipped; the part that runs along the surface is kept.
In the example the camera looks straight into the screen. For each pixel on the sphere, the view direction bounces off the surface normal, and the bounced direction is used to look up a simple sky-and-floor environment. The result looks like a chrome ball.
Typical uses
- Specular highlights (Phong):
pow(max(dot(reflect(-lightDir, normal), viewDir), 0.0), shininess). - Environment reflections: look up a sky color or cube map with the reflected direction.
- Bouncing particles: reflect the velocity when a particle hits a wall.
Common mistakes
- Passing the direction the wrong way.
Ipoints toward the surface. For a light direction that points from the surface to the light, usereflect(-lightDir, normal). - Using an unnormalized normal, which makes the bounce angle wrong. Always
normalize(N)first. - Swapping the arguments: the incoming direction comes first, the normal second.
Related functions
refract()
Returns the direction a ray takes after passing into a different material, like light bending as it enters glass or water.
normalize()
Returns a vector pointing in the same direction as x but with length 1.0. Keeps the direction, drops the size.
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.
Tutorials that use reflect()
- Phong Lighting ModelImplement the basic Phong lighting model to simulate ambient, diffuse, and specular highlights on object surfaces.
- Material Lighting CompareCompare Lambert, Phong, Blinn-Phong, and rim-light effects in one scene to understand their visual differences.
- Phong SpecularLearn core lighting terms (diffuse/specular/rim) on a simple sphere.
- Toon ShadingImplement a non-photorealistic rendering technique that simulates the visual style of cartoons or comic books by quantizing light intensity into discrete color levels, often combined with edge detection.