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 struct NearbyCollisionInfo {
37 NearbyCollisionInfo(bool is_ul, bool is_obj, int bouncy,
38 const v3s16 &pos, const aabb3f &box) :
47 bool is_step_up = false;
56 // Checks for collision of a moving aabbox with a static aabbox
57 // Returns -1 if no collision, 0 if X collision, 1 if Y collision, 2 if Z collision
58 // The time after which the collision occurs is stored in dtime.
59 CollisionAxis axisAlignedCollision(
60 const aabb3f &staticbox, const aabb3f &movingbox,
61 const v3f &speed, f32 *dtime)
63 //TimeTaker tt("axisAlignedCollision");
66 movingbox.MaxEdge.X - movingbox.MinEdge.X + staticbox.MaxEdge.X - staticbox.MinEdge.X, // sum of the widths
67 movingbox.MaxEdge.Y - movingbox.MinEdge.Y + staticbox.MaxEdge.Y - staticbox.MinEdge.Y,
68 movingbox.MaxEdge.Z - movingbox.MinEdge.Z + staticbox.MaxEdge.Z - staticbox.MinEdge.Z,
69 std::max(movingbox.MaxEdge.X, staticbox.MaxEdge.X) - std::min(movingbox.MinEdge.X, staticbox.MinEdge.X), //outer bounding 'box' dimensions
70 std::max(movingbox.MaxEdge.Y, staticbox.MaxEdge.Y) - std::min(movingbox.MinEdge.Y, staticbox.MinEdge.Y),
71 std::max(movingbox.MaxEdge.Z, staticbox.MaxEdge.Z) - std::min(movingbox.MinEdge.Z, staticbox.MinEdge.Z)
74 const f32 dtime_max = *dtime;
75 const f32 inner_margin = -1.5f;
80 distance = relbox.MaxEdge.X - relbox.MinEdge.X;
82 *dtime = distance >= 0 ? std::abs(distance / speed.X) : -std::abs(distance / speed.X);
83 time = std::max(*dtime, 0.0f);
85 if (distance > inner_margin) {
86 if (*dtime <= dtime_max) {
87 if ((speed.X > 0 && staticbox.MaxEdge.X > movingbox.MaxEdge.X) ||
88 (speed.X < 0 && staticbox.MinEdge.X < movingbox.MinEdge.X)) {
90 (std::max(movingbox.MaxEdge.Y + speed.Y * time, staticbox.MaxEdge.Y)
91 - std::min(movingbox.MinEdge.Y + speed.Y * time, staticbox.MinEdge.Y)
92 - relbox.MinEdge.Y < 0) &&
93 (std::max(movingbox.MaxEdge.Z + speed.Z * time, staticbox.MaxEdge.Z)
94 - std::min(movingbox.MinEdge.Z + speed.Z * time, staticbox.MinEdge.Z)
95 - relbox.MinEdge.Z < 0)
97 return COLLISION_AXIS_X;
100 return COLLISION_AXIS_NONE;
108 distance = relbox.MaxEdge.Y - relbox.MinEdge.Y;
110 *dtime = distance >= 0 ? std::abs(distance / speed.Y) : -std::abs(distance / speed.Y);
111 time = std::max(*dtime, 0.0f);
113 if (distance > inner_margin) {
114 if (*dtime <= dtime_max) {
115 if ((speed.Y > 0 && staticbox.MaxEdge.Y > movingbox.MaxEdge.Y) ||
116 (speed.Y < 0 && staticbox.MinEdge.Y < movingbox.MinEdge.Y)) {
118 (std::max(movingbox.MaxEdge.X + speed.X * time, staticbox.MaxEdge.X)
119 - std::min(movingbox.MinEdge.X + speed.X * time, staticbox.MinEdge.X)
120 - relbox.MinEdge.X < 0) &&
121 (std::max(movingbox.MaxEdge.Z + speed.Z * time, staticbox.MaxEdge.Z)
122 - std::min(movingbox.MinEdge.Z + speed.Z * time, staticbox.MinEdge.Z)
123 - relbox.MinEdge.Z < 0)
125 return COLLISION_AXIS_Y;
128 return COLLISION_AXIS_NONE;
136 distance = relbox.MaxEdge.Z - relbox.MinEdge.Z;
138 *dtime = distance >= 0 ? std::abs(distance / speed.Z) : -std::abs(distance / speed.Z);
139 time = std::max(*dtime, 0.0f);
141 if (distance > inner_margin) {
142 if (*dtime <= dtime_max) {
143 if ((speed.Z > 0 && staticbox.MaxEdge.Z > movingbox.MaxEdge.Z) ||
144 (speed.Z < 0 && staticbox.MinEdge.Z < movingbox.MinEdge.Z)) {
146 (std::max(movingbox.MaxEdge.X + speed.X * time, staticbox.MaxEdge.X)
147 - std::min(movingbox.MinEdge.X + speed.X * time, staticbox.MinEdge.X)
148 - relbox.MinEdge.X < 0) &&
149 (std::max(movingbox.MaxEdge.Y + speed.Y * time, staticbox.MaxEdge.Y)
150 - std::min(movingbox.MinEdge.Y + speed.Y * time, staticbox.MinEdge.Y)
151 - relbox.MinEdge.Y < 0)
153 return COLLISION_AXIS_Z;
159 return COLLISION_AXIS_NONE;
163 // Checks if moving the movingbox up by the given distance would hit a ceiling.
164 bool wouldCollideWithCeiling(
165 const std::vector<NearbyCollisionInfo> &cinfo,
166 const aabb3f &movingbox,
167 f32 y_increase, f32 d)
169 //TimeTaker tt("wouldCollideWithCeiling");
171 assert(y_increase >= 0); // pre-condition
173 for (const auto &it : cinfo) {
174 const aabb3f &staticbox = it.box;
175 if ((movingbox.MaxEdge.Y - d <= staticbox.MinEdge.Y) &&
176 (movingbox.MaxEdge.Y + y_increase > staticbox.MinEdge.Y) &&
177 (movingbox.MinEdge.X < staticbox.MaxEdge.X) &&
178 (movingbox.MaxEdge.X > staticbox.MinEdge.X) &&
179 (movingbox.MinEdge.Z < staticbox.MaxEdge.Z) &&
180 (movingbox.MaxEdge.Z > staticbox.MinEdge.Z))
187 static inline void getNeighborConnectingFace(const v3s16 &p,
188 const NodeDefManager *nodedef, Map *map, MapNode n, int v, int *neighbors)
190 MapNode n2 = map->getNode(p);
191 if (nodedef->nodeboxConnects(n, n2, v))
195 collisionMoveResult collisionMoveSimple(Environment *env, IGameDef *gamedef,
196 f32 pos_max_d, const aabb3f &box_0,
197 f32 stepheight, f32 dtime,
198 v3f *pos_f, v3f *speed_f,
199 v3f accel_f, ActiveObject *self,
200 bool collideWithObjects)
202 static bool time_notification_done = false;
203 Map *map = &env->getMap();
205 ScopeProfiler sp(g_profiler, "collisionMoveSimple()", SPT_AVG);
207 collisionMoveResult result;
210 Calculate new velocity
213 if (!time_notification_done) {
214 time_notification_done = true;
215 infostream << "collisionMoveSimple: maximum step interval exceeded,"
216 " lost movement details!"<<std::endl;
220 time_notification_done = false;
222 *speed_f += accel_f * dtime;
224 // If there is no speed, there are no collisions
225 if (speed_f->getLength() == 0)
228 // Limit speed for avoiding hangs
229 speed_f->Y = rangelim(speed_f->Y, -5000, 5000);
230 speed_f->X = rangelim(speed_f->X, -5000, 5000);
231 speed_f->Z = rangelim(speed_f->Z, -5000, 5000);
234 Collect node boxes in movement range
236 std::vector<NearbyCollisionInfo> cinfo;
238 //TimeTaker tt2("collisionMoveSimple collect boxes");
239 ScopeProfiler sp2(g_profiler, "collisionMoveSimple(): collect boxes", SPT_AVG);
241 v3f newpos_f = *pos_f + *speed_f * dtime;
243 MYMIN(pos_f->X, newpos_f.X),
244 MYMIN(pos_f->Y, newpos_f.Y) + 0.01f * BS, // bias rounding, player often at +/-n.5
245 MYMIN(pos_f->Z, newpos_f.Z)
248 MYMAX(pos_f->X, newpos_f.X),
249 MYMAX(pos_f->Y, newpos_f.Y),
250 MYMAX(pos_f->Z, newpos_f.Z)
252 v3s16 min = floatToInt(minpos_f + box_0.MinEdge, BS) - v3s16(1, 1, 1);
253 v3s16 max = floatToInt(maxpos_f + box_0.MaxEdge, BS) + v3s16(1, 1, 1);
255 bool any_position_valid = false;
258 for (p.X = min.X; p.X <= max.X; p.X++)
259 for (p.Y = min.Y; p.Y <= max.Y; p.Y++)
260 for (p.Z = min.Z; p.Z <= max.Z; p.Z++) {
261 bool is_position_valid;
262 MapNode n = map->getNode(p, &is_position_valid);
264 if (is_position_valid && n.getContent() != CONTENT_IGNORE) {
265 // Object collides into walkable nodes
267 any_position_valid = true;
268 const NodeDefManager *nodedef = gamedef->getNodeDefManager();
269 const ContentFeatures &f = nodedef->get(n);
274 int n_bouncy_value = itemgroup_get(f.groups, "bouncy");
277 if (f.drawtype == NDT_NODEBOX &&
278 f.node_box.type == NODEBOX_CONNECTED) {
282 getNeighborConnectingFace(p2, nodedef, map, n, 1, &neighbors);
286 getNeighborConnectingFace(p2, nodedef, map, n, 2, &neighbors);
290 getNeighborConnectingFace(p2, nodedef, map, n, 4, &neighbors);
294 getNeighborConnectingFace(p2, nodedef, map, n, 8, &neighbors);
298 getNeighborConnectingFace(p2, nodedef, map, n, 16, &neighbors);
302 getNeighborConnectingFace(p2, nodedef, map, n, 32, &neighbors);
304 std::vector<aabb3f> nodeboxes;
305 n.getCollisionBoxes(gamedef->ndef(), &nodeboxes, neighbors);
307 // Calculate float position only once
308 v3f posf = intToFloat(p, BS);
309 for (auto box : nodeboxes) {
312 cinfo.emplace_back(false, false, n_bouncy_value, p, box);
315 // Collide with unloaded nodes (position invalid) and loaded
316 // CONTENT_IGNORE nodes (position valid)
317 aabb3f box = getNodeBox(p, BS);
318 cinfo.emplace_back(true, false, 0, p, box);
322 // Do not move if world has not loaded yet, since custom node boxes
323 // are not available for collision detection.
324 // This also intentionally occurs in the case of the object being positioned
325 // solely on loaded CONTENT_IGNORE nodes, no matter where they come from.
326 if (!any_position_valid) {
327 *speed_f = v3f(0, 0, 0);
333 if(collideWithObjects)
335 /* add object boxes to cinfo */
337 std::vector<ActiveObject*> objects;
339 ClientEnvironment *c_env = dynamic_cast<ClientEnvironment*>(env);
341 // Calculate distance by speed, add own extent and 1.5m of tolerance
342 f32 distance = speed_f->getLength() * dtime +
343 box_0.getExtent().getLength() + 1.5f * BS;
344 std::vector<DistanceSortedActiveObject> clientobjects;
345 c_env->getActiveObjects(*pos_f, distance, clientobjects);
347 for (auto &clientobject : clientobjects) {
348 // Do collide with everything but itself and the parent CAO
349 if (!self || (self != clientobject.obj &&
350 self != clientobject.obj->getParent())) {
351 objects.push_back((ActiveObject*) clientobject.obj);
358 ServerEnvironment *s_env = dynamic_cast<ServerEnvironment*>(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<u16> s_objects;
364 s_env->getObjectsInsideRadius(s_objects, *pos_f, distance);
366 for (u16 obj_id : s_objects) {
367 ServerActiveObject *current = s_env->getActiveObject(obj_id);
369 if (!self || (self != current &&
370 self != current->getParent())) {
371 objects.push_back((ActiveObject*)current);
377 for (std::vector<ActiveObject*>::const_iterator iter = objects.begin();
378 iter != objects.end(); ++iter) {
379 ActiveObject *object = *iter;
382 aabb3f object_collisionbox;
383 if (object->getCollisionBox(&object_collisionbox) &&
384 object->collideWithObjects()) {
385 cinfo.emplace_back(false, true, 0, v3s16(), object_collisionbox);
391 LocalPlayer *lplayer = c_env->getLocalPlayer();
392 if (lplayer->getParent() == nullptr) {
393 aabb3f lplayer_collisionbox = lplayer->getCollisionbox();
394 v3f lplayer_pos = lplayer->getPosition();
395 lplayer_collisionbox.MinEdge += lplayer_pos;
396 lplayer_collisionbox.MaxEdge += lplayer_pos;
397 cinfo.emplace_back(false, true, 0, v3s16(), lplayer_collisionbox);
411 while(dtime > BS * 1e-10f) {
412 // Avoid infinite loop
414 if (loopcount >= 100) {
415 warningstream << "collisionMoveSimple: Loop count exceeded, aborting to avoid infiniite loop" << std::endl;
419 aabb3f movingbox = box_0;
420 movingbox.MinEdge += *pos_f;
421 movingbox.MaxEdge += *pos_f;
423 CollisionAxis nearest_collided = COLLISION_AXIS_NONE;
424 f32 nearest_dtime = dtime;
425 int nearest_boxindex = -1;
428 Go through every nodebox, find nearest collision
430 for (u32 boxindex = 0; boxindex < cinfo.size(); boxindex++) {
431 const NearbyCollisionInfo &box_info = cinfo[boxindex];
432 // Ignore if already stepped up this nodebox.
433 if (box_info.is_step_up)
436 // Find nearest collision of the two boxes (raytracing-like)
437 f32 dtime_tmp = nearest_dtime;
438 CollisionAxis collided = axisAlignedCollision(box_info.box,
439 movingbox, *speed_f, &dtime_tmp);
441 if (collided == -1 || dtime_tmp >= nearest_dtime)
444 nearest_dtime = dtime_tmp;
445 nearest_collided = collided;
446 nearest_boxindex = boxindex;
449 if (nearest_collided == COLLISION_AXIS_NONE) {
450 // No collision with any collision box.
451 *pos_f += *speed_f * dtime;
452 dtime = 0; // Set to 0 to avoid "infinite" loop due to small FP numbers
454 // Otherwise, a collision occurred.
455 NearbyCollisionInfo &nearest_info = cinfo[nearest_boxindex];
456 const aabb3f& cbox = nearest_info.box;
458 //movingbox except moved to the horizontal position it would be after step up
459 aabb3f stepbox = movingbox;
460 stepbox.MinEdge.X += speed_f->X * dtime;
461 stepbox.MinEdge.Z += speed_f->Z * dtime;
462 stepbox.MaxEdge.X += speed_f->X * dtime;
463 stepbox.MaxEdge.Z += speed_f->Z * dtime;
465 bool step_up = (nearest_collided != COLLISION_AXIS_Y) && // must not be Y direction
466 (movingbox.MinEdge.Y < cbox.MaxEdge.Y) &&
467 (movingbox.MinEdge.Y + stepheight > cbox.MaxEdge.Y) &&
468 (!wouldCollideWithCeiling(cinfo, stepbox,
469 cbox.MaxEdge.Y - movingbox.MinEdge.Y,
472 // Get bounce multiplier
473 float bounce = -(float)nearest_info.bouncy / 100.0f;
475 // Move to the point of collision and reduce dtime by nearest_dtime
476 if (nearest_dtime < 0) {
477 // Handle negative nearest_dtime
479 if (nearest_collided == COLLISION_AXIS_X)
480 pos_f->X += speed_f->X * nearest_dtime;
481 if (nearest_collided == COLLISION_AXIS_Y)
482 pos_f->Y += speed_f->Y * nearest_dtime;
483 if (nearest_collided == COLLISION_AXIS_Z)
484 pos_f->Z += speed_f->Z * nearest_dtime;
487 *pos_f += *speed_f * nearest_dtime;
488 dtime -= nearest_dtime;
491 bool is_collision = true;
492 if (nearest_info.is_unloaded)
493 is_collision = false;
496 if (nearest_info.is_object)
497 info.type = COLLISION_OBJECT;
499 info.type = COLLISION_NODE;
501 info.node_p = nearest_info.position;
502 info.old_speed = *speed_f;
503 info.plane = nearest_collided;
505 // Set the speed component that caused the collision to zero
507 // Special case: Handle stairs
508 nearest_info.is_step_up = true;
509 is_collision = false;
510 } else if (nearest_collided == COLLISION_AXIS_X) {
511 if (fabs(speed_f->X) > BS * 3)
512 speed_f->X *= bounce;
515 result.collides = true;
516 } else if (nearest_collided == COLLISION_AXIS_Y) {
517 if(fabs(speed_f->Y) > BS * 3)
518 speed_f->Y *= bounce;
521 result.collides = true;
522 } else if (nearest_collided == COLLISION_AXIS_Z) {
523 if (fabs(speed_f->Z) > BS * 3)
524 speed_f->Z *= bounce;
527 result.collides = true;
530 info.new_speed = *speed_f;
531 if (info.new_speed.getDistanceFrom(info.old_speed) < 0.1f * BS)
532 is_collision = false;
535 info.axis = nearest_collided;
536 result.collisions.push_back(info);
542 Final touches: Check if standing on ground, step up stairs.
545 box.MinEdge += *pos_f;
546 box.MaxEdge += *pos_f;
547 for (const auto &box_info : cinfo) {
548 const aabb3f &cbox = box_info.box;
551 See if the object is touching ground.
553 Object touches ground if object's minimum Y is near node's
554 maximum Y and object's X-Z-area overlaps with the node's
558 if (cbox.MaxEdge.X - d > box.MinEdge.X && cbox.MinEdge.X + d < box.MaxEdge.X &&
559 cbox.MaxEdge.Z - d > box.MinEdge.Z &&
560 cbox.MinEdge.Z + d < box.MaxEdge.Z) {
561 if (box_info.is_step_up) {
562 pos_f->Y += cbox.MaxEdge.Y - box.MinEdge.Y;
564 box.MinEdge += *pos_f;
565 box.MaxEdge += *pos_f;
567 if (std::fabs(cbox.MaxEdge.Y - box.MinEdge.Y) < 0.05f) {
568 result.touching_ground = true;
570 if (box_info.is_object)
571 result.standing_on_object = true;