intersect.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. free(this->list[i]);
  33. }
  34. /* Free stuff */
  35. free(this->list);
  36. }
  37. void Intersect::reset()
  38. {
  39. this->num = 0;
  40. }
  41. void Intersect::add(Intersection i)
  42. {
  43. Intersection *x;
  44. int j, k;
  45. if ((this->num + 1) > this->allocated)
  46. {
  47. this->allocated *= 2;
  48. stats.addRealloc();
  49. this->list = (Intersection **)realloc(this->list, sizeof(Intersection *) * this->allocated);
  50. }
  51. this->list[this->num++] = new Intersection(i.t, i.object);
  52. stats.setMaxIntersect(this->num);
  53. /* Now sort.. */
  54. for(j = 1; j < (this->num); j++)
  55. {
  56. x = this->list[j];
  57. k = j;
  58. while( (k > 0) && (this->list[k - 1]->t) > x->t )
  59. {
  60. this->list[k] = this->list[k - 1];
  61. k--;
  62. }
  63. this->list[k] = x;
  64. }
  65. }
  66. Intersection Intersect::hit()
  67. {
  68. int i;
  69. for(i = 0; i < this->num; i++)
  70. {
  71. if (this->list[i]->t >= 0)
  72. return *this->list[i];
  73. }
  74. return Intersection(0, nullptr);
  75. }