Box.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. module Core.Box;
  2. import Core.Std;
  3. import Core.ToString;
  4. using Core::Box;
  5. Box::Box(const Vector3& min_, const Vector3& max_) : min(min_), max(max_) {
  6. }
  7. Box::Box(const Vector3& size) : min(), max() {
  8. for(size_t i = 0; i < 3; i++) {
  9. if(size[i] < 0.0f) {
  10. min[i] = size[i];
  11. } else {
  12. max[i] = size[i];
  13. }
  14. }
  15. }
  16. Box Box::offset(const Vector3& offset) const {
  17. return Box(min + offset, max + offset);
  18. }
  19. bool Box::collidesWith(const Box& other) const {
  20. return max[0] > other.min[0] && min[0] < other.max[0] &&
  21. max[1] > other.min[1] && min[1] < other.max[1] &&
  22. max[2] > other.min[2] && min[2] < other.max[2];
  23. }
  24. Box Box::expand(const Vector3& offset) const {
  25. Vector3 add(
  26. offset[0] > 0.0f ? offset[0] : 0.0f,
  27. offset[1] > 0.0f ? offset[1] : 0.0f,
  28. offset[2] > 0.0f ? offset[2] : 0.0f);
  29. Vector3 sub(
  30. offset[0] < 0.0f ? offset[0] : 0.0f,
  31. offset[1] < 0.0f ? offset[1] : 0.0f,
  32. offset[2] < 0.0f ? offset[2] : 0.0f);
  33. return Box(min + sub, max + add);
  34. }
  35. Box Box::grow(const Vector3& growth) const {
  36. Vector3 half = growth * 0.5f;
  37. Vector3 nMin = min - half;
  38. Vector3 nMax = max + half;
  39. for(size_t i = 0; i < 3; i++) {
  40. if(nMin[i] > nMax[i]) {
  41. nMin[i] = (min[i] + max[i]) * 0.5f;
  42. nMax[i] = nMin[i];
  43. }
  44. }
  45. return Box(nMin, nMax);
  46. }
  47. const Core::Vector3& Box::getMin() const {
  48. return min;
  49. }
  50. const Core::Vector3& Box::getMax() const {
  51. return max;
  52. }
  53. size_t Box::toString(char* s, size_t n) const {
  54. return formatBuffer(
  55. s, n, "Box([{.2}, {.2}, {.2}], [{.2}, {.2}, {.2}])", min[0], min[1],
  56. min[2], max[0], max[1], max[2]);
  57. }