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"
28 #include "client/localplayer.h"
30 #include "serverenvironment.h"
31 #include "server/serveractiveobject.h"
32 #include "util/timetaker.h"
36 #warning "-ffast-math is known to cause bugs in collision code, do not use!"
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 *dtime)
66 //TimeTaker tt("axisAlignedCollision");
69 movingbox.MaxEdge.X - movingbox.MinEdge.X + staticbox.MaxEdge.X - staticbox.MinEdge.X, // sum of the widths
70 movingbox.MaxEdge.Y - movingbox.MinEdge.Y + staticbox.MaxEdge.Y - staticbox.MinEdge.Y,
71 movingbox.MaxEdge.Z - movingbox.MinEdge.Z + staticbox.MaxEdge.Z - staticbox.MinEdge.Z,
72 std::max(movingbox.MaxEdge.X, staticbox.MaxEdge.X) - std::min(movingbox.MinEdge.X, staticbox.MinEdge.X), //outer bounding 'box' dimensions
73 std::max(movingbox.MaxEdge.Y, staticbox.MaxEdge.Y) - std::min(movingbox.MinEdge.Y, staticbox.MinEdge.Y),
74 std::max(movingbox.MaxEdge.Z, staticbox.MaxEdge.Z) - std::min(movingbox.MinEdge.Z, staticbox.MinEdge.Z)
77 const f32 dtime_max = *dtime;
78 const f32 inner_margin = -1.5f;
83 distance = relbox.MaxEdge.X - relbox.MinEdge.X;
85 *dtime = distance >= 0 ? std::abs(distance / speed.X) : -std::abs(distance / speed.X);
86 time = std::max(*dtime, 0.0f);
88 if (distance > inner_margin) {
89 if (*dtime <= dtime_max) {
90 if ((speed.X > 0 && staticbox.MaxEdge.X > movingbox.MaxEdge.X) ||
91 (speed.X < 0 && staticbox.MinEdge.X < movingbox.MinEdge.X)) {
93 (std::max(movingbox.MaxEdge.Y + speed.Y * time, staticbox.MaxEdge.Y)
94 - std::min(movingbox.MinEdge.Y + speed.Y * time, staticbox.MinEdge.Y)
95 - relbox.MinEdge.Y < 0) &&
96 (std::max(movingbox.MaxEdge.Z + speed.Z * time, staticbox.MaxEdge.Z)
97 - std::min(movingbox.MinEdge.Z + speed.Z * time, staticbox.MinEdge.Z)
98 - relbox.MinEdge.Z < 0)
100 return COLLISION_AXIS_X;
103 return COLLISION_AXIS_NONE;
111 distance = relbox.MaxEdge.Y - relbox.MinEdge.Y;
113 *dtime = distance >= 0 ? std::abs(distance / speed.Y) : -std::abs(distance / speed.Y);
114 time = std::max(*dtime, 0.0f);
116 if (distance > inner_margin) {
117 if (*dtime <= dtime_max) {
118 if ((speed.Y > 0 && staticbox.MaxEdge.Y > movingbox.MaxEdge.Y) ||
119 (speed.Y < 0 && staticbox.MinEdge.Y < movingbox.MinEdge.Y)) {
121 (std::max(movingbox.MaxEdge.X + speed.X * time, staticbox.MaxEdge.X)
122 - std::min(movingbox.MinEdge.X + speed.X * time, staticbox.MinEdge.X)
123 - relbox.MinEdge.X < 0) &&
124 (std::max(movingbox.MaxEdge.Z + speed.Z * time, staticbox.MaxEdge.Z)
125 - std::min(movingbox.MinEdge.Z + speed.Z * time, staticbox.MinEdge.Z)
126 - relbox.MinEdge.Z < 0)
128 return COLLISION_AXIS_Y;
131 return COLLISION_AXIS_NONE;
139 distance = relbox.MaxEdge.Z - relbox.MinEdge.Z;
141 *dtime = distance >= 0 ? std::abs(distance / speed.Z) : -std::abs(distance / speed.Z);
142 time = std::max(*dtime, 0.0f);
144 if (distance > inner_margin) {
145 if (*dtime <= dtime_max) {
146 if ((speed.Z > 0 && staticbox.MaxEdge.Z > movingbox.MaxEdge.Z) ||
147 (speed.Z < 0 && staticbox.MinEdge.Z < movingbox.MinEdge.Z)) {
149 (std::max(movingbox.MaxEdge.X + speed.X * time, staticbox.MaxEdge.X)
150 - std::min(movingbox.MinEdge.X + speed.X * time, staticbox.MinEdge.X)
151 - relbox.MinEdge.X < 0) &&
152 (std::max(movingbox.MaxEdge.Y + speed.Y * time, staticbox.MaxEdge.Y)
153 - std::min(movingbox.MinEdge.Y + speed.Y * time, staticbox.MinEdge.Y)
154 - relbox.MinEdge.Y < 0)
156 return COLLISION_AXIS_Z;
162 return COLLISION_AXIS_NONE;
166 // Checks if moving the movingbox up by the given distance would hit a ceiling.
167 bool wouldCollideWithCeiling(
168 const std::vector<NearbyCollisionInfo> &cinfo,
169 const aabb3f &movingbox,
170 f32 y_increase, f32 d)
172 //TimeTaker tt("wouldCollideWithCeiling");
174 assert(y_increase >= 0); // pre-condition
176 for (const auto &it : cinfo) {
177 const aabb3f &staticbox = it.box;
178 if ((movingbox.MaxEdge.Y - d <= staticbox.MinEdge.Y) &&
179 (movingbox.MaxEdge.Y + y_increase > staticbox.MinEdge.Y) &&
180 (movingbox.MinEdge.X < staticbox.MaxEdge.X) &&
181 (movingbox.MaxEdge.X > staticbox.MinEdge.X) &&
182 (movingbox.MinEdge.Z < staticbox.MaxEdge.Z) &&
183 (movingbox.MaxEdge.Z > staticbox.MinEdge.Z))
190 static inline void getNeighborConnectingFace(const v3s16 &p,
191 const NodeDefManager *nodedef, Map *map, MapNode n, int v, int *neighbors)
193 MapNode n2 = map->getNode(p);
194 if (nodedef->nodeboxConnects(n, n2, v))
198 collisionMoveResult collisionMoveSimple(Environment *env, IGameDef *gamedef,
199 f32 pos_max_d, const aabb3f &box_0,
200 f32 stepheight, f32 dtime,
201 v3f *pos_f, v3f *speed_f,
202 v3f accel_f, ActiveObject *self,
203 bool collideWithObjects)
205 static bool time_notification_done = false;
206 Map *map = &env->getMap();
208 ScopeProfiler sp(g_profiler, "collisionMoveSimple()", SPT_AVG);
210 collisionMoveResult result;
213 Calculate new velocity
216 if (!time_notification_done) {
217 time_notification_done = true;
218 infostream << "collisionMoveSimple: maximum step interval exceeded,"
219 " lost movement details!"<<std::endl;
223 time_notification_done = false;
225 *speed_f += accel_f * dtime;
227 // If there is no speed, there are no collisions
228 if (speed_f->getLength() == 0)
231 // Limit speed for avoiding hangs
232 speed_f->Y = rangelim(speed_f->Y, -5000, 5000);
233 speed_f->X = rangelim(speed_f->X, -5000, 5000);
234 speed_f->Z = rangelim(speed_f->Z, -5000, 5000);
237 Collect node boxes in movement range
239 std::vector<NearbyCollisionInfo> cinfo;
241 //TimeTaker tt2("collisionMoveSimple collect boxes");
242 ScopeProfiler sp2(g_profiler, "collisionMoveSimple(): collect boxes", SPT_AVG);
244 v3f newpos_f = *pos_f + *speed_f * dtime;
246 MYMIN(pos_f->X, newpos_f.X),
247 MYMIN(pos_f->Y, newpos_f.Y) + 0.01f * BS, // bias rounding, player often at +/-n.5
248 MYMIN(pos_f->Z, newpos_f.Z)
251 MYMAX(pos_f->X, newpos_f.X),
252 MYMAX(pos_f->Y, newpos_f.Y),
253 MYMAX(pos_f->Z, newpos_f.Z)
255 v3s16 min = floatToInt(minpos_f + box_0.MinEdge, BS) - v3s16(1, 1, 1);
256 v3s16 max = floatToInt(maxpos_f + box_0.MaxEdge, BS) + v3s16(1, 1, 1);
258 bool any_position_valid = false;
261 for (p.X = min.X; p.X <= max.X; p.X++)
262 for (p.Y = min.Y; p.Y <= max.Y; p.Y++)
263 for (p.Z = min.Z; p.Z <= max.Z; p.Z++) {
264 bool is_position_valid;
265 MapNode n = map->getNode(p, &is_position_valid);
267 if (is_position_valid && n.getContent() != CONTENT_IGNORE) {
268 // Object collides into walkable nodes
270 any_position_valid = true;
271 const NodeDefManager *nodedef = gamedef->getNodeDefManager();
272 const ContentFeatures &f = nodedef->get(n);
277 int n_bouncy_value = itemgroup_get(f.groups, "bouncy");
280 if (f.drawtype == NDT_NODEBOX &&
281 f.node_box.type == NODEBOX_CONNECTED) {
285 getNeighborConnectingFace(p2, nodedef, map, n, 1, &neighbors);
289 getNeighborConnectingFace(p2, nodedef, map, n, 2, &neighbors);
293 getNeighborConnectingFace(p2, nodedef, map, n, 4, &neighbors);
297 getNeighborConnectingFace(p2, nodedef, map, n, 8, &neighbors);
301 getNeighborConnectingFace(p2, nodedef, map, n, 16, &neighbors);
305 getNeighborConnectingFace(p2, nodedef, map, n, 32, &neighbors);
307 std::vector<aabb3f> nodeboxes;
308 n.getCollisionBoxes(gamedef->ndef(), &nodeboxes, neighbors);
310 // Calculate float position only once
311 v3f posf = intToFloat(p, BS);
312 for (auto box : nodeboxes) {
315 cinfo.emplace_back(false, false, n_bouncy_value, p, box);
318 // Collide with unloaded nodes (position invalid) and loaded
319 // CONTENT_IGNORE nodes (position valid)
320 aabb3f box = getNodeBox(p, BS);
321 cinfo.emplace_back(true, false, 0, p, box);
325 // Do not move if world has not loaded yet, since custom node boxes
326 // are not available for collision detection.
327 // This also intentionally occurs in the case of the object being positioned
328 // solely on loaded CONTENT_IGNORE nodes, no matter where they come from.
329 if (!any_position_valid) {
330 *speed_f = v3f(0, 0, 0);
336 if(collideWithObjects)
338 /* add object boxes to cinfo */
340 std::vector<ActiveObject*> objects;
342 ClientEnvironment *c_env = dynamic_cast<ClientEnvironment*>(env);
344 // Calculate distance by speed, add own extent and 1.5m of tolerance
345 f32 distance = speed_f->getLength() * dtime +
346 box_0.getExtent().getLength() + 1.5f * BS;
347 std::vector<DistanceSortedActiveObject> clientobjects;
348 c_env->getActiveObjects(*pos_f, distance, clientobjects);
350 for (auto &clientobject : clientobjects) {
351 // Do collide with everything but itself and the parent CAO
352 if (!self || (self != clientobject.obj &&
353 self != clientobject.obj->getParent())) {
354 objects.push_back((ActiveObject*) clientobject.obj);
361 ServerEnvironment *s_env = dynamic_cast<ServerEnvironment*>(env);
363 // Calculate distance by speed, add own extent and 1.5m of tolerance
364 f32 distance = speed_f->getLength() * dtime +
365 box_0.getExtent().getLength() + 1.5f * BS;
367 // search for objects which are not us, or we are not its parent
368 // we directly use the callback to populate the result to prevent
369 // a useless result loop here
370 auto include_obj_cb = [self, &objects] (ServerActiveObject *obj) {
371 if (!self || (self != obj && self != obj->getParent())) {
372 objects.push_back((ActiveObject *)obj);
377 std::vector<ServerActiveObject *> s_objects;
378 s_env->getObjectsInsideRadius(s_objects, *pos_f, distance, include_obj_cb);
382 for (std::vector<ActiveObject*>::const_iterator iter = objects.begin();
383 iter != objects.end(); ++iter) {
384 ActiveObject *object = *iter;
387 aabb3f object_collisionbox;
388 if (object->getCollisionBox(&object_collisionbox) &&
389 object->collideWithObjects()) {
390 cinfo.emplace_back(false, true, 0, v3s16(), object_collisionbox);
396 LocalPlayer *lplayer = c_env->getLocalPlayer();
397 if (lplayer->getParent() == nullptr) {
398 aabb3f lplayer_collisionbox = lplayer->getCollisionbox();
399 v3f lplayer_pos = lplayer->getPosition();
400 lplayer_collisionbox.MinEdge += lplayer_pos;
401 lplayer_collisionbox.MaxEdge += lplayer_pos;
402 cinfo.emplace_back(false, true, 0, v3s16(), lplayer_collisionbox);
416 while(dtime > BS * 1e-10f) {
417 // Avoid infinite loop
419 if (loopcount >= 100) {
420 warningstream << "collisionMoveSimple: Loop count exceeded, aborting to avoid infiniite loop" << std::endl;
424 aabb3f movingbox = box_0;
425 movingbox.MinEdge += *pos_f;
426 movingbox.MaxEdge += *pos_f;
428 CollisionAxis nearest_collided = COLLISION_AXIS_NONE;
429 f32 nearest_dtime = dtime;
430 int nearest_boxindex = -1;
433 Go through every nodebox, find nearest collision
435 for (u32 boxindex = 0; boxindex < cinfo.size(); boxindex++) {
436 const NearbyCollisionInfo &box_info = cinfo[boxindex];
437 // Ignore if already stepped up this nodebox.
438 if (box_info.is_step_up)
441 // Find nearest collision of the two boxes (raytracing-like)
442 f32 dtime_tmp = nearest_dtime;
443 CollisionAxis collided = axisAlignedCollision(box_info.box,
444 movingbox, *speed_f, &dtime_tmp);
446 if (collided == -1 || dtime_tmp >= nearest_dtime)
449 nearest_dtime = dtime_tmp;
450 nearest_collided = collided;
451 nearest_boxindex = boxindex;
454 if (nearest_collided == COLLISION_AXIS_NONE) {
455 // No collision with any collision box.
456 *pos_f += *speed_f * dtime;
457 dtime = 0; // Set to 0 to avoid "infinite" loop due to small FP numbers
459 // Otherwise, a collision occurred.
460 NearbyCollisionInfo &nearest_info = cinfo[nearest_boxindex];
461 const aabb3f& cbox = nearest_info.box;
463 //movingbox except moved to the horizontal position it would be after step up
464 aabb3f stepbox = movingbox;
465 stepbox.MinEdge.X += speed_f->X * dtime;
466 stepbox.MinEdge.Z += speed_f->Z * dtime;
467 stepbox.MaxEdge.X += speed_f->X * dtime;
468 stepbox.MaxEdge.Z += speed_f->Z * dtime;
470 bool step_up = (nearest_collided != COLLISION_AXIS_Y) && // must not be Y direction
471 (movingbox.MinEdge.Y < cbox.MaxEdge.Y) &&
472 (movingbox.MinEdge.Y + stepheight > cbox.MaxEdge.Y) &&
473 (!wouldCollideWithCeiling(cinfo, stepbox,
474 cbox.MaxEdge.Y - movingbox.MinEdge.Y,
477 // Get bounce multiplier
478 float bounce = -(float)nearest_info.bouncy / 100.0f;
480 // Move to the point of collision and reduce dtime by nearest_dtime
481 if (nearest_dtime < 0) {
482 // Handle negative nearest_dtime
484 if (nearest_collided == COLLISION_AXIS_X)
485 pos_f->X += speed_f->X * nearest_dtime;
486 if (nearest_collided == COLLISION_AXIS_Y)
487 pos_f->Y += speed_f->Y * nearest_dtime;
488 if (nearest_collided == COLLISION_AXIS_Z)
489 pos_f->Z += speed_f->Z * nearest_dtime;
492 *pos_f += *speed_f * nearest_dtime;
493 dtime -= nearest_dtime;
496 bool is_collision = true;
497 if (nearest_info.is_unloaded)
498 is_collision = false;
501 if (nearest_info.is_object)
502 info.type = COLLISION_OBJECT;
504 info.type = COLLISION_NODE;
506 info.node_p = nearest_info.position;
507 info.old_speed = *speed_f;
508 info.plane = nearest_collided;
510 // Set the speed component that caused the collision to zero
512 // Special case: Handle stairs
513 nearest_info.is_step_up = true;
514 is_collision = false;
515 } else if (nearest_collided == COLLISION_AXIS_X) {
516 if (fabs(speed_f->X) > BS * 3)
517 speed_f->X *= bounce;
520 result.collides = true;
521 } else if (nearest_collided == COLLISION_AXIS_Y) {
522 if(fabs(speed_f->Y) > BS * 3)
523 speed_f->Y *= bounce;
526 result.collides = true;
527 } else if (nearest_collided == COLLISION_AXIS_Z) {
528 if (fabs(speed_f->Z) > BS * 3)
529 speed_f->Z *= bounce;
532 result.collides = true;
535 info.new_speed = *speed_f;
536 if (info.new_speed.getDistanceFrom(info.old_speed) < 0.1f * BS)
537 is_collision = false;
540 info.axis = nearest_collided;
541 result.collisions.push_back(info);
547 Final touches: Check if standing on ground, step up stairs.
550 box.MinEdge += *pos_f;
551 box.MaxEdge += *pos_f;
552 for (const auto &box_info : cinfo) {
553 const aabb3f &cbox = box_info.box;
556 See if the object is touching ground.
558 Object touches ground if object's minimum Y is near node's
559 maximum Y and object's X-Z-area overlaps with the node's
563 if (cbox.MaxEdge.X - d > box.MinEdge.X && cbox.MinEdge.X + d < box.MaxEdge.X &&
564 cbox.MaxEdge.Z - d > box.MinEdge.Z &&
565 cbox.MinEdge.Z + d < box.MaxEdge.Z) {
566 if (box_info.is_step_up) {
567 pos_f->Y += cbox.MaxEdge.Y - box.MinEdge.Y;
569 box.MinEdge += *pos_f;
570 box.MaxEdge += *pos_f;
572 if (std::fabs(cbox.MaxEdge.Y - box.MinEdge.Y) < 0.05f) {
573 result.touching_ground = true;
575 if (box_info.is_object)
576 result.standing_on_object = true;