Schlick reflection

This commit is contained in:
Armin Friedl 2022-07-30 18:58:41 +02:00
parent 7ca342d5a4
commit 0a0080ce80

View file

@ -57,27 +57,36 @@ public:
virtual bool scatter(const ray &r_in, const hit_record &rec, virtual bool scatter(const ray &r_in, const hit_record &rec,
color &attenuation, ray &scattered) const override { color &attenuation, ray &scattered) const override {
attenuation = color(1.0, 1.0, 1.0); attenuation = color(1.0, 1.0, 1.0);
double refraction_ratio = rec.front_face ? (1.0/ir) : ir; double refraction_ratio = rec.front_face ? (1.0 / ir) : ir;
vec3 unit_direction = unit_vector(r_in.direction()); vec3 unit_direction = unit_vector(r_in.direction());
double cos_theta = fmin(dot(-unit_direction, rec.normal), 1.0); double cos_theta = fmin(dot(-unit_direction, rec.normal), 1.0);
double sin_theta = sqrt(1.0 - cos_theta*cos_theta); double sin_theta = sqrt(1.0 - cos_theta * cos_theta);
bool cannot_refract = refraction_ratio * sin_theta > 1.0; bool cannot_refract = refraction_ratio * sin_theta > 1.0;
vec3 direction; vec3 direction;
if (cannot_refract) if (cannot_refract ||
direction = reflect(unit_direction, rec.normal); reflectance(cos_theta, refraction_ratio) > random_double())
else direction = reflect(unit_direction, rec.normal);
direction = refract(unit_direction, rec.normal, refraction_ratio); else
direction = refract(unit_direction, rec.normal, refraction_ratio);
scattered = ray(rec.p, direction); scattered = ray(rec.p, direction);
return true; return true;
} }
public: public:
double ir; double ir;
private:
static double reflectance(double cosine, double ref_idx) {
// Use Schlick's approximation for reflectance
auto r0 = (1 - ref_idx) / (1 + ref_idx);
r0 = r0 * r0;
return r0 + (1 - r0) * pow((1 - cosine), 5);
}
}; };
#endif // MATERIAL_H_ #endif // MATERIAL_H_