sphere.cpp 835 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. /*
  2. * DoRayMe - a quick and dirty Raytracer
  3. * Sphere implementation
  4. *
  5. * Created by Manoël Trapier
  6. * Copyright (c) 2020 986-Studio.
  7. *
  8. */
  9. #include <math.h>
  10. #include <sphere.h>
  11. #include <ray.h>
  12. #include <tuple.h>
  13. #include <intersect.h>
  14. Intersect Sphere::intersect(Ray r)
  15. {
  16. Intersect ret;
  17. double a, b, c, discriminant;
  18. Ray transRay = this->invTransform(r);
  19. Tuple sphere_to_ray = transRay.origin - Point(0, 0, 0);
  20. a = transRay.direction.dot(transRay.direction);
  21. b = 2 * transRay.direction.dot(sphere_to_ray);
  22. c = sphere_to_ray.dot(sphere_to_ray) - 1;
  23. discriminant = b * b - 4 * a * c;
  24. if (discriminant >= 0)
  25. {
  26. ret.add(Intersection((-b - sqrt(discriminant)) / (2 * a), this));
  27. ret.add(Intersection((-b + sqrt(discriminant)) / (2 * a), this));
  28. }
  29. return ret;
  30. }