intersect.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. #define MIN_ALLOC (2)
  14. Intersect::Intersect()
  15. {
  16. this->allocated = MIN_ALLOC;
  17. this->list = (Intersection **)calloc(sizeof(Intersection *), MIN_ALLOC);
  18. this->num = 0;
  19. }
  20. Intersect::~Intersect()
  21. {
  22. /* Free stuff */
  23. free(this->list);
  24. }
  25. void Intersect::add(Intersection i)
  26. {
  27. Intersection *x;
  28. int j, k;
  29. if ((this->num + 1) > this->allocated)
  30. {
  31. this->allocated *= 2;
  32. this->list = (Intersection **)realloc(this->list, sizeof(Intersection *) * this->allocated);
  33. }
  34. this->list[this->num++] = new Intersection(i.t, i.object);
  35. /* Now sort.. */
  36. for(j = 1; j < (this->num); j++)
  37. {
  38. x = this->list[j];
  39. k = j;
  40. while( (k > 0) && (this->list[k - 1]->t) > x->t )
  41. {
  42. this->list[k] = this->list[k - 1];
  43. k--;
  44. }
  45. this->list[k] = x;
  46. }
  47. }
  48. Intersection Intersect::hit()
  49. {
  50. int i;
  51. for(i = 0; i < this->num; i++)
  52. {
  53. if (this->list[i]->t >= 0)
  54. return *this->list[i];
  55. }
  56. return Intersection(0, nullptr);
  57. }