# 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:

```cpp
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.

```cpp
color ray_color(const ray& r) {
    auto t = hit_sphere(point3(0,0,-1), 0.5, r);
    if (t > 0.0) {
        vec3 N = unit_vector(r.at(t) - vec3(0,0,-1));
        return 0.5*color(N.x()+1, N.y()+1, N.z()+1);
    }

    vec3 unit_direction = unit_vector(r.direction());
    auto a = 0.5*(unit_direction.y() + 1.0);
    return (1.0-a)*color(1.0, 1.0, 1.0) + a*color(0.5, 0.7, 1.0);
}
```

#### Build and Run Your Program

```
./ray01.exe > image4.ppm
```

You will see the following:

<figure><img src="https://3464970502-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3JUKGJZ67JX02QZdPhsy%2Fuploads%2F24jSCUWru769FnyLzcxQ%2F9a0e0b21-4be9-4014-9190-9b9f26ee1902.png?alt=media&#x26;token=dcc75321-dc11-4895-9f2d-f448cac68bea" alt="" width="316"><figcaption></figcaption></figure>

#### 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 = \frac{-b}{2}$$, the intersection can be calculated as

&#x20; $$t = \frac{h \pm \sqrt{h^2 - ac}}{a}$$

```cpp
double hit_sphere(const point3& center, double radius, const ray& r) {
    vec3 oc = center - r.origin();
    auto a = r.direction().length_squared();
    auto h = dot(r.direction(), oc);
    auto c = oc.length_squared() - radius*radius;
    auto discriminant = h*h - a*c;

    if (discriminant < 0) {
        return -1.0;
    } else {
        return (h - std::sqrt(discriminant)) / a;
    }
}
```
