cube.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. * DoRayMe - a quick and dirty Raytracer
  3. * Cube implementation
  4. *
  5. * Created by Manoël Trapier
  6. * Copyright (c) 2020 986-Studio.
  7. *
  8. */
  9. #include <tuple.h>
  10. #include <ray.h>
  11. #include <shape.h>
  12. #include <cube.h>
  13. #include <math_helper.h>
  14. void Cube::checkAxis(double axeOrigin, double axeDirection, double *axeMin, double *axeMax)
  15. {
  16. double tMinNumerator = (-1 - axeOrigin);
  17. double tMaxNumerator = (1 - axeOrigin);
  18. if (fabs(axeDirection) >= getEpsilon())
  19. {
  20. *axeMin = tMinNumerator / axeDirection;
  21. *axeMax = tMaxNumerator / axeDirection;
  22. }
  23. else
  24. {
  25. *axeMin = tMinNumerator * INFINITY;
  26. *axeMax = tMaxNumerator * INFINITY;
  27. }
  28. if (*axeMin > *axeMax)
  29. {
  30. double swap = *axeMax;
  31. *axeMax = *axeMin;
  32. *axeMin = swap;
  33. }
  34. }
  35. void Cube::localIntersect(Ray r, Intersect &xs)
  36. {
  37. double xtMin, xtMax, ytMin, ytMax, ztMin, ztMax;
  38. double tMin, tMax;
  39. this->checkAxis(r.origin.x, r.direction.x, &xtMin, &xtMax);
  40. this->checkAxis(r.origin.y, r.direction.y, &ytMin, &ytMax);
  41. this->checkAxis(r.origin.z, r.direction.z, &ztMin, &ztMax);
  42. tMin = max3(xtMin, ytMin, ztMin);
  43. tMax = min3(xtMax, ytMax, ztMax);
  44. if (tMin <= tMax)
  45. {
  46. xs.add(Intersection(tMin, this));
  47. xs.add(Intersection(tMax, this));
  48. }
  49. }
  50. Tuple Cube::localNormalAt(Tuple point, Intersection *hit)
  51. {
  52. double maxC = max3(fabs(point.x), fabs(point.y), fabs(point.z));
  53. if (maxC == fabs(point.x))
  54. {
  55. return Vector(point.x, 0, 0);
  56. }
  57. else if (maxC == fabs(point.y))
  58. {
  59. return Vector(0, point.y, 0);
  60. }
  61. return Vector(0, 0, point.z);
  62. }
  63. void Cube::dumpMe(FILE *fp)
  64. {
  65. fprintf(fp, "\"Type\": \"Cube\",\n");
  66. Tuple t = this->transformMatrix * Point(0, 0, 0);
  67. fprintf(fp, "\"center\": { \"x\": %f, \"y\": %f, \"z\": %f}, \n",
  68. t.x, t.y, t.z);
  69. t = this->transformMatrix * Point(1, 1, 1);
  70. fprintf(fp, "\"corner\": { \"x\": %f, \"y\": %f, \"z\": %f}, \n",
  71. t.x, t.y, t.z);
  72. Shape::dumpMe(fp);
  73. }