World.cpp 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. #include <cmath>
  2. #include "common/world/HighMap.h"
  3. #include "common/world/World.h"
  4. #include "utils/Logger.h"
  5. #include "utils/Random.h"
  6. World::World() : blocks(7, 7), dirty(true) {
  7. }
  8. void World::setBlock(int x, int y, int z, Block::Id block) {
  9. blocks.set(x, y, z, block);
  10. }
  11. Block::Id World::getBlock(int x, int y, int z) const {
  12. return blocks.get(x, y, z);
  13. }
  14. int World::getSize() const {
  15. return blocks.getSize();
  16. }
  17. int World::getHeight() const {
  18. return blocks.getHeight();
  19. }
  20. void World::addEntity(Entity* e) {
  21. entities.add(e);
  22. }
  23. void World::removeEntity(Entity* e) {
  24. for(int i = 0; i < entities.getLength(); i++) {
  25. if(entities[i] == e) {
  26. entities.removeBySwap(i);
  27. return;
  28. }
  29. }
  30. }
  31. List<Box> World::getBoxes(const Box& box) const {
  32. int minX = floorf(box.getMin()[0]);
  33. int minY = floorf(box.getMin()[1]);
  34. int minZ = floorf(box.getMin()[2]);
  35. int maxX = floorf(box.getMax()[0]);
  36. int maxY = floorf(box.getMax()[1]);
  37. int maxZ = floorf(box.getMax()[2]);
  38. List<Box> boxes;
  39. for(int x = minX; x <= maxX; x++) {
  40. for(int y = minY; y <= maxY; y++) {
  41. for(int z = minZ; z <= maxZ; z++) {
  42. Block::addBoxes(getBlock(x, y, z), boxes,
  43. Vector3(static_cast<float>(x),
  44. static_cast<float>(y),
  45. static_cast<float>(z)));
  46. }
  47. }
  48. }
  49. return boxes;
  50. }
  51. void World::tick() {
  52. for(Entity* e : entities) {
  53. e->tick();
  54. if(!e->skip) {
  55. Vector3 move = limitMove(*e, e->getVelocity());
  56. e->move(move);
  57. }
  58. }
  59. }
  60. Vector3 World::limitMove(const Entity& e, Vector3 move) const {
  61. Box box = e.getBox();
  62. List<Box> boxes = getBoxes(box.expand(move));
  63. if(boxes.getLength() == 0) {
  64. return move;
  65. }
  66. Vector3 realMove;
  67. constexpr float step = 0.05f;
  68. while(move[0] != 0.0f || move[1] != 0.0f || move[2] != 0.0f) {
  69. for(int i = 0; i < 3; i++) {
  70. Vector3 old = realMove;
  71. if(move[i] > step) {
  72. realMove[i] += step;
  73. move[i] -= step;
  74. } else if(move[i] < -step) {
  75. realMove[i] -= step;
  76. move[i] += step;
  77. } else if(move[i] != 0.0f) {
  78. realMove[i] += move[i];
  79. move[i] = 0.0f;
  80. }
  81. Box moved = box.offset(realMove);
  82. for(const Box& box : boxes) {
  83. if(box.collidesWith(moved)) {
  84. move[i] = 0.0f;
  85. realMove = old;
  86. break;
  87. }
  88. }
  89. }
  90. }
  91. return realMove;
  92. }