3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "collision.h"
27 #include "client/clientenvironment.h"
29 #include "serverenvironment.h"
30 #include "serverobject.h"
31 #include "util/timetaker.h"
34 // float error is 10 - 9.96875 = 0.03125
35 //#define COLL_ZERO 0.032 // broken unit tests
39 struct NearbyCollisionInfo {
40 NearbyCollisionInfo(bool is_ul, bool is_obj, int bouncy,
41 const v3s16 &pos, const aabb3f &box) :
50 bool is_step_up = false;
59 // Checks for collision of a moving aabbox with a static aabbox
60 // Returns -1 if no collision, 0 if X collision, 1 if Y collision, 2 if Z collision
61 // The time after which the collision occurs is stored in dtime.
62 CollisionAxis axisAlignedCollision(
63 const aabb3f &staticbox, const aabb3f &movingbox,
64 const v3f &speed, f32 d, f32 *dtime)
66 //TimeTaker tt("axisAlignedCollision");
68 f32 xsize = (staticbox.MaxEdge.X - staticbox.MinEdge.X) - COLL_ZERO; // reduce box size for solve collision stuck (flying sand)
69 f32 ysize = (staticbox.MaxEdge.Y - staticbox.MinEdge.Y); // - COLL_ZERO; // Y - no sense for falling, but maybe try later
70 f32 zsize = (staticbox.MaxEdge.Z - staticbox.MinEdge.Z) - COLL_ZERO;
73 movingbox.MinEdge.X - staticbox.MinEdge.X,
74 movingbox.MinEdge.Y - staticbox.MinEdge.Y,
75 movingbox.MinEdge.Z - staticbox.MinEdge.Z,
76 movingbox.MaxEdge.X - staticbox.MinEdge.X,
77 movingbox.MaxEdge.Y - staticbox.MinEdge.Y,
78 movingbox.MaxEdge.Z - staticbox.MinEdge.Z
81 if(speed.X > 0) // Check for collision with X- plane
83 if (relbox.MaxEdge.X <= d) {
84 *dtime = -relbox.MaxEdge.X / speed.X;
85 if ((relbox.MinEdge.Y + speed.Y * (*dtime) < ysize) &&
86 (relbox.MaxEdge.Y + speed.Y * (*dtime) > COLL_ZERO) &&
87 (relbox.MinEdge.Z + speed.Z * (*dtime) < zsize) &&
88 (relbox.MaxEdge.Z + speed.Z * (*dtime) > COLL_ZERO))
89 return COLLISION_AXIS_X;
91 else if(relbox.MinEdge.X > xsize)
93 return COLLISION_AXIS_NONE;
96 else if(speed.X < 0) // Check for collision with X+ plane
98 if (relbox.MinEdge.X >= xsize - d) {
99 *dtime = (xsize - relbox.MinEdge.X) / speed.X;
100 if ((relbox.MinEdge.Y + speed.Y * (*dtime) < ysize) &&
101 (relbox.MaxEdge.Y + speed.Y * (*dtime) > COLL_ZERO) &&
102 (relbox.MinEdge.Z + speed.Z * (*dtime) < zsize) &&
103 (relbox.MaxEdge.Z + speed.Z * (*dtime) > COLL_ZERO))
104 return COLLISION_AXIS_X;
106 else if(relbox.MaxEdge.X < 0)
108 return COLLISION_AXIS_NONE;
114 if(speed.Y > 0) // Check for collision with Y- plane
116 if (relbox.MaxEdge.Y <= d) {
117 *dtime = -relbox.MaxEdge.Y / speed.Y;
118 if ((relbox.MinEdge.X + speed.X * (*dtime) < xsize) &&
119 (relbox.MaxEdge.X + speed.X * (*dtime) > COLL_ZERO) &&
120 (relbox.MinEdge.Z + speed.Z * (*dtime) < zsize) &&
121 (relbox.MaxEdge.Z + speed.Z * (*dtime) > COLL_ZERO))
122 return COLLISION_AXIS_Y;
124 else if(relbox.MinEdge.Y > ysize)
126 return COLLISION_AXIS_NONE;
129 else if(speed.Y < 0) // Check for collision with Y+ plane
131 if (relbox.MinEdge.Y >= ysize - d) {
132 *dtime = (ysize - relbox.MinEdge.Y) / speed.Y;
133 if ((relbox.MinEdge.X + speed.X * (*dtime) < xsize) &&
134 (relbox.MaxEdge.X + speed.X * (*dtime) > COLL_ZERO) &&
135 (relbox.MinEdge.Z + speed.Z * (*dtime) < zsize) &&
136 (relbox.MaxEdge.Z + speed.Z * (*dtime) > COLL_ZERO))
137 return COLLISION_AXIS_Y;
139 else if(relbox.MaxEdge.Y < 0)
141 return COLLISION_AXIS_NONE;
147 if(speed.Z > 0) // Check for collision with Z- plane
149 if (relbox.MaxEdge.Z <= d) {
150 *dtime = -relbox.MaxEdge.Z / speed.Z;
151 if ((relbox.MinEdge.X + speed.X * (*dtime) < xsize) &&
152 (relbox.MaxEdge.X + speed.X * (*dtime) > COLL_ZERO) &&
153 (relbox.MinEdge.Y + speed.Y * (*dtime) < ysize) &&
154 (relbox.MaxEdge.Y + speed.Y * (*dtime) > COLL_ZERO))
155 return COLLISION_AXIS_Z;
157 //else if(relbox.MinEdge.Z > zsize)
159 // return COLLISION_AXIS_NONE;
162 else if(speed.Z < 0) // Check for collision with Z+ plane
164 if (relbox.MinEdge.Z >= zsize - d) {
165 *dtime = (zsize - relbox.MinEdge.Z) / speed.Z;
166 if ((relbox.MinEdge.X + speed.X * (*dtime) < xsize) &&
167 (relbox.MaxEdge.X + speed.X * (*dtime) > COLL_ZERO) &&
168 (relbox.MinEdge.Y + speed.Y * (*dtime) < ysize) &&
169 (relbox.MaxEdge.Y + speed.Y * (*dtime) > COLL_ZERO))
170 return COLLISION_AXIS_Z;
172 //else if(relbox.MaxEdge.Z < 0)
174 // return COLLISION_AXIS_NONE;
178 return COLLISION_AXIS_NONE;
182 // Checks if moving the movingbox up by the given distance would hit a ceiling.
183 bool wouldCollideWithCeiling(
184 const std::vector<NearbyCollisionInfo> &cinfo,
185 const aabb3f &movingbox,
186 f32 y_increase, f32 d)
188 //TimeTaker tt("wouldCollideWithCeiling");
190 assert(y_increase >= 0); // pre-condition
192 for (const auto &it : cinfo) {
193 const aabb3f &staticbox = it.box;
194 if ((movingbox.MaxEdge.Y - d <= staticbox.MinEdge.Y) &&
195 (movingbox.MaxEdge.Y + y_increase > staticbox.MinEdge.Y) &&
196 (movingbox.MinEdge.X < staticbox.MaxEdge.X) &&
197 (movingbox.MaxEdge.X > staticbox.MinEdge.X) &&
198 (movingbox.MinEdge.Z < staticbox.MaxEdge.Z) &&
199 (movingbox.MaxEdge.Z > staticbox.MinEdge.Z))
206 static inline void getNeighborConnectingFace(const v3s16 &p,
207 const NodeDefManager *nodedef, Map *map, MapNode n, int v, int *neighbors)
209 MapNode n2 = map->getNode(p);
210 if (nodedef->nodeboxConnects(n, n2, v))
214 collisionMoveResult collisionMoveSimple(Environment *env, IGameDef *gamedef,
215 f32 pos_max_d, const aabb3f &box_0,
216 f32 stepheight, f32 dtime,
217 v3f *pos_f, v3f *speed_f,
218 v3f accel_f, ActiveObject *self,
219 bool collideWithObjects)
221 static bool time_notification_done = false;
222 Map *map = &env->getMap();
224 ScopeProfiler sp(g_profiler, "collisionMoveSimple()", SPT_AVG);
226 collisionMoveResult result;
229 Calculate new velocity
232 if (!time_notification_done) {
233 time_notification_done = true;
234 infostream << "collisionMoveSimple: maximum step interval exceeded,"
235 " lost movement details!"<<std::endl;
239 time_notification_done = false;
241 *speed_f += accel_f * dtime;
243 // If there is no speed, there are no collisions
244 if (speed_f->getLength() == 0)
247 // Limit speed for avoiding hangs
248 speed_f->Y = rangelim(speed_f->Y, -5000, 5000);
249 speed_f->X = rangelim(speed_f->X, -5000, 5000);
250 speed_f->Z = rangelim(speed_f->Z, -5000, 5000);
253 Collect node boxes in movement range
255 std::vector<NearbyCollisionInfo> cinfo;
257 //TimeTaker tt2("collisionMoveSimple collect boxes");
258 ScopeProfiler sp2(g_profiler, "collisionMoveSimple(): collect boxes", SPT_AVG);
260 v3f newpos_f = *pos_f + *speed_f * dtime;
262 MYMIN(pos_f->X, newpos_f.X),
263 MYMIN(pos_f->Y, newpos_f.Y) + 0.01f * BS, // bias rounding, player often at +/-n.5
264 MYMIN(pos_f->Z, newpos_f.Z)
267 MYMAX(pos_f->X, newpos_f.X),
268 MYMAX(pos_f->Y, newpos_f.Y),
269 MYMAX(pos_f->Z, newpos_f.Z)
271 v3s16 min = floatToInt(minpos_f + box_0.MinEdge, BS) - v3s16(1, 1, 1);
272 v3s16 max = floatToInt(maxpos_f + box_0.MaxEdge, BS) + v3s16(1, 1, 1);
274 bool any_position_valid = false;
277 for (p.X = min.X; p.X <= max.X; p.X++)
278 for (p.Y = min.Y; p.Y <= max.Y; p.Y++)
279 for (p.Z = min.Z; p.Z <= max.Z; p.Z++) {
280 bool is_position_valid;
281 MapNode n = map->getNode(p, &is_position_valid);
283 if (is_position_valid && n.getContent() != CONTENT_IGNORE) {
284 // Object collides into walkable nodes
286 any_position_valid = true;
287 const NodeDefManager *nodedef = gamedef->getNodeDefManager();
288 const ContentFeatures &f = nodedef->get(n);
293 int n_bouncy_value = itemgroup_get(f.groups, "bouncy");
296 if (f.drawtype == NDT_NODEBOX &&
297 f.node_box.type == NODEBOX_CONNECTED) {
301 getNeighborConnectingFace(p2, nodedef, map, n, 1, &neighbors);
305 getNeighborConnectingFace(p2, nodedef, map, n, 2, &neighbors);
309 getNeighborConnectingFace(p2, nodedef, map, n, 4, &neighbors);
313 getNeighborConnectingFace(p2, nodedef, map, n, 8, &neighbors);
317 getNeighborConnectingFace(p2, nodedef, map, n, 16, &neighbors);
321 getNeighborConnectingFace(p2, nodedef, map, n, 32, &neighbors);
323 std::vector<aabb3f> nodeboxes;
324 n.getCollisionBoxes(gamedef->ndef(), &nodeboxes, neighbors);
326 // Calculate float position only once
327 v3f posf = intToFloat(p, BS);
328 for (auto box : nodeboxes) {
331 cinfo.emplace_back(false, false, n_bouncy_value, p, box);
334 // Collide with unloaded nodes (position invalid) and loaded
335 // CONTENT_IGNORE nodes (position valid)
336 aabb3f box = getNodeBox(p, BS);
337 cinfo.emplace_back(true, false, 0, p, box);
341 // Do not move if world has not loaded yet, since custom node boxes
342 // are not available for collision detection.
343 // This also intentionally occurs in the case of the object being positioned
344 // solely on loaded CONTENT_IGNORE nodes, no matter where they come from.
345 if (!any_position_valid) {
346 *speed_f = v3f(0, 0, 0);
352 if(collideWithObjects)
354 /* add object boxes to cinfo */
356 std::vector<ActiveObject*> objects;
358 ClientEnvironment *c_env = dynamic_cast<ClientEnvironment*>(env);
360 // Calculate distance by speed, add own extent and 1.5m of tolerance
361 f32 distance = speed_f->getLength() * dtime +
362 box_0.getExtent().getLength() + 1.5f * BS;
363 std::vector<DistanceSortedActiveObject> clientobjects;
364 c_env->getActiveObjects(*pos_f, distance, clientobjects);
366 for (auto &clientobject : clientobjects) {
367 // Do collide with everything but itself and the parent CAO
368 if (!self || (self != clientobject.obj &&
369 self != clientobject.obj->getParent())) {
370 objects.push_back((ActiveObject*) clientobject.obj);
377 ServerEnvironment *s_env = dynamic_cast<ServerEnvironment*>(env);
379 // Calculate distance by speed, add own extent and 1.5m of tolerance
380 f32 distance = speed_f->getLength() * dtime +
381 box_0.getExtent().getLength() + 1.5f * BS;
382 std::vector<u16> s_objects;
383 s_env->getObjectsInsideRadius(s_objects, *pos_f, distance);
385 for (u16 obj_id : s_objects) {
386 ServerActiveObject *current = s_env->getActiveObject(obj_id);
388 if (!self || (self != current &&
389 self != current->getParent())) {
390 objects.push_back((ActiveObject*)current);
396 for (std::vector<ActiveObject*>::const_iterator iter = objects.begin();
397 iter != objects.end(); ++iter) {
398 ActiveObject *object = *iter;
401 aabb3f object_collisionbox;
402 if (object->getCollisionBox(&object_collisionbox) &&
403 object->collideWithObjects()) {
404 cinfo.emplace_back(false, true, 0, v3s16(), object_collisionbox);
415 Collision uncertainty radius
416 Make it a bit larger than the maximum distance of movement
418 f32 d = pos_max_d * 1.1f;
419 // A fairly large value in here makes moving smoother
422 // This should always apply, otherwise there are glitches
423 assert(d > pos_max_d); // invariant
427 while(dtime > BS * 1e-10f) {
428 // Avoid infinite loop
430 if (loopcount >= 100) {
431 warningstream << "collisionMoveSimple: Loop count exceeded, aborting to avoid infiniite loop" << std::endl;
435 aabb3f movingbox = box_0;
436 movingbox.MinEdge += *pos_f;
437 movingbox.MaxEdge += *pos_f;
439 CollisionAxis nearest_collided = COLLISION_AXIS_NONE;
440 f32 nearest_dtime = dtime;
441 int nearest_boxindex = -1;
444 Go through every nodebox, find nearest collision
446 for (u32 boxindex = 0; boxindex < cinfo.size(); boxindex++) {
447 const NearbyCollisionInfo &box_info = cinfo[boxindex];
448 // Ignore if already stepped up this nodebox.
449 if (box_info.is_step_up)
452 // Find nearest collision of the two boxes (raytracing-like)
454 CollisionAxis collided = axisAlignedCollision(box_info.box,
455 movingbox, *speed_f, d, &dtime_tmp);
457 if (collided == -1 || dtime_tmp >= nearest_dtime)
460 nearest_dtime = dtime_tmp;
461 nearest_collided = collided;
462 nearest_boxindex = boxindex;
465 if (nearest_collided == COLLISION_AXIS_NONE) {
466 // No collision with any collision box.
467 *pos_f += *speed_f * dtime;
468 dtime = 0; // Set to 0 to avoid "infinite" loop due to small FP numbers
470 // Otherwise, a collision occurred.
471 NearbyCollisionInfo &nearest_info = cinfo[nearest_boxindex];
472 const aabb3f& cbox = nearest_info.box;
474 bool step_up = (nearest_collided != COLLISION_AXIS_Y) && // must not be Y direction
475 (movingbox.MinEdge.Y < cbox.MaxEdge.Y) &&
476 (movingbox.MinEdge.Y + stepheight > cbox.MaxEdge.Y) &&
477 (!wouldCollideWithCeiling(cinfo, movingbox,
478 cbox.MaxEdge.Y - movingbox.MinEdge.Y,
481 // Get bounce multiplier
482 float bounce = -(float)nearest_info.bouncy / 100.0f;
484 // Move to the point of collision and reduce dtime by nearest_dtime
485 if (nearest_dtime < 0) {
486 // Handle negative nearest_dtime (can be caused by the d allowance)
488 if (nearest_collided == COLLISION_AXIS_X)
489 pos_f->X += speed_f->X * nearest_dtime;
490 if (nearest_collided == COLLISION_AXIS_Y)
491 pos_f->Y += speed_f->Y * nearest_dtime;
492 if (nearest_collided == COLLISION_AXIS_Z)
493 pos_f->Z += speed_f->Z * nearest_dtime;
496 *pos_f += *speed_f * nearest_dtime;
497 dtime -= nearest_dtime;
500 bool is_collision = true;
501 if (nearest_info.is_unloaded)
502 is_collision = false;
505 if (nearest_info.is_object)
506 info.type = COLLISION_OBJECT;
508 info.type = COLLISION_NODE;
510 info.node_p = nearest_info.position;
511 info.old_speed = *speed_f;
512 info.plane = nearest_collided;
514 // Set the speed component that caused the collision to zero
516 // Special case: Handle stairs
517 nearest_info.is_step_up = true;
518 is_collision = false;
519 } else if (nearest_collided == COLLISION_AXIS_X) {
520 if (fabs(speed_f->X) > BS * 3)
521 speed_f->X *= bounce;
524 result.collides = true;
525 } else if (nearest_collided == COLLISION_AXIS_Y) {
526 if(fabs(speed_f->Y) > BS * 3)
527 speed_f->Y *= bounce;
530 result.collides = true;
531 } else if (nearest_collided == COLLISION_AXIS_Z) {
532 if (fabs(speed_f->Z) > BS * 3)
533 speed_f->Z *= bounce;
536 result.collides = true;
539 info.new_speed = *speed_f;
540 if (info.new_speed.getDistanceFrom(info.old_speed) < 0.1f * BS)
541 is_collision = false;
544 info.axis = nearest_collided;
545 result.collisions.push_back(info);
551 Final touches: Check if standing on ground, step up stairs.
554 box.MinEdge += *pos_f;
555 box.MaxEdge += *pos_f;
556 for (const auto &box_info : cinfo) {
557 const aabb3f &cbox = box_info.box;
560 See if the object is touching ground.
562 Object touches ground if object's minimum Y is near node's
563 maximum Y and object's X-Z-area overlaps with the node's
566 Use 0.15*BS so that it is easier to get on a node.
568 if (cbox.MaxEdge.X - d > box.MinEdge.X && cbox.MinEdge.X + d < box.MaxEdge.X &&
569 cbox.MaxEdge.Z - d > box.MinEdge.Z &&
570 cbox.MinEdge.Z + d < box.MaxEdge.Z) {
571 if (box_info.is_step_up) {
572 pos_f->Y += cbox.MaxEdge.Y - box.MinEdge.Y;
574 box.MinEdge += *pos_f;
575 box.MaxEdge += *pos_f;
577 if (std::fabs(cbox.MaxEdge.Y - box.MinEdge.Y) < 0.15f * BS) {
578 result.touching_ground = true;
580 if (box_info.is_object)
581 result.standing_on_object = true;