T6 Show Surface Normal as Colours

Return the Intersections

In the previous example, we only calculated if a ray hits a sphere. To show surface normals we need to know the intersection point. We are going to revise hit_sphere to return the ray parameter at the intersection point as follows:

double hit_sphere(const point3& center, double radius, const ray& r) {
    vec3 oc = center - r.origin();
    auto a = dot(r.direction(), r.direction());
    auto b = -2.0 * dot(r.direction(), oc);
    auto c = dot(oc, oc) - radius*radius;
    auto discriminant = b*b - 4*a*c;

    if (discriminant < 0) {
        return -1.0;
    } else {
        return (-b - std::sqrt(discriminant) ) / (2.0*a);
    }
}

Show Normals as the Colour

We are going to revise ray_color to show the normal at the intersected point.

As the sphere is located at (0, 0, -1), we calculate the vector from the sphere center tothe intersection point, which is the surface normal after normalisation.

Build and Run Your Program

You will see the following:

Simplification of Ray-Sphere Intersection Calculation

We can do a bit simplification on the discriminant and intersection calculation to remove those 2 and 4 in the formula.

Let h=b2h = \frac{-b}{2}, the intersection can be calculated as

t=h±h2acat = \frac{h \pm \sqrt{h^2 - ac}}{a}

Last updated