4.2.3  Short introduction to raytracing

Before we start looking at the code, let's look briefly how raytracing works. This will help you understand what the script is doing.

The basic idea of raytracing is to "shoot" rays from the camera towards the scene and see what does the ray hit. If the ray hits the surface of an object then lighting calculations are performed in order to get the color of the surface at that place.

The following image shows this graphically:

The basic raytracing algorithm
The basic raytracing algorithm

First a ray is "shot" in a specified direction to see if there's something there. As this is solved mathematically, we need to know the mathematical representation of the ray and the objects in the scene so that we can calculate where does the ray intersect the objects. Once we get all the intersection points, we choose the closest one.

After this we have to calculate the lighting (ie. the illumination) of the object at the intersection point. In the most basic lighting model (as the one used in the script) there are three main things that affect the lighting of the surface:

Don't worry if these things sound a bit confusing. Full details of all these things will be given through this tutorial, as we look what does the raytracing script do. The most important thing at this stage is to understand how the basic raytracing algorithm works at theoretical level (the image above should say most of it).

Let's just look at the raytracer source code line by line and look what does it do