# T2 Add a lambertian material inherits class material

### T2.1 Add a function near\_zero() in vec.h to check if a vector is close to zero in length

```cpp
class vec3 {
    ...

    double length_squared() const {
        return e[0]*e[0] + e[1]*e[1] + e[2]*e[2];
    }

    // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    bool near_zero() const {
        // Return true if the vector is close to zero in all dimensions.
        auto s = 1e-8;
        return (std::fabs(e[0]) < s) && (std::fabs(e[1]) < s) && (std::fabs(e[2]) < s);
    }
    // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    ...
};
```

### T2.2 Add a lambertian class in material.h

The lambertian class inherits from material and implements the scatter() method.

It calculates a random scattered ray direction at the hit point and sets the attenuation to its albedo colour.

<pre class="language-cpp"><code class="lang-cpp"><strong>class material {
</strong>  public:
    virtual ~material() = default;

    virtual bool scatter(
        const ray&#x26; r_in, const hit_record&#x26; rec, color &#x26; attenuation, ray&#x26; scattered
    ) const {
        return false;
    }
<strong>};
</strong><strong>
</strong><strong>// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
</strong><strong>class lambertian : public material {
</strong>  private:
    color albedo;
  public:
    lambertian(const color&#x26; albedo) : albedo(albedo) {}

  bool scatter(const ray&#x26; r_in, const hit_record&#x26; rec, color&#x26; attenuation, ray&#x26; scattered)
    const override {
        auto scatter_direction = rec.normal + random_unit_vector();

        // Catch degenerate scatter direction
        if (scatter_direction.near_zero())
            scatter_direction = rec.normal;

        scattered = ray(rec.p, scatter_direction);
        attenuation = albedo;
        return true;
    }
};

// &#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;&#x3C;
</code></pre>
