GLSL built-in function
refract()
Returns the direction a ray takes after passing into a different material, like light bending as it enters glass or water.
Syntax
vec2 refract(vec2 I, vec2 N, float eta)
vec3 refract(vec3 I, vec3 N, float eta)Parameters
- I
- The incoming direction, normalized, pointing toward the surface.
- N
- The surface normal, normalized.
- eta
- The ratio of refractive indices, outside / inside. Air into glass is 1.0 / 1.5.
Return value
The refracted direction, or a zero vector when total internal reflection happens.
Live example
Edit the code and the preview updates as you type.
How it works
When light crosses from one material into another it changes direction. How much depends on the ratio of the two refractive indices, eta:
| from / to | eta |
|---|---|
| air into water | 1.0 / 1.33 |
| air into glass | 1.0 / 1.5 |
| glass into air | 1.5 / 1.0 |
refract(I, N, eta) returns that new direction. In the example the view ray enters a glass sphere, bends toward the center, and the bent direction is used to offset where the checkerboard background is sampled. That is why the board looks magnified and flipped inside the ball.
Typical uses
- Glass, water and lenses: offset a background lookup by the refracted direction.
- Raytracing transparent objects: continue the ray inside the object along the refracted direction.
Common mistakes
- Not normalizing
IandN. The formula assumes unit vectors. - Inverting
eta. Going from air into glass is1.0 / 1.5, not1.5. - Ignoring total internal reflection. When light leaves a dense material at a shallow angle,
refractreturnsvec3(0.0). Check for it and fall back toreflect.
Related functions
reflect()
Returns the direction a ray bounces to after hitting a surface: reflect(I, N) = I - 2.0 * dot(N, I) * N.
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.