Depth of Field in Path Tracing: What do I do with the secondary ray? How can I implement Depth of Field in my Path Tracer? I have read this article which explains the theory behind everything &amp; I already have a good understanding of what this effect needs to achieve based on previous experience with a DSLR but I am a little confused on how to code everything although I understand a most of the calculations involved (after reading the article linked above). 

I understand how to calculate the focal point, focal distance and the secondary ray. But I'm confused on how to put this all together to create the 'blur' that is needed. I haven't found much online so I was hoping that someone here could explain that with some code.

Could someone show me their implementation?
The missing step

If you already understand how to generate a secondary ray, then you have already grasped the difficult part. All you need to do now is find the colour that this secondary ray results in. This is exactly the same process as using the primary ray to find a colour, in basic ray tracing.

After repeating this for a large number of secondary rays, the average of all those colours is the colour you assign to the pixel in question (you don't use the primary ray - its only purpose is generating the secondary rays). This is the only difference from basic ray tracing.

Why it works

My personal difficulty when trying to understand this was that I was trying to understand how the light gets from the different points on the lens back to the eye/camera. The thing to understand is that this is only an approximation of a lens, and the rays don't need to consider the eye/camera at all.

The lens is being approximated by a disc.

All these different secondary rays show you what you would see from different points on that disc, if you looked directly towards a certain point (the focal point).


For an object at the focal point, all these different viewpoints will see the same point on the object, and the object will look sharply defined.
For an object behind the focal point, all these different viewpoints will see slightly different positions on the object, and some of them will miss the object and see what is to the side of it. The edges of the object will be blended with the colour of whatever is to the side of it.
For an object in front of the focal point, again the different viewpoints will see slightly different positions on the object, giving blurred edges.


If a primary ray hits an object at the focal distance, but there is a closer object which is not quite in the way, but almost, then some of the secondary rays will hit the closer object before they reach the focal point. This will give a blurred edge to the closer object, partially obscuring the object at the focal point, even though that object itself is in sharp focus.

All of this is as desired. To this level of explanation, this mimics the effect of a real lens, without having to consider refraction at all.