intersect.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. * DoRayMe - a quick and dirty Raytracer
  3. * Intersect implementation
  4. *
  5. * Created by Manoël Trapier
  6. * Copyright (c) 2020 986-Studio.
  7. *
  8. */
  9. #include <stdlib.h>
  10. #include <math_helper.h>
  11. #include <intersect.h>
  12. #include <float.h>
  13. #include <renderstat.h>
  14. #define MIN_ALLOC (2)
  15. /* TODO: Memory allocation, even if using standard calloc/realloc have a huge impact on performances. need to find a way
  16. * to reuse the intersect object without reallocating from scratch all the time. We use a lot of Intersect objects as
  17. * there is at least 2 per ray (one for Ray intersect object, one object per light)
  18. */
  19. Intersect::Intersect()
  20. {
  21. this->allocated = MIN_ALLOC;
  22. this->list = (Intersection **)calloc(sizeof(Intersection *), MIN_ALLOC);
  23. stats.addMalloc();
  24. stats.addIntersect();
  25. this->num = 0;
  26. }
  27. Intersect::~Intersect()
  28. {
  29. int i;
  30. for(i = 0; i < this->num; i++)
  31. {
  32. delete this->list[i];
  33. }
  34. /* Free stuff */
  35. if (this->list != nullptr)
  36. {
  37. free(this->list);
  38. }
  39. }
  40. void Intersect::reset()
  41. {
  42. this->num = 0;
  43. }
  44. void Intersect::add(Intersection i)
  45. {
  46. Intersection *x;
  47. int j, k;
  48. if ((this->num + 1) > this->allocated)
  49. {
  50. this->allocated *= 2;
  51. stats.addRealloc();
  52. this->list = (Intersection **)realloc(this->list, sizeof(Intersection *) * this->allocated);
  53. }
  54. this->list[this->num++] = new Intersection(i.t, i.object, i.u, i.v);
  55. stats.setMaxIntersect(this->num);
  56. /* Now sort.. */
  57. for(j = 1; j < (this->num); j++)
  58. {
  59. x = this->list[j];
  60. k = j;
  61. while( (k > 0) && (this->list[k - 1]->t) > x->t )
  62. {
  63. this->list[k] = this->list[k - 1];
  64. k--;
  65. }
  66. this->list[k] = x;
  67. }
  68. }
  69. Intersection Intersect::hit()
  70. {
  71. int i;
  72. for(i = 0; i < this->num; i++)
  73. {
  74. if (this->list[i]->t >= 0)
  75. return *this->list[i];
  76. }
  77. return Intersection(0, nullptr);
  78. }