# Depth of Field in Path Tracing

In this article, I will share my experience with implementing depth-of-field effect in a path tracer.

Implementing depth of field in path tracing comes with two parameters: focal length, and aperture size. Focal length determines how far objects must be from the camera to be in focus; this number should always be positive. Aperture size will determine how blurry objects that are out of focus will appear.

The above image shows a ray that starts at the eye, goes through the image plane and intersects the focal plane at point P.

Calculating focal point P is the first step in creating a depth of field effect.

This point is calculated using three variables: ray.origin, ray.direction, and focal length.

The first two variables should be familiar in any path tracer, but the third is a new variable that comes as a parameter of depth of field. To get focal point P, simply multiply ray.direction by focal length. The focal point of all pixels will result in a spherical plane that is the same distance away from the camera in any given direction. Any objects that are intersected with on or near this focal plane will appear to be in focus, otherwise objects will appear out of focus.

Now that we know where focal point P is, we can begin to add the blur effect. This is done by shifting ray.origin using the aperture variable, then recalculating ray.direction that starts at new ray.origin and goes toward focal point P. For the first step of shifting the ray.origin, I used a random number generator that would give a random number in the range of -0.5 to 0.5 for each component of a vector then multiply that vector by aperture size then add that result on to ray. origin. This will effectively shift ray.origin in an even area surrounding the original ray.origin. The last step is a simple one which is to recalculate ray.direction which begins at this new ray.origin and goes toward the focal point P that we calculated earlier.

Below is an illustration of this process of shifting ray.origin in an aperture area and redirecting that ray to focal point P.