Small optimization on sphere
This commit is contained in:
parent
b75663feab
commit
3aea707982
2 changed files with 13 additions and 6 deletions
11
main.cpp
11
main.cpp
|
|
@ -25,14 +25,15 @@ color ray_color(const ray& r)
|
|||
double hit_sphere(const point3& center, double radius, const ray& r)
|
||||
{
|
||||
vec3 oc = r.origin - center;
|
||||
double a = dot(r.direction, r.direction);
|
||||
double b = 2.0 * dot(oc, r.direction);
|
||||
double c = dot(oc,oc) - radius*radius;
|
||||
double discriminant = b*b - 4*a*c;
|
||||
double a = r.direction.length_squared();
|
||||
double half_b = dot(oc, r.direction);
|
||||
double c = oc.length_squared() - radius*radius;
|
||||
double discriminant = half_b*half_b - a*c;
|
||||
|
||||
if (discriminant < 0)
|
||||
return -1;
|
||||
else
|
||||
return (-b - sqrt(discriminant)) / (2.0*a);
|
||||
return (-half_b - sqrt(discriminant)) / a;
|
||||
}
|
||||
|
||||
int main()
|
||||
|
|
|
|||
6
vec3.hpp
6
vec3.hpp
|
|
@ -59,6 +59,12 @@ struct vec3 {
|
|||
{
|
||||
return sqrt(x*x + y*y + z*z);
|
||||
}
|
||||
|
||||
// Length squared, useful for some calculations
|
||||
double length_squared() const
|
||||
{
|
||||
return x*x + y*y + z*z;
|
||||
}
|
||||
};
|
||||
|
||||
/* Type aliases */
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue