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)
|
double hit_sphere(const point3& center, double radius, const ray& r)
|
||||||
{
|
{
|
||||||
vec3 oc = r.origin - center;
|
vec3 oc = r.origin - center;
|
||||||
double a = dot(r.direction, r.direction);
|
double a = r.direction.length_squared();
|
||||||
double b = 2.0 * dot(oc, r.direction);
|
double half_b = dot(oc, r.direction);
|
||||||
double c = dot(oc,oc) - radius*radius;
|
double c = oc.length_squared() - radius*radius;
|
||||||
double discriminant = b*b - 4*a*c;
|
double discriminant = half_b*half_b - a*c;
|
||||||
|
|
||||||
if (discriminant < 0)
|
if (discriminant < 0)
|
||||||
return -1;
|
return -1;
|
||||||
else
|
else
|
||||||
return (-b - sqrt(discriminant)) / (2.0*a);
|
return (-half_b - sqrt(discriminant)) / a;
|
||||||
}
|
}
|
||||||
|
|
||||||
int main()
|
int main()
|
||||||
|
|
|
||||||
8
vec3.hpp
8
vec3.hpp
|
|
@ -58,7 +58,13 @@ struct vec3 {
|
||||||
double length() const
|
double length() const
|
||||||
{
|
{
|
||||||
return sqrt(x*x + y*y + z*z);
|
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 */
|
/* Type aliases */
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue