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"
26 #include "clientenvironment.h"
28 #include "serverenvironment.h"
29 #include "serverobject.h"
30 #include "util/timetaker.h"
33 // float error is 10 - 9.96875 = 0.03125
34 //#define COLL_ZERO 0.032 // broken unit tests
38 struct NearbyCollisionInfo {
39 NearbyCollisionInfo(bool is_ul, bool is_obj, int bouncy,
40 const v3s16 &pos, const aabb3f &box) :
49 bool is_step_up = false;
58 // Checks for collision of a moving aabbox with a static aabbox
59 // Returns -1 if no collision, 0 if X collision, 1 if Y collision, 2 if Z collision
60 // The time after which the collision occurs is stored in dtime.
61 int axisAlignedCollision(
62 const aabb3f &staticbox, const aabb3f &movingbox,
63 const v3f &speed, f32 d, f32 *dtime)
65 //TimeTaker tt("axisAlignedCollision");
67 f32 xsize = (staticbox.MaxEdge.X - staticbox.MinEdge.X) - COLL_ZERO; // reduce box size for solve collision stuck (flying sand)
68 f32 ysize = (staticbox.MaxEdge.Y - staticbox.MinEdge.Y); // - COLL_ZERO; // Y - no sense for falling, but maybe try later
69 f32 zsize = (staticbox.MaxEdge.Z - staticbox.MinEdge.Z) - COLL_ZERO;
72 movingbox.MinEdge.X - staticbox.MinEdge.X,
73 movingbox.MinEdge.Y - staticbox.MinEdge.Y,
74 movingbox.MinEdge.Z - staticbox.MinEdge.Z,
75 movingbox.MaxEdge.X - staticbox.MinEdge.X,
76 movingbox.MaxEdge.Y - staticbox.MinEdge.Y,
77 movingbox.MaxEdge.Z - staticbox.MinEdge.Z
80 if(speed.X > 0) // Check for collision with X- plane
82 if (relbox.MaxEdge.X <= d) {
83 *dtime = -relbox.MaxEdge.X / speed.X;
84 if ((relbox.MinEdge.Y + speed.Y * (*dtime) < ysize) &&
85 (relbox.MaxEdge.Y + speed.Y * (*dtime) > COLL_ZERO) &&
86 (relbox.MinEdge.Z + speed.Z * (*dtime) < zsize) &&
87 (relbox.MaxEdge.Z + speed.Z * (*dtime) > COLL_ZERO))
90 else if(relbox.MinEdge.X > xsize)
95 else if(speed.X < 0) // Check for collision with X+ plane
97 if (relbox.MinEdge.X >= xsize - d) {
98 *dtime = (xsize - relbox.MinEdge.X) / speed.X;
99 if ((relbox.MinEdge.Y + speed.Y * (*dtime) < ysize) &&
100 (relbox.MaxEdge.Y + speed.Y * (*dtime) > COLL_ZERO) &&
101 (relbox.MinEdge.Z + speed.Z * (*dtime) < zsize) &&
102 (relbox.MaxEdge.Z + speed.Z * (*dtime) > COLL_ZERO))
105 else if(relbox.MaxEdge.X < 0)
113 if(speed.Y > 0) // Check for collision with Y- plane
115 if (relbox.MaxEdge.Y <= d) {
116 *dtime = -relbox.MaxEdge.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))
123 else if(relbox.MinEdge.Y > ysize)
128 else if(speed.Y < 0) // Check for collision with Y+ plane
130 if (relbox.MinEdge.Y >= ysize - d) {
131 *dtime = (ysize - relbox.MinEdge.Y) / speed.Y;
132 if ((relbox.MinEdge.X + speed.X * (*dtime) < xsize) &&
133 (relbox.MaxEdge.X + speed.X * (*dtime) > COLL_ZERO) &&
134 (relbox.MinEdge.Z + speed.Z * (*dtime) < zsize) &&
135 (relbox.MaxEdge.Z + speed.Z * (*dtime) > COLL_ZERO))
138 else if(relbox.MaxEdge.Y < 0)
146 if(speed.Z > 0) // Check for collision with Z- plane
148 if (relbox.MaxEdge.Z <= d) {
149 *dtime = -relbox.MaxEdge.Z / speed.Z;
150 if ((relbox.MinEdge.X + speed.X * (*dtime) < xsize) &&
151 (relbox.MaxEdge.X + speed.X * (*dtime) > COLL_ZERO) &&
152 (relbox.MinEdge.Y + speed.Y * (*dtime) < ysize) &&
153 (relbox.MaxEdge.Y + speed.Y * (*dtime) > COLL_ZERO))
156 //else if(relbox.MinEdge.Z > zsize)
161 else if(speed.Z < 0) // Check for collision with Z+ plane
163 if (relbox.MinEdge.Z >= zsize - d) {
164 *dtime = (zsize - relbox.MinEdge.Z) / speed.Z;
165 if ((relbox.MinEdge.X + speed.X * (*dtime) < xsize) &&
166 (relbox.MaxEdge.X + speed.X * (*dtime) > COLL_ZERO) &&
167 (relbox.MinEdge.Y + speed.Y * (*dtime) < ysize) &&
168 (relbox.MaxEdge.Y + speed.Y * (*dtime) > COLL_ZERO))
171 //else if(relbox.MaxEdge.Z < 0)
181 // Checks if moving the movingbox up by the given distance would hit a ceiling.
182 bool wouldCollideWithCeiling(
183 const std::vector<NearbyCollisionInfo> &cinfo,
184 const aabb3f &movingbox,
185 f32 y_increase, f32 d)
187 //TimeTaker tt("wouldCollideWithCeiling");
189 assert(y_increase >= 0); // pre-condition
191 for (const auto &it : cinfo) {
192 const aabb3f &staticbox = it.box;
193 if ((movingbox.MaxEdge.Y - d <= staticbox.MinEdge.Y) &&
194 (movingbox.MaxEdge.Y + y_increase > staticbox.MinEdge.Y) &&
195 (movingbox.MinEdge.X < staticbox.MaxEdge.X) &&
196 (movingbox.MaxEdge.X > staticbox.MinEdge.X) &&
197 (movingbox.MinEdge.Z < staticbox.MaxEdge.Z) &&
198 (movingbox.MaxEdge.Z > staticbox.MinEdge.Z))
205 static inline void getNeighborConnectingFace(const v3s16 &p,
206 const NodeDefManager *nodedef, Map *map, MapNode n, int v, int *neighbors)
208 MapNode n2 = map->getNodeNoEx(p);
209 if (nodedef->nodeboxConnects(n, n2, v))
213 collisionMoveResult collisionMoveSimple(Environment *env, IGameDef *gamedef,
214 f32 pos_max_d, const aabb3f &box_0,
215 f32 stepheight, f32 dtime,
216 v3f *pos_f, v3f *speed_f,
217 v3f accel_f, ActiveObject *self,
218 bool collideWithObjects)
220 static bool time_notification_done = false;
221 Map *map = &env->getMap();
222 //TimeTaker tt("collisionMoveSimple");
223 ScopeProfiler sp(g_profiler, "collisionMoveSimple avg", SPT_AVG);
225 collisionMoveResult result;
228 Calculate new velocity
231 if (!time_notification_done) {
232 time_notification_done = true;
233 infostream << "collisionMoveSimple: maximum step interval exceeded,"
234 " lost movement details!"<<std::endl;
238 time_notification_done = false;
240 *speed_f += accel_f * dtime;
242 // If there is no speed, there are no collisions
243 if (speed_f->getLength() == 0)
246 // Limit speed for avoiding hangs
247 speed_f->Y = rangelim(speed_f->Y, -5000, 5000);
248 speed_f->X = rangelim(speed_f->X, -5000, 5000);
249 speed_f->Z = rangelim(speed_f->Z, -5000, 5000);
252 Collect node boxes in movement range
254 std::vector<NearbyCollisionInfo> cinfo;
256 //TimeTaker tt2("collisionMoveSimple collect boxes");
257 ScopeProfiler sp2(g_profiler, "collisionMoveSimple collect boxes avg", SPT_AVG);
259 v3f newpos_f = *pos_f + *speed_f * dtime;
261 MYMIN(pos_f->X, newpos_f.X),
262 MYMIN(pos_f->Y, newpos_f.Y) + 0.01f * BS, // bias rounding, player often at +/-n.5
263 MYMIN(pos_f->Z, newpos_f.Z)
266 MYMAX(pos_f->X, newpos_f.X),
267 MYMAX(pos_f->Y, newpos_f.Y),
268 MYMAX(pos_f->Z, newpos_f.Z)
270 v3s16 min = floatToInt(minpos_f + box_0.MinEdge, BS) - v3s16(1, 1, 1);
271 v3s16 max = floatToInt(maxpos_f + box_0.MaxEdge, BS) + v3s16(1, 1, 1);
273 bool any_position_valid = false;
276 for (p.X = min.X; p.X <= max.X; p.X++)
277 for (p.Y = min.Y; p.Y <= max.Y; p.Y++)
278 for (p.Z = min.Z; p.Z <= max.Z; p.Z++) {
279 bool is_position_valid;
280 MapNode n = map->getNodeNoEx(p, &is_position_valid);
282 if (is_position_valid && n.getContent() != CONTENT_IGNORE) {
283 // Object collides into walkable nodes
285 any_position_valid = true;
286 const NodeDefManager *nodedef = gamedef->getNodeDefManager();
287 const ContentFeatures &f = nodedef->get(n);
292 int n_bouncy_value = itemgroup_get(f.groups, "bouncy");
295 if (f.drawtype == NDT_NODEBOX &&
296 f.node_box.type == NODEBOX_CONNECTED) {
300 getNeighborConnectingFace(p2, nodedef, map, n, 1, &neighbors);
304 getNeighborConnectingFace(p2, nodedef, map, n, 2, &neighbors);
308 getNeighborConnectingFace(p2, nodedef, map, n, 4, &neighbors);
312 getNeighborConnectingFace(p2, nodedef, map, n, 8, &neighbors);
316 getNeighborConnectingFace(p2, nodedef, map, n, 16, &neighbors);
320 getNeighborConnectingFace(p2, nodedef, map, n, 32, &neighbors);
322 std::vector<aabb3f> nodeboxes;
323 n.getCollisionBoxes(gamedef->ndef(), &nodeboxes, neighbors);
324 for (auto box : nodeboxes) {
325 box.MinEdge += intToFloat(p, BS);
326 box.MaxEdge += intToFloat(p, BS);
327 cinfo.emplace_back(false, false, n_bouncy_value, p, box);
330 // Collide with unloaded nodes (position invalid) and loaded
331 // CONTENT_IGNORE nodes (position valid)
332 aabb3f box = getNodeBox(p, BS);
333 cinfo.emplace_back(true, false, 0, p, box);
337 // Do not move if world has not loaded yet, since custom node boxes
338 // are not available for collision detection.
339 // This also intentionally occurs in the case of the object being positioned
340 // solely on loaded CONTENT_IGNORE nodes, no matter where they come from.
341 if (!any_position_valid) {
342 *speed_f = v3f(0, 0, 0);
348 if(collideWithObjects)
350 ScopeProfiler sp2(g_profiler, "collisionMoveSimple objects avg", SPT_AVG);
351 //TimeTaker tt3("collisionMoveSimple collect object boxes");
353 /* add object boxes to cinfo */
355 std::vector<ActiveObject*> objects;
357 ClientEnvironment *c_env = dynamic_cast<ClientEnvironment*>(env);
359 f32 distance = speed_f->getLength();
360 std::vector<DistanceSortedActiveObject> clientobjects;
361 c_env->getActiveObjects(*pos_f, distance * 1.5f, clientobjects);
362 for (auto &clientobject : clientobjects) {
363 if (!self || (self != clientobject.obj)) {
364 objects.push_back((ActiveObject*) clientobject.obj);
371 ServerEnvironment *s_env = dynamic_cast<ServerEnvironment*>(env);
373 f32 distance = speed_f->getLength();
374 std::vector<u16> s_objects;
375 s_env->getObjectsInsideRadius(s_objects, *pos_f, distance * 1.5f);
376 for (u16 obj_id : s_objects) {
377 ServerActiveObject *current = s_env->getActiveObject(obj_id);
378 if (!self || (self != current)) {
379 objects.push_back((ActiveObject*)current);
385 for (std::vector<ActiveObject*>::const_iterator iter = objects.begin();
386 iter != objects.end(); ++iter) {
387 ActiveObject *object = *iter;
390 aabb3f object_collisionbox;
391 if (object->getCollisionBox(&object_collisionbox) &&
392 object->collideWithObjects()) {
393 cinfo.emplace_back(false, true, 0, v3s16(), object_collisionbox);
404 Collision uncertainty radius
405 Make it a bit larger than the maximum distance of movement
407 f32 d = pos_max_d * 1.1f;
408 // A fairly large value in here makes moving smoother
411 // This should always apply, otherwise there are glitches
412 assert(d > pos_max_d); // invariant
416 while(dtime > BS * 1e-10f) {
417 //TimeTaker tt3("collisionMoveSimple dtime loop");
418 ScopeProfiler sp2(g_profiler, "collisionMoveSimple dtime loop avg", SPT_AVG);
420 // Avoid infinite loop
422 if (loopcount >= 100) {
423 warningstream << "collisionMoveSimple: Loop count exceeded, aborting to avoid infiniite loop" << std::endl;
427 aabb3f movingbox = box_0;
428 movingbox.MinEdge += *pos_f;
429 movingbox.MaxEdge += *pos_f;
431 int nearest_collided = -1;
432 f32 nearest_dtime = dtime;
433 int nearest_boxindex = -1;
436 Go through every nodebox, find nearest collision
438 for (u32 boxindex = 0; boxindex < cinfo.size(); boxindex++) {
439 NearbyCollisionInfo box_info = cinfo[boxindex];
440 // Ignore if already stepped up this nodebox.
441 if (box_info.is_step_up)
444 // Find nearest collision of the two boxes (raytracing-like)
446 int collided = axisAlignedCollision(box_info.box,
447 movingbox, *speed_f, d, &dtime_tmp);
449 if (collided == -1 || dtime_tmp >= nearest_dtime)
452 nearest_dtime = dtime_tmp;
453 nearest_collided = collided;
454 nearest_boxindex = boxindex;
457 if (nearest_collided == -1) {
458 // No collision with any collision box.
459 *pos_f += *speed_f * dtime;
460 dtime = 0; // Set to 0 to avoid "infinite" loop due to small FP numbers
462 // Otherwise, a collision occurred.
463 NearbyCollisionInfo &nearest_info = cinfo[nearest_boxindex];
464 const aabb3f& cbox = nearest_info.box;
466 bool step_up = (nearest_collided != 1) && // must not be Y direction
467 (movingbox.MinEdge.Y < cbox.MaxEdge.Y) &&
468 (movingbox.MinEdge.Y + stepheight > cbox.MaxEdge.Y) &&
469 (!wouldCollideWithCeiling(cinfo, movingbox,
470 cbox.MaxEdge.Y - movingbox.MinEdge.Y,
473 // Get bounce multiplier
474 float bounce = -(float)nearest_info.bouncy / 100.0f;
476 // Move to the point of collision and reduce dtime by nearest_dtime
477 if (nearest_dtime < 0) {
478 // Handle negative nearest_dtime (can be caused by the d allowance)
480 if (nearest_collided == 0)
481 pos_f->X += speed_f->X * nearest_dtime;
482 if (nearest_collided == 1)
483 pos_f->Y += speed_f->Y * nearest_dtime;
484 if (nearest_collided == 2)
485 pos_f->Z += speed_f->Z * nearest_dtime;
488 *pos_f += *speed_f * nearest_dtime;
489 dtime -= nearest_dtime;
492 bool is_collision = true;
493 if (nearest_info.is_unloaded)
494 is_collision = false;
497 if (nearest_info.is_object)
498 info.type = COLLISION_OBJECT;
500 info.type = COLLISION_NODE;
502 info.node_p = nearest_info.position;
503 info.old_speed = *speed_f;
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 == 0) { // X
511 if (fabs(speed_f->X) > BS * 3)
512 speed_f->X *= bounce;
515 result.collides = true;
516 } else if (nearest_collided == 1) { // Y
517 if(fabs(speed_f->Y) > BS * 3)
518 speed_f->Y *= bounce;
521 result.collides = true;
522 } else if (nearest_collided == 2) { // 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 result.collisions.push_back(info);
541 Final touches: Check if standing on ground, step up stairs.
544 box.MinEdge += *pos_f;
545 box.MaxEdge += *pos_f;
546 for (const auto &box_info : cinfo) {
547 const aabb3f &cbox = box_info.box;
550 See if the object is touching ground.
552 Object touches ground if object's minimum Y is near node's
553 maximum Y and object's X-Z-area overlaps with the node's
556 Use 0.15*BS so that it is easier to get on a node.
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 (fabs(cbox.MaxEdge.Y - box.MinEdge.Y) < 0.15f * BS) {
568 result.touching_ground = true;
570 if (box_info.is_object)
571 result.standing_on_object = true;