intersect.cpp 1.7 KB

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