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 "environment.h"
27 #include "serverobject.h"
30 #include "util/timetaker.h"
31 #include "main.h" // g_profiler
34 // float error is 10 - 9.96875 = 0.03125
35 #define COLL_ZERO 0.032
38 // Checks for collision of a moving aabbox with a static aabbox
39 // Returns -1 if no collision, 0 if X collision, 1 if Y collision, 2 if Z collision
40 // The time after which the collision occurs is stored in dtime.
41 int axisAlignedCollision(
42 const aabb3f &staticbox, const aabb3f &movingbox,
43 const v3f &speed, f32 d, f32 &dtime)
45 //TimeTaker tt("axisAlignedCollision");
47 f32 xsize = (staticbox.MaxEdge.X - staticbox.MinEdge.X) - COLL_ZERO; // reduce box size for solve collision stuck (flying sand)
48 f32 ysize = (staticbox.MaxEdge.Y - staticbox.MinEdge.Y); // - COLL_ZERO; // Y - no sense for falling, but maybe try later
49 f32 zsize = (staticbox.MaxEdge.Z - staticbox.MinEdge.Z) - COLL_ZERO;
52 movingbox.MinEdge.X - staticbox.MinEdge.X,
53 movingbox.MinEdge.Y - staticbox.MinEdge.Y,
54 movingbox.MinEdge.Z - staticbox.MinEdge.Z,
55 movingbox.MaxEdge.X - staticbox.MinEdge.X,
56 movingbox.MaxEdge.Y - staticbox.MinEdge.Y,
57 movingbox.MaxEdge.Z - staticbox.MinEdge.Z
60 if(speed.X > 0) // Check for collision with X- plane
62 if(relbox.MaxEdge.X <= d)
64 dtime = - relbox.MaxEdge.X / speed.X;
65 if((relbox.MinEdge.Y + speed.Y * dtime < ysize) &&
66 (relbox.MaxEdge.Y + speed.Y * dtime > COLL_ZERO) &&
67 (relbox.MinEdge.Z + speed.Z * dtime < zsize) &&
68 (relbox.MaxEdge.Z + speed.Z * dtime > COLL_ZERO))
71 else if(relbox.MinEdge.X > xsize)
76 else if(speed.X < 0) // Check for collision with X+ plane
78 if(relbox.MinEdge.X >= xsize - d)
80 dtime = (xsize - relbox.MinEdge.X) / speed.X;
81 if((relbox.MinEdge.Y + speed.Y * dtime < ysize) &&
82 (relbox.MaxEdge.Y + speed.Y * dtime > COLL_ZERO) &&
83 (relbox.MinEdge.Z + speed.Z * dtime < zsize) &&
84 (relbox.MaxEdge.Z + speed.Z * dtime > COLL_ZERO))
87 else if(relbox.MaxEdge.X < 0)
95 if(speed.Y > 0) // Check for collision with Y- plane
97 if(relbox.MaxEdge.Y <= d)
99 dtime = - relbox.MaxEdge.Y / speed.Y;
100 if((relbox.MinEdge.X + speed.X * dtime < xsize) &&
101 (relbox.MaxEdge.X + speed.X * dtime > COLL_ZERO) &&
102 (relbox.MinEdge.Z + speed.Z * dtime < zsize) &&
103 (relbox.MaxEdge.Z + speed.Z * dtime > COLL_ZERO))
106 else if(relbox.MinEdge.Y > ysize)
111 else if(speed.Y < 0) // Check for collision with Y+ plane
113 if(relbox.MinEdge.Y >= ysize - d)
115 dtime = (ysize - relbox.MinEdge.Y) / speed.Y;
116 if((relbox.MinEdge.X + speed.X * dtime < xsize) &&
117 (relbox.MaxEdge.X + speed.X * dtime > COLL_ZERO) &&
118 (relbox.MinEdge.Z + speed.Z * dtime < zsize) &&
119 (relbox.MaxEdge.Z + speed.Z * dtime > COLL_ZERO))
122 else if(relbox.MaxEdge.Y < 0)
130 if(speed.Z > 0) // Check for collision with Z- plane
132 if(relbox.MaxEdge.Z <= d)
134 dtime = - relbox.MaxEdge.Z / speed.Z;
135 if((relbox.MinEdge.X + speed.X * dtime < xsize) &&
136 (relbox.MaxEdge.X + speed.X * dtime > COLL_ZERO) &&
137 (relbox.MinEdge.Y + speed.Y * dtime < ysize) &&
138 (relbox.MaxEdge.Y + speed.Y * dtime > COLL_ZERO))
141 //else if(relbox.MinEdge.Z > zsize)
146 else if(speed.Z < 0) // Check for collision with Z+ plane
148 if(relbox.MinEdge.Z >= zsize - d)
150 dtime = (zsize - relbox.MinEdge.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))
157 //else if(relbox.MaxEdge.Z < 0)
167 // Checks if moving the movingbox up by the given distance would hit a ceiling.
168 bool wouldCollideWithCeiling(
169 const std::vector<aabb3f> &staticboxes,
170 const aabb3f &movingbox,
171 f32 y_increase, f32 d)
173 //TimeTaker tt("wouldCollideWithCeiling");
175 assert(y_increase >= 0);
177 for(std::vector<aabb3f>::const_iterator
178 i = staticboxes.begin();
179 i != staticboxes.end(); i++)
181 const aabb3f& staticbox = *i;
182 if((movingbox.MaxEdge.Y - d <= staticbox.MinEdge.Y) &&
183 (movingbox.MaxEdge.Y + y_increase > staticbox.MinEdge.Y) &&
184 (movingbox.MinEdge.X < staticbox.MaxEdge.X) &&
185 (movingbox.MaxEdge.X > staticbox.MinEdge.X) &&
186 (movingbox.MinEdge.Z < staticbox.MaxEdge.Z) &&
187 (movingbox.MaxEdge.Z > staticbox.MinEdge.Z))
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, v3f &accel_f,ActiveObject* self)
200 Map *map = &env->getMap();
201 //TimeTaker tt("collisionMoveSimple");
202 ScopeProfiler sp(g_profiler, "collisionMoveSimple avg", SPT_AVG);
204 collisionMoveResult result;
207 Calculate new velocity
210 infostream<<"collisionMoveSimple: WARNING: maximum step interval exceeded, lost movement details!"<<std::endl;
213 speed_f += accel_f * dtime;
215 // If there is no speed, there are no collisions
216 if(speed_f.getLength() == 0)
219 // Limit speed for avoiding hangs
220 speed_f.Y=rangelim(speed_f.Y,-5000,5000);
221 speed_f.X=rangelim(speed_f.X,-5000,5000);
222 speed_f.Z=rangelim(speed_f.Z,-5000,5000);
225 Collect node boxes in movement range
227 std::vector<aabb3f> cboxes;
228 std::vector<bool> is_unloaded;
229 std::vector<bool> is_step_up;
230 std::vector<bool> is_object;
231 std::vector<int> bouncy_values;
232 std::vector<v3s16> node_positions;
234 //TimeTaker tt2("collisionMoveSimple collect boxes");
235 ScopeProfiler sp(g_profiler, "collisionMoveSimple collect boxes avg", SPT_AVG);
237 v3s16 oldpos_i = floatToInt(pos_f, BS);
238 v3s16 newpos_i = floatToInt(pos_f + speed_f * dtime, BS);
239 s16 min_x = MYMIN(oldpos_i.X, newpos_i.X) + (box_0.MinEdge.X / BS) - 1;
240 s16 min_y = MYMIN(oldpos_i.Y, newpos_i.Y) + (box_0.MinEdge.Y / BS) - 1;
241 s16 min_z = MYMIN(oldpos_i.Z, newpos_i.Z) + (box_0.MinEdge.Z / BS) - 1;
242 s16 max_x = MYMAX(oldpos_i.X, newpos_i.X) + (box_0.MaxEdge.X / BS) + 1;
243 s16 max_y = MYMAX(oldpos_i.Y, newpos_i.Y) + (box_0.MaxEdge.Y / BS) + 1;
244 s16 max_z = MYMAX(oldpos_i.Z, newpos_i.Z) + (box_0.MaxEdge.Z / BS) + 1;
246 for(s16 x = min_x; x <= max_x; x++)
247 for(s16 y = min_y; y <= max_y; y++)
248 for(s16 z = min_z; z <= max_z; z++)
252 // Object collides into walkable nodes
253 MapNode n = map->getNode(p);
254 const ContentFeatures &f = gamedef->getNodeDefManager()->get(n);
255 if(f.walkable == false)
257 int n_bouncy_value = itemgroup_get(f.groups, "bouncy");
259 std::vector<aabb3f> nodeboxes = n.getNodeBoxes(gamedef->ndef());
260 for(std::vector<aabb3f>::iterator
261 i = nodeboxes.begin();
262 i != nodeboxes.end(); i++)
265 box.MinEdge += v3f(x, y, z)*BS;
266 box.MaxEdge += v3f(x, y, z)*BS;
267 cboxes.push_back(box);
268 is_unloaded.push_back(false);
269 is_step_up.push_back(false);
270 bouncy_values.push_back(n_bouncy_value);
271 node_positions.push_back(p);
272 is_object.push_back(false);
275 catch(InvalidPositionException &e)
277 // Collide with unloaded nodes
278 aabb3f box = getNodeBox(p, BS);
279 cboxes.push_back(box);
280 is_unloaded.push_back(true);
281 is_step_up.push_back(false);
282 bouncy_values.push_back(0);
283 node_positions.push_back(p);
284 is_object.push_back(false);
290 ScopeProfiler sp(g_profiler, "collisionMoveSimple objects avg", SPT_AVG);
291 //TimeTaker tt3("collisionMoveSimple collect object boxes");
293 /* add object boxes to cboxes */
296 std::list<ActiveObject*> objects;
298 ClientEnvironment *c_env = dynamic_cast<ClientEnvironment*>(env);
301 f32 distance = speed_f.getLength();
302 std::vector<DistanceSortedActiveObject> clientobjects;
303 c_env->getActiveObjects(pos_f,distance * 1.5,clientobjects);
304 for (size_t i=0; i < clientobjects.size(); i++)
306 if ((self == 0) || (self != clientobjects[i].obj)) {
307 objects.push_back((ActiveObject*)clientobjects[i].obj);
314 ServerEnvironment *s_env = dynamic_cast<ServerEnvironment*>(env);
317 f32 distance = speed_f.getLength();
318 std::set<u16> s_objects = s_env->getObjectsInsideRadius(pos_f,distance * 1.5);
319 for (std::set<u16>::iterator iter = s_objects.begin(); iter != s_objects.end(); iter++)
321 ServerActiveObject *current = s_env->getActiveObject(*iter);
322 if ((self == 0) || (self != current)) {
323 objects.push_back((ActiveObject*)current);
329 for (std::list<ActiveObject*>::const_iterator iter = objects.begin();iter != objects.end(); ++iter)
331 ActiveObject *object = *iter;
335 aabb3f object_collisionbox;
336 if (object->getCollisionBox(&object_collisionbox))
338 cboxes.push_back(object_collisionbox);
339 is_unloaded.push_back(false);
340 is_step_up.push_back(false);
341 bouncy_values.push_back(0);
342 node_positions.push_back(v3s16(0,0,0));
343 is_object.push_back(true);
349 assert(cboxes.size() == is_unloaded.size());
350 assert(cboxes.size() == is_step_up.size());
351 assert(cboxes.size() == bouncy_values.size());
352 assert(cboxes.size() == node_positions.size());
353 assert(cboxes.size() == is_object.size());
360 Collision uncertainty radius
361 Make it a bit larger than the maximum distance of movement
363 f32 d = pos_max_d * 1.1;
364 // A fairly large value in here makes moving smoother
367 // This should always apply, otherwise there are glitches
368 assert(d > pos_max_d);
372 while(dtime > BS*1e-10)
374 //TimeTaker tt3("collisionMoveSimple dtime loop");
375 ScopeProfiler sp(g_profiler, "collisionMoveSimple dtime loop avg", SPT_AVG);
377 // Avoid infinite loop
381 infostream<<"collisionMoveSimple: WARNING: Loop count exceeded, aborting to avoid infiniite loop"<<std::endl;
386 aabb3f movingbox = box_0;
387 movingbox.MinEdge += pos_f;
388 movingbox.MaxEdge += pos_f;
390 int nearest_collided = -1;
391 f32 nearest_dtime = dtime;
392 u32 nearest_boxindex = -1;
395 Go through every nodebox, find nearest collision
397 for(u32 boxindex = 0; boxindex < cboxes.size(); boxindex++)
399 // Ignore if already stepped up this nodebox.
400 if(is_step_up[boxindex])
403 // Find nearest collision of the two boxes (raytracing-like)
405 int collided = axisAlignedCollision(
406 cboxes[boxindex], movingbox, speed_f, d, dtime_tmp);
408 if(collided == -1 || dtime_tmp >= nearest_dtime)
411 nearest_dtime = dtime_tmp;
412 nearest_collided = collided;
413 nearest_boxindex = boxindex;
416 if(nearest_collided == -1)
418 // No collision with any collision box.
419 pos_f += speed_f * dtime;
420 dtime = 0; // Set to 0 to avoid "infinite" loop due to small FP numbers
424 // Otherwise, a collision occurred.
426 const aabb3f& cbox = cboxes[nearest_boxindex];
429 bool step_up = (nearest_collided != 1) && // must not be Y direction
430 (movingbox.MinEdge.Y < cbox.MaxEdge.Y) &&
431 (movingbox.MinEdge.Y + stepheight > cbox.MaxEdge.Y) &&
432 (!wouldCollideWithCeiling(cboxes, movingbox,
433 cbox.MaxEdge.Y - movingbox.MinEdge.Y,
436 // Get bounce multiplier
437 bool bouncy = (bouncy_values[nearest_boxindex] >= 1);
438 float bounce = -(float)bouncy_values[nearest_boxindex] / 100.0;
440 // Move to the point of collision and reduce dtime by nearest_dtime
441 if(nearest_dtime < 0)
443 // Handle negative nearest_dtime (can be caused by the d allowance)
446 if(nearest_collided == 0)
447 pos_f.X += speed_f.X * nearest_dtime;
448 if(nearest_collided == 1)
449 pos_f.Y += speed_f.Y * nearest_dtime;
450 if(nearest_collided == 2)
451 pos_f.Z += speed_f.Z * nearest_dtime;
456 pos_f += speed_f * nearest_dtime;
457 dtime -= nearest_dtime;
460 bool is_collision = true;
461 if(is_unloaded[nearest_boxindex])
462 is_collision = false;
465 if (is_object[nearest_boxindex]) {
466 info.type = COLLISION_OBJECT;
469 info.type = COLLISION_NODE;
471 info.node_p = node_positions[nearest_boxindex];
472 info.bouncy = bouncy;
473 info.old_speed = speed_f;
475 // Set the speed component that caused the collision to zero
478 // Special case: Handle stairs
479 is_step_up[nearest_boxindex] = true;
480 is_collision = false;
482 else if(nearest_collided == 0) // X
484 if(fabs(speed_f.X) > BS*3)
488 result.collides = true;
489 result.collides_xz = true;
491 else if(nearest_collided == 1) // Y
493 if(fabs(speed_f.Y) > BS*3)
497 result.collides = true;
499 else if(nearest_collided == 2) // Z
501 if(fabs(speed_f.Z) > BS*3)
505 result.collides = true;
506 result.collides_xz = true;
509 info.new_speed = speed_f;
510 if(info.new_speed.getDistanceFrom(info.old_speed) < 0.1*BS)
511 is_collision = false;
514 result.collisions.push_back(info);
520 Final touches: Check if standing on ground, step up stairs.
523 box.MinEdge += pos_f;
524 box.MaxEdge += pos_f;
525 for(u32 boxindex = 0; boxindex < cboxes.size(); boxindex++)
527 const aabb3f& cbox = cboxes[boxindex];
530 See if the object is touching ground.
532 Object touches ground if object's minimum Y is near node's
533 maximum Y and object's X-Z-area overlaps with the node's
536 Use 0.15*BS so that it is easier to get on a node.
539 cbox.MaxEdge.X-d > box.MinEdge.X &&
540 cbox.MinEdge.X+d < box.MaxEdge.X &&
541 cbox.MaxEdge.Z-d > box.MinEdge.Z &&
542 cbox.MinEdge.Z+d < box.MaxEdge.Z
544 if(is_step_up[boxindex])
546 pos_f.Y += (cbox.MaxEdge.Y - box.MinEdge.Y);
548 box.MinEdge += pos_f;
549 box.MaxEdge += pos_f;
551 if(fabs(cbox.MaxEdge.Y-box.MinEdge.Y) < 0.15*BS)
553 result.touching_ground = true;
554 if(is_unloaded[boxindex])
555 result.standing_on_unloaded = true;
564 // This doesn't seem to work and isn't used
565 collisionMoveResult collisionMovePrecise(Map *map, IGameDef *gamedef,
566 f32 pos_max_d, const aabb3f &box_0,
567 f32 stepheight, f32 dtime,
568 v3f &pos_f, v3f &speed_f, v3f &accel_f)
570 //TimeTaker tt("collisionMovePrecise");
571 ScopeProfiler sp(g_profiler, "collisionMovePrecise avg", SPT_AVG);
573 collisionMoveResult final_result;
575 // If there is no speed, there are no collisions
576 if(speed_f.getLength() == 0)
579 // Don't allow overly huge dtime
583 f32 dtime_downcount = dtime;
590 // Maximum time increment (for collision detection etc)
591 // time = distance / speed
592 f32 dtime_max_increment = 1.0;
593 if(speed_f.getLength() != 0)
594 dtime_max_increment = pos_max_d / speed_f.getLength();
596 // Maximum time increment is 10ms or lower
597 if(dtime_max_increment > 0.01)
598 dtime_max_increment = 0.01;
601 if(dtime_downcount > dtime_max_increment)
603 dtime_part = dtime_max_increment;
604 dtime_downcount -= dtime_part;
608 dtime_part = dtime_downcount;
610 Setting this to 0 (no -=dtime_part) disables an infinite loop
611 when dtime_part is so small that dtime_downcount -= dtime_part
617 collisionMoveResult result = collisionMoveSimple(map, gamedef,
618 pos_max_d, box_0, stepheight, dtime_part,
619 pos_f, speed_f, accel_f);
621 if(result.touching_ground)
622 final_result.touching_ground = true;
624 final_result.collides = true;
625 if(result.collides_xz)
626 final_result.collides_xz = true;
627 if(result.standing_on_unloaded)
628 final_result.standing_on_unloaded = true;
630 while(dtime_downcount > 0.001);