2
0

collision.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. /*
  2. Minetest
  3. Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #include "collision.h"
  17. #include "mapblock.h"
  18. #include "map.h"
  19. #include "nodedef.h"
  20. #include "gamedef.h"
  21. #ifndef SERVER
  22. #include "clientenvironment.h"
  23. #endif
  24. #include "serverenvironment.h"
  25. #include "serverobject.h"
  26. #include "util/timetaker.h"
  27. #include "profiler.h"
  28. // float error is 10 - 9.96875 = 0.03125
  29. //#define COLL_ZERO 0.032 // broken unit tests
  30. #define COLL_ZERO 0
  31. struct NearbyCollisionInfo {
  32. NearbyCollisionInfo(bool is_ul, bool is_obj, int bouncy,
  33. const v3s16 &pos, const aabb3f &box) :
  34. is_unloaded(is_ul),
  35. is_object(is_obj),
  36. bouncy(bouncy),
  37. position(pos),
  38. box(box)
  39. {}
  40. bool is_unloaded;
  41. bool is_step_up = false;
  42. bool is_object;
  43. int bouncy;
  44. v3s16 position;
  45. aabb3f box;
  46. };
  47. // Helper function:
  48. // Checks for collision of a moving aabbox with a static aabbox
  49. // Returns -1 if no collision, 0 if X collision, 1 if Y collision, 2 if Z collision
  50. // The time after which the collision occurs is stored in dtime.
  51. int axisAlignedCollision(
  52. const aabb3f &staticbox, const aabb3f &movingbox,
  53. const v3f &speed, f32 d, f32 *dtime)
  54. {
  55. //TimeTaker tt("axisAlignedCollision");
  56. f32 xsize = (staticbox.MaxEdge.X - staticbox.MinEdge.X) - COLL_ZERO; // reduce box size for solve collision stuck (flying sand)
  57. f32 ysize = (staticbox.MaxEdge.Y - staticbox.MinEdge.Y); // - COLL_ZERO; // Y - no sense for falling, but maybe try later
  58. f32 zsize = (staticbox.MaxEdge.Z - staticbox.MinEdge.Z) - COLL_ZERO;
  59. aabb3f relbox(
  60. movingbox.MinEdge.X - staticbox.MinEdge.X,
  61. movingbox.MinEdge.Y - staticbox.MinEdge.Y,
  62. movingbox.MinEdge.Z - staticbox.MinEdge.Z,
  63. movingbox.MaxEdge.X - staticbox.MinEdge.X,
  64. movingbox.MaxEdge.Y - staticbox.MinEdge.Y,
  65. movingbox.MaxEdge.Z - staticbox.MinEdge.Z
  66. );
  67. if(speed.X > 0) // Check for collision with X- plane
  68. {
  69. if (relbox.MaxEdge.X <= d) {
  70. *dtime = -relbox.MaxEdge.X / speed.X;
  71. if ((relbox.MinEdge.Y + speed.Y * (*dtime) < ysize) &&
  72. (relbox.MaxEdge.Y + speed.Y * (*dtime) > COLL_ZERO) &&
  73. (relbox.MinEdge.Z + speed.Z * (*dtime) < zsize) &&
  74. (relbox.MaxEdge.Z + speed.Z * (*dtime) > COLL_ZERO))
  75. return 0;
  76. }
  77. else if(relbox.MinEdge.X > xsize)
  78. {
  79. return -1;
  80. }
  81. }
  82. else if(speed.X < 0) // Check for collision with X+ plane
  83. {
  84. if (relbox.MinEdge.X >= xsize - d) {
  85. *dtime = (xsize - relbox.MinEdge.X) / speed.X;
  86. if ((relbox.MinEdge.Y + speed.Y * (*dtime) < ysize) &&
  87. (relbox.MaxEdge.Y + speed.Y * (*dtime) > COLL_ZERO) &&
  88. (relbox.MinEdge.Z + speed.Z * (*dtime) < zsize) &&
  89. (relbox.MaxEdge.Z + speed.Z * (*dtime) > COLL_ZERO))
  90. return 0;
  91. }
  92. else if(relbox.MaxEdge.X < 0)
  93. {
  94. return -1;
  95. }
  96. }
  97. // NO else if here
  98. if(speed.Y > 0) // Check for collision with Y- plane
  99. {
  100. if (relbox.MaxEdge.Y <= d) {
  101. *dtime = -relbox.MaxEdge.Y / speed.Y;
  102. if ((relbox.MinEdge.X + speed.X * (*dtime) < xsize) &&
  103. (relbox.MaxEdge.X + speed.X * (*dtime) > COLL_ZERO) &&
  104. (relbox.MinEdge.Z + speed.Z * (*dtime) < zsize) &&
  105. (relbox.MaxEdge.Z + speed.Z * (*dtime) > COLL_ZERO))
  106. return 1;
  107. }
  108. else if(relbox.MinEdge.Y > ysize)
  109. {
  110. return -1;
  111. }
  112. }
  113. else if(speed.Y < 0) // Check for collision with Y+ plane
  114. {
  115. if (relbox.MinEdge.Y >= ysize - d) {
  116. *dtime = (ysize - relbox.MinEdge.Y) / speed.Y;
  117. if ((relbox.MinEdge.X + speed.X * (*dtime) < xsize) &&
  118. (relbox.MaxEdge.X + speed.X * (*dtime) > COLL_ZERO) &&
  119. (relbox.MinEdge.Z + speed.Z * (*dtime) < zsize) &&
  120. (relbox.MaxEdge.Z + speed.Z * (*dtime) > COLL_ZERO))
  121. return 1;
  122. }
  123. else if(relbox.MaxEdge.Y < 0)
  124. {
  125. return -1;
  126. }
  127. }
  128. // NO else if here
  129. if(speed.Z > 0) // Check for collision with Z- plane
  130. {
  131. if (relbox.MaxEdge.Z <= d) {
  132. *dtime = -relbox.MaxEdge.Z / speed.Z;
  133. if ((relbox.MinEdge.X + speed.X * (*dtime) < xsize) &&
  134. (relbox.MaxEdge.X + speed.X * (*dtime) > COLL_ZERO) &&
  135. (relbox.MinEdge.Y + speed.Y * (*dtime) < ysize) &&
  136. (relbox.MaxEdge.Y + speed.Y * (*dtime) > COLL_ZERO))
  137. return 2;
  138. }
  139. //else if(relbox.MinEdge.Z > zsize)
  140. //{
  141. // return -1;
  142. //}
  143. }
  144. else if(speed.Z < 0) // Check for collision with Z+ plane
  145. {
  146. if (relbox.MinEdge.Z >= zsize - d) {
  147. *dtime = (zsize - relbox.MinEdge.Z) / speed.Z;
  148. if ((relbox.MinEdge.X + speed.X * (*dtime) < xsize) &&
  149. (relbox.MaxEdge.X + speed.X * (*dtime) > COLL_ZERO) &&
  150. (relbox.MinEdge.Y + speed.Y * (*dtime) < ysize) &&
  151. (relbox.MaxEdge.Y + speed.Y * (*dtime) > COLL_ZERO))
  152. return 2;
  153. }
  154. //else if(relbox.MaxEdge.Z < 0)
  155. //{
  156. // return -1;
  157. //}
  158. }
  159. return -1;
  160. }
  161. // Helper function:
  162. // Checks if moving the movingbox up by the given distance would hit a ceiling.
  163. bool wouldCollideWithCeiling(
  164. const std::vector<NearbyCollisionInfo> &cinfo,
  165. const aabb3f &movingbox,
  166. f32 y_increase, f32 d)
  167. {
  168. //TimeTaker tt("wouldCollideWithCeiling");
  169. assert(y_increase >= 0); // pre-condition
  170. for (const auto &it : cinfo) {
  171. const aabb3f &staticbox = it.box;
  172. if ((movingbox.MaxEdge.Y - d <= staticbox.MinEdge.Y) &&
  173. (movingbox.MaxEdge.Y + y_increase > staticbox.MinEdge.Y) &&
  174. (movingbox.MinEdge.X < staticbox.MaxEdge.X) &&
  175. (movingbox.MaxEdge.X > staticbox.MinEdge.X) &&
  176. (movingbox.MinEdge.Z < staticbox.MaxEdge.Z) &&
  177. (movingbox.MaxEdge.Z > staticbox.MinEdge.Z))
  178. return true;
  179. }
  180. return false;
  181. }
  182. static inline void getNeighborConnectingFace(const v3s16 &p,
  183. const NodeDefManager *nodedef, Map *map, MapNode n, int v, int *neighbors)
  184. {
  185. MapNode n2 = map->getNodeNoEx(p);
  186. if (nodedef->nodeboxConnects(n, n2, v))
  187. *neighbors |= v;
  188. }
  189. collisionMoveResult collisionMoveSimple(Environment *env, IGameDef *gamedef,
  190. f32 pos_max_d, const aabb3f &box_0,
  191. f32 stepheight, f32 dtime,
  192. v3f *pos_f, v3f *speed_f,
  193. v3f accel_f, ActiveObject *self,
  194. bool collideWithObjects)
  195. {
  196. static bool time_notification_done = false;
  197. Map *map = &env->getMap();
  198. //TimeTaker tt("collisionMoveSimple");
  199. ScopeProfiler sp(g_profiler, "collisionMoveSimple avg", SPT_AVG);
  200. collisionMoveResult result;
  201. /*
  202. Calculate new velocity
  203. */
  204. if (dtime > 0.5f) {
  205. if (!time_notification_done) {
  206. time_notification_done = true;
  207. infostream << "collisionMoveSimple: maximum step interval exceeded,"
  208. " lost movement details!"<<std::endl;
  209. }
  210. dtime = 0.5f;
  211. } else {
  212. time_notification_done = false;
  213. }
  214. *speed_f += accel_f * dtime;
  215. // If there is no speed, there are no collisions
  216. if (speed_f->getLength() == 0)
  217. return result;
  218. // Limit speed for avoiding hangs
  219. speed_f->Y = rangelim(speed_f->Y, -5000, 5000);
  220. speed_f->X = rangelim(speed_f->X, -5000, 5000);
  221. speed_f->Z = rangelim(speed_f->Z, -5000, 5000);
  222. /*
  223. Collect node boxes in movement range
  224. */
  225. std::vector<NearbyCollisionInfo> cinfo;
  226. {
  227. //TimeTaker tt2("collisionMoveSimple collect boxes");
  228. ScopeProfiler sp2(g_profiler, "collisionMoveSimple collect boxes avg", SPT_AVG);
  229. v3f newpos_f = *pos_f + *speed_f * dtime;
  230. v3f minpos_f(
  231. MYMIN(pos_f->X, newpos_f.X),
  232. MYMIN(pos_f->Y, newpos_f.Y) + 0.01f * BS, // bias rounding, player often at +/-n.5
  233. MYMIN(pos_f->Z, newpos_f.Z)
  234. );
  235. v3f maxpos_f(
  236. MYMAX(pos_f->X, newpos_f.X),
  237. MYMAX(pos_f->Y, newpos_f.Y),
  238. MYMAX(pos_f->Z, newpos_f.Z)
  239. );
  240. v3s16 min = floatToInt(minpos_f + box_0.MinEdge, BS) - v3s16(1, 1, 1);
  241. v3s16 max = floatToInt(maxpos_f + box_0.MaxEdge, BS) + v3s16(1, 1, 1);
  242. bool any_position_valid = false;
  243. v3s16 p;
  244. for (p.X = min.X; p.X <= max.X; p.X++)
  245. for (p.Y = min.Y; p.Y <= max.Y; p.Y++)
  246. for (p.Z = min.Z; p.Z <= max.Z; p.Z++) {
  247. bool is_position_valid;
  248. MapNode n = map->getNodeNoEx(p, &is_position_valid);
  249. if (is_position_valid && n.getContent() != CONTENT_IGNORE) {
  250. // Object collides into walkable nodes
  251. any_position_valid = true;
  252. const NodeDefManager *nodedef = gamedef->getNodeDefManager();
  253. const ContentFeatures &f = nodedef->get(n);
  254. if (!f.walkable)
  255. continue;
  256. int n_bouncy_value = itemgroup_get(f.groups, "bouncy");
  257. int neighbors = 0;
  258. if (f.drawtype == NDT_NODEBOX &&
  259. f.node_box.type == NODEBOX_CONNECTED) {
  260. v3s16 p2 = p;
  261. p2.Y++;
  262. getNeighborConnectingFace(p2, nodedef, map, n, 1, &neighbors);
  263. p2 = p;
  264. p2.Y--;
  265. getNeighborConnectingFace(p2, nodedef, map, n, 2, &neighbors);
  266. p2 = p;
  267. p2.Z--;
  268. getNeighborConnectingFace(p2, nodedef, map, n, 4, &neighbors);
  269. p2 = p;
  270. p2.X--;
  271. getNeighborConnectingFace(p2, nodedef, map, n, 8, &neighbors);
  272. p2 = p;
  273. p2.Z++;
  274. getNeighborConnectingFace(p2, nodedef, map, n, 16, &neighbors);
  275. p2 = p;
  276. p2.X++;
  277. getNeighborConnectingFace(p2, nodedef, map, n, 32, &neighbors);
  278. }
  279. std::vector<aabb3f> nodeboxes;
  280. n.getCollisionBoxes(gamedef->ndef(), &nodeboxes, neighbors);
  281. for (auto box : nodeboxes) {
  282. box.MinEdge += intToFloat(p, BS);
  283. box.MaxEdge += intToFloat(p, BS);
  284. cinfo.emplace_back(false, false, n_bouncy_value, p, box);
  285. }
  286. } else {
  287. // Collide with unloaded nodes (position invalid) and loaded
  288. // CONTENT_IGNORE nodes (position valid)
  289. aabb3f box = getNodeBox(p, BS);
  290. cinfo.emplace_back(true, false, 0, p, box);
  291. }
  292. }
  293. // Do not move if world has not loaded yet, since custom node boxes
  294. // are not available for collision detection.
  295. // This also intentionally occurs in the case of the object being positioned
  296. // solely on loaded CONTENT_IGNORE nodes, no matter where they come from.
  297. if (!any_position_valid) {
  298. *speed_f = v3f(0, 0, 0);
  299. return result;
  300. }
  301. } // tt2
  302. if(collideWithObjects)
  303. {
  304. ScopeProfiler sp2(g_profiler, "collisionMoveSimple objects avg", SPT_AVG);
  305. //TimeTaker tt3("collisionMoveSimple collect object boxes");
  306. /* add object boxes to cinfo */
  307. std::vector<ActiveObject*> objects;
  308. #ifndef SERVER
  309. ClientEnvironment *c_env = dynamic_cast<ClientEnvironment*>(env);
  310. if (c_env != 0) {
  311. f32 distance = speed_f->getLength();
  312. std::vector<DistanceSortedActiveObject> clientobjects;
  313. c_env->getActiveObjects(*pos_f, distance * 1.5f, clientobjects);
  314. for (auto &clientobject : clientobjects) {
  315. if (!self || (self != clientobject.obj)) {
  316. objects.push_back((ActiveObject*) clientobject.obj);
  317. }
  318. }
  319. }
  320. else
  321. #endif
  322. {
  323. ServerEnvironment *s_env = dynamic_cast<ServerEnvironment*>(env);
  324. if (s_env != NULL) {
  325. f32 distance = speed_f->getLength();
  326. std::vector<u16> s_objects;
  327. s_env->getObjectsInsideRadius(s_objects, *pos_f, distance * 1.5f);
  328. for (u16 obj_id : s_objects) {
  329. ServerActiveObject *current = s_env->getActiveObject(obj_id);
  330. if (!self || (self != current)) {
  331. objects.push_back((ActiveObject*)current);
  332. }
  333. }
  334. }
  335. }
  336. for (std::vector<ActiveObject*>::const_iterator iter = objects.begin();
  337. iter != objects.end(); ++iter) {
  338. ActiveObject *object = *iter;
  339. if (object) {
  340. aabb3f object_collisionbox;
  341. if (object->getCollisionBox(&object_collisionbox) &&
  342. object->collideWithObjects()) {
  343. cinfo.emplace_back(false, true, 0, v3s16(), object_collisionbox);
  344. }
  345. }
  346. }
  347. } //tt3
  348. /*
  349. Collision detection
  350. */
  351. /*
  352. Collision uncertainty radius
  353. Make it a bit larger than the maximum distance of movement
  354. */
  355. f32 d = pos_max_d * 1.1f;
  356. // A fairly large value in here makes moving smoother
  357. //f32 d = 0.15*BS;
  358. // This should always apply, otherwise there are glitches
  359. assert(d > pos_max_d); // invariant
  360. int loopcount = 0;
  361. while(dtime > BS * 1e-10f) {
  362. //TimeTaker tt3("collisionMoveSimple dtime loop");
  363. ScopeProfiler sp2(g_profiler, "collisionMoveSimple dtime loop avg", SPT_AVG);
  364. // Avoid infinite loop
  365. loopcount++;
  366. if (loopcount >= 100) {
  367. warningstream << "collisionMoveSimple: Loop count exceeded, aborting to avoid infiniite loop" << std::endl;
  368. break;
  369. }
  370. aabb3f movingbox = box_0;
  371. movingbox.MinEdge += *pos_f;
  372. movingbox.MaxEdge += *pos_f;
  373. int nearest_collided = -1;
  374. f32 nearest_dtime = dtime;
  375. int nearest_boxindex = -1;
  376. /*
  377. Go through every nodebox, find nearest collision
  378. */
  379. for (u32 boxindex = 0; boxindex < cinfo.size(); boxindex++) {
  380. NearbyCollisionInfo box_info = cinfo[boxindex];
  381. // Ignore if already stepped up this nodebox.
  382. if (box_info.is_step_up)
  383. continue;
  384. // Find nearest collision of the two boxes (raytracing-like)
  385. f32 dtime_tmp;
  386. int collided = axisAlignedCollision(box_info.box,
  387. movingbox, *speed_f, d, &dtime_tmp);
  388. if (collided == -1 || dtime_tmp >= nearest_dtime)
  389. continue;
  390. nearest_dtime = dtime_tmp;
  391. nearest_collided = collided;
  392. nearest_boxindex = boxindex;
  393. }
  394. if (nearest_collided == -1) {
  395. // No collision with any collision box.
  396. *pos_f += *speed_f * dtime;
  397. dtime = 0; // Set to 0 to avoid "infinite" loop due to small FP numbers
  398. } else {
  399. // Otherwise, a collision occurred.
  400. NearbyCollisionInfo &nearest_info = cinfo[nearest_boxindex];
  401. const aabb3f& cbox = nearest_info.box;
  402. // Check for stairs.
  403. bool step_up = (nearest_collided != 1) && // must not be Y direction
  404. (movingbox.MinEdge.Y < cbox.MaxEdge.Y) &&
  405. (movingbox.MinEdge.Y + stepheight > cbox.MaxEdge.Y) &&
  406. (!wouldCollideWithCeiling(cinfo, movingbox,
  407. cbox.MaxEdge.Y - movingbox.MinEdge.Y,
  408. d));
  409. // Get bounce multiplier
  410. float bounce = -(float)nearest_info.bouncy / 100.0f;
  411. // Move to the point of collision and reduce dtime by nearest_dtime
  412. if (nearest_dtime < 0) {
  413. // Handle negative nearest_dtime (can be caused by the d allowance)
  414. if (!step_up) {
  415. if (nearest_collided == 0)
  416. pos_f->X += speed_f->X * nearest_dtime;
  417. if (nearest_collided == 1)
  418. pos_f->Y += speed_f->Y * nearest_dtime;
  419. if (nearest_collided == 2)
  420. pos_f->Z += speed_f->Z * nearest_dtime;
  421. }
  422. } else {
  423. *pos_f += *speed_f * nearest_dtime;
  424. dtime -= nearest_dtime;
  425. }
  426. bool is_collision = true;
  427. if (nearest_info.is_unloaded)
  428. is_collision = false;
  429. CollisionInfo info;
  430. if (nearest_info.is_object)
  431. info.type = COLLISION_OBJECT;
  432. else
  433. info.type = COLLISION_NODE;
  434. info.node_p = nearest_info.position;
  435. info.old_speed = *speed_f;
  436. // Set the speed component that caused the collision to zero
  437. if (step_up) {
  438. // Special case: Handle stairs
  439. nearest_info.is_step_up = true;
  440. is_collision = false;
  441. } else if (nearest_collided == 0) { // X
  442. if (fabs(speed_f->X) > BS * 3)
  443. speed_f->X *= bounce;
  444. else
  445. speed_f->X = 0;
  446. result.collides = true;
  447. } else if (nearest_collided == 1) { // Y
  448. if(fabs(speed_f->Y) > BS * 3)
  449. speed_f->Y *= bounce;
  450. else
  451. speed_f->Y = 0;
  452. result.collides = true;
  453. } else if (nearest_collided == 2) { // Z
  454. if (fabs(speed_f->Z) > BS * 3)
  455. speed_f->Z *= bounce;
  456. else
  457. speed_f->Z = 0;
  458. result.collides = true;
  459. }
  460. info.new_speed = *speed_f;
  461. if (info.new_speed.getDistanceFrom(info.old_speed) < 0.1f * BS)
  462. is_collision = false;
  463. if (is_collision) {
  464. result.collisions.push_back(info);
  465. }
  466. }
  467. }
  468. /*
  469. Final touches: Check if standing on ground, step up stairs.
  470. */
  471. aabb3f box = box_0;
  472. box.MinEdge += *pos_f;
  473. box.MaxEdge += *pos_f;
  474. for (const auto &box_info : cinfo) {
  475. const aabb3f &cbox = box_info.box;
  476. /*
  477. See if the object is touching ground.
  478. Object touches ground if object's minimum Y is near node's
  479. maximum Y and object's X-Z-area overlaps with the node's
  480. X-Z-area.
  481. Use 0.15*BS so that it is easier to get on a node.
  482. */
  483. if (cbox.MaxEdge.X - d > box.MinEdge.X && cbox.MinEdge.X + d < box.MaxEdge.X &&
  484. cbox.MaxEdge.Z - d > box.MinEdge.Z &&
  485. cbox.MinEdge.Z + d < box.MaxEdge.Z) {
  486. if (box_info.is_step_up) {
  487. pos_f->Y += cbox.MaxEdge.Y - box.MinEdge.Y;
  488. box = box_0;
  489. box.MinEdge += *pos_f;
  490. box.MaxEdge += *pos_f;
  491. }
  492. if (fabs(cbox.MaxEdge.Y - box.MinEdge.Y) < 0.15f * BS) {
  493. result.touching_ground = true;
  494. if (box_info.is_object)
  495. result.standing_on_object = true;
  496. }
  497. }
  498. }
  499. return result;
  500. }