# Can somebody explain this Ray Tracing Function?

I am currently reading through Peter Shirley's Ray Tracing in One Weekend. In the beginning chapters where the author introduces diffuse surfaces we a presented with this function:

vec3 color(const ray& r, hitable *world)
{
hit_record rec;
if(world->hit(r, 0.0, MAXFLOAT,rec))
{
vec3 target = rec.p + rec.normal + random_in_unit_sphere();
return 0.5*color(ray(rec.p, target-rec.p), world);
}
else
{
vec3 unit_direction = unit_vector(r.direction());
float t = 0.5*(unit_direction.y() + 1.0);
return (1.0-t)*vec3(1.0, 1.0, 1.0) + t*vec3(0.5, 0.7, 1.0);
}
}


Can somebody where the actual definition for the function is? Because in the first part of the ifthe return value is 0.5*color(ray(rec.p, target-rec.p), world);. Will it execute the function again except go through the else?

Regarding what the function actually does here is what I have gathered from the book based on my current understanding:

1. Pick a random point s from the unit radius sphere that is tangent to the hitpoint, and send a ray from the hitpoint p to the random point s. That sphere has center (p+N)

1. Which then gives us:

vec3 target = rec.p + rec.normal + random_in_unit_sphere();
return 0.5*color(ray(rec.p, target-rec.p), world);


this is the exact same as

vec3 targetDir = rec.normal + random_in_unit_sphere();
return 0.5*color(ray(rec.p, targetDir), world);


In other words the sphere is a way to pick a random direction which is biased towards the normal direction without doing a lot of fancy maths.

And yeah if that hits again it will repeat the process again and again until it hits the sky box. this can be avoided by adding a parameter to avoid unlimited recursion.

However that function is bad in general for a few reasons:

1. The color on hit should depend on the object's material (the color) and the relation between the normal vector the incoming eye ray and the outgoing light ray.

2. The light sky box is hardcoded to be a gradiant.

3. only a single recursive sample on each hit. This gives very grainy images and requires a lot of samples per pixel to converge to a proper image.

• Since the objective of the chapter is to implement Lambert could you suggest an alternative implementation? Where does the grey color from the sphere come from, is it set anywhere? – Arjan Singh Apr 10 '17 at 10:54

Good answer above. (I like that the book adds in p then subtracts it.)

This is a hard-coded grey world as a "hello world" kind of ray tracer. The 0.5 is the hard-coded reflectance. Keep working through book and the object reflectance and max-recursion will be addressed. Ray branching I avoid like the plague. In cost benefit I am always a skeptic on ray trees versus ray paths.