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 // broken unit tests
39 // Checks for collision of a moving aabbox with a static aabbox
40 // Returns -1 if no collision, 0 if X collision, 1 if Y collision, 2 if Z collision
41 // The time after which the collision occurs is stored in dtime.
42 int axisAlignedCollision(
43 const aabb3f &staticbox, const aabb3f &movingbox,
44 const v3f &speed, f32 d, f32 &dtime)
46 //TimeTaker tt("axisAlignedCollision");
48 f32 xsize = (staticbox.MaxEdge.X - staticbox.MinEdge.X) - COLL_ZERO; // reduce box size for solve collision stuck (flying sand)
49 f32 ysize = (staticbox.MaxEdge.Y - staticbox.MinEdge.Y); // - COLL_ZERO; // Y - no sense for falling, but maybe try later
50 f32 zsize = (staticbox.MaxEdge.Z - staticbox.MinEdge.Z) - COLL_ZERO;
53 movingbox.MinEdge.X - staticbox.MinEdge.X,
54 movingbox.MinEdge.Y - staticbox.MinEdge.Y,
55 movingbox.MinEdge.Z - staticbox.MinEdge.Z,
56 movingbox.MaxEdge.X - staticbox.MinEdge.X,
57 movingbox.MaxEdge.Y - staticbox.MinEdge.Y,
58 movingbox.MaxEdge.Z - staticbox.MinEdge.Z
61 if(speed.X > 0) // Check for collision with X- plane
63 if(relbox.MaxEdge.X <= d)
65 dtime = - relbox.MaxEdge.X / speed.X;
66 if((relbox.MinEdge.Y + speed.Y * dtime < ysize) &&
67 (relbox.MaxEdge.Y + speed.Y * dtime > COLL_ZERO) &&
68 (relbox.MinEdge.Z + speed.Z * dtime < zsize) &&
69 (relbox.MaxEdge.Z + speed.Z * dtime > COLL_ZERO))
72 else if(relbox.MinEdge.X > xsize)
77 else if(speed.X < 0) // Check for collision with X+ plane
79 if(relbox.MinEdge.X >= xsize - d)
81 dtime = (xsize - relbox.MinEdge.X) / speed.X;
82 if((relbox.MinEdge.Y + speed.Y * dtime < ysize) &&
83 (relbox.MaxEdge.Y + speed.Y * dtime > COLL_ZERO) &&
84 (relbox.MinEdge.Z + speed.Z * dtime < zsize) &&
85 (relbox.MaxEdge.Z + speed.Z * dtime > COLL_ZERO))
88 else if(relbox.MaxEdge.X < 0)
96 if(speed.Y > 0) // Check for collision with Y- plane
98 if(relbox.MaxEdge.Y <= d)
100 dtime = - relbox.MaxEdge.Y / speed.Y;
101 if((relbox.MinEdge.X + speed.X * dtime < xsize) &&
102 (relbox.MaxEdge.X + speed.X * dtime > COLL_ZERO) &&
103 (relbox.MinEdge.Z + speed.Z * dtime < zsize) &&
104 (relbox.MaxEdge.Z + speed.Z * dtime > COLL_ZERO))
107 else if(relbox.MinEdge.Y > ysize)
112 else if(speed.Y < 0) // Check for collision with Y+ plane
114 if(relbox.MinEdge.Y >= ysize - d)
116 dtime = (ysize - relbox.MinEdge.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.MaxEdge.Y < 0)
131 if(speed.Z > 0) // Check for collision with Z- plane
133 if(relbox.MaxEdge.Z <= d)
135 dtime = - relbox.MaxEdge.Z / speed.Z;
136 if((relbox.MinEdge.X + speed.X * dtime < xsize) &&
137 (relbox.MaxEdge.X + speed.X * dtime > COLL_ZERO) &&
138 (relbox.MinEdge.Y + speed.Y * dtime < ysize) &&
139 (relbox.MaxEdge.Y + speed.Y * dtime > COLL_ZERO))
142 //else if(relbox.MinEdge.Z > zsize)
147 else if(speed.Z < 0) // Check for collision with Z+ plane
149 if(relbox.MinEdge.Z >= zsize - d)
151 dtime = (zsize - relbox.MinEdge.Z) / speed.Z;
152 if((relbox.MinEdge.X + speed.X * dtime < xsize) &&
153 (relbox.MaxEdge.X + speed.X * dtime > COLL_ZERO) &&
154 (relbox.MinEdge.Y + speed.Y * dtime < ysize) &&
155 (relbox.MaxEdge.Y + speed.Y * dtime > COLL_ZERO))
158 //else if(relbox.MaxEdge.Z < 0)
168 // Checks if moving the movingbox up by the given distance would hit a ceiling.
169 bool wouldCollideWithCeiling(
170 const std::vector<aabb3f> &staticboxes,
171 const aabb3f &movingbox,
172 f32 y_increase, f32 d)
174 //TimeTaker tt("wouldCollideWithCeiling");
176 assert(y_increase >= 0);
178 for(std::vector<aabb3f>::const_iterator
179 i = staticboxes.begin();
180 i != staticboxes.end(); i++)
182 const aabb3f& staticbox = *i;
183 if((movingbox.MaxEdge.Y - d <= staticbox.MinEdge.Y) &&
184 (movingbox.MaxEdge.Y + y_increase > staticbox.MinEdge.Y) &&
185 (movingbox.MinEdge.X < staticbox.MaxEdge.X) &&
186 (movingbox.MaxEdge.X > staticbox.MinEdge.X) &&
187 (movingbox.MinEdge.Z < staticbox.MaxEdge.Z) &&
188 (movingbox.MaxEdge.Z > staticbox.MinEdge.Z))
196 collisionMoveResult collisionMoveSimple(Environment *env, IGameDef *gamedef,
197 f32 pos_max_d, const aabb3f &box_0,
198 f32 stepheight, f32 dtime,
199 v3f &pos_f, v3f &speed_f,
200 v3f &accel_f,ActiveObject* self,
201 bool collideWithObjects)
203 Map *map = &env->getMap();
204 //TimeTaker tt("collisionMoveSimple");
205 ScopeProfiler sp(g_profiler, "collisionMoveSimple avg", SPT_AVG);
207 collisionMoveResult result;
210 Calculate new velocity
213 infostream<<"collisionMoveSimple: WARNING: maximum step interval exceeded, lost movement details!"<<std::endl;
216 speed_f += accel_f * dtime;
218 // If there is no speed, there are no collisions
219 if(speed_f.getLength() == 0)
222 // Limit speed for avoiding hangs
223 speed_f.Y=rangelim(speed_f.Y,-5000,5000);
224 speed_f.X=rangelim(speed_f.X,-5000,5000);
225 speed_f.Z=rangelim(speed_f.Z,-5000,5000);
228 Collect node boxes in movement range
230 std::vector<aabb3f> cboxes;
231 std::vector<bool> is_unloaded;
232 std::vector<bool> is_step_up;
233 std::vector<bool> is_object;
234 std::vector<int> bouncy_values;
235 std::vector<v3s16> node_positions;
237 //TimeTaker tt2("collisionMoveSimple collect boxes");
238 ScopeProfiler sp(g_profiler, "collisionMoveSimple collect boxes avg", SPT_AVG);
240 v3s16 oldpos_i = floatToInt(pos_f, BS);
241 v3s16 newpos_i = floatToInt(pos_f + speed_f * dtime, BS);
242 s16 min_x = MYMIN(oldpos_i.X, newpos_i.X) + (box_0.MinEdge.X / BS) - 1;
243 s16 min_y = MYMIN(oldpos_i.Y, newpos_i.Y) + (box_0.MinEdge.Y / BS) - 1;
244 s16 min_z = MYMIN(oldpos_i.Z, newpos_i.Z) + (box_0.MinEdge.Z / BS) - 1;
245 s16 max_x = MYMAX(oldpos_i.X, newpos_i.X) + (box_0.MaxEdge.X / BS) + 1;
246 s16 max_y = MYMAX(oldpos_i.Y, newpos_i.Y) + (box_0.MaxEdge.Y / BS) + 1;
247 s16 max_z = MYMAX(oldpos_i.Z, newpos_i.Z) + (box_0.MaxEdge.Z / BS) + 1;
249 for(s16 x = min_x; x <= max_x; x++)
250 for(s16 y = min_y; y <= max_y; y++)
251 for(s16 z = min_z; z <= max_z; z++)
255 // Object collides into walkable nodes
256 MapNode n = map->getNode(p);
257 const ContentFeatures &f = gamedef->getNodeDefManager()->get(n);
258 if(f.walkable == false)
260 int n_bouncy_value = itemgroup_get(f.groups, "bouncy");
262 std::vector<aabb3f> nodeboxes = n.getNodeBoxes(gamedef->ndef());
263 for(std::vector<aabb3f>::iterator
264 i = nodeboxes.begin();
265 i != nodeboxes.end(); i++)
268 box.MinEdge += v3f(x, y, z)*BS;
269 box.MaxEdge += v3f(x, y, z)*BS;
270 cboxes.push_back(box);
271 is_unloaded.push_back(false);
272 is_step_up.push_back(false);
273 bouncy_values.push_back(n_bouncy_value);
274 node_positions.push_back(p);
275 is_object.push_back(false);
278 catch(InvalidPositionException &e)
280 // Collide with unloaded nodes
281 aabb3f box = getNodeBox(p, BS);
282 cboxes.push_back(box);
283 is_unloaded.push_back(true);
284 is_step_up.push_back(false);
285 bouncy_values.push_back(0);
286 node_positions.push_back(p);
287 is_object.push_back(false);
292 if(collideWithObjects)
294 ScopeProfiler sp(g_profiler, "collisionMoveSimple objects avg", SPT_AVG);
295 //TimeTaker tt3("collisionMoveSimple collect object boxes");
297 /* add object boxes to cboxes */
300 std::list<ActiveObject*> objects;
302 ClientEnvironment *c_env = dynamic_cast<ClientEnvironment*>(env);
305 f32 distance = speed_f.getLength();
306 std::vector<DistanceSortedActiveObject> clientobjects;
307 c_env->getActiveObjects(pos_f,distance * 1.5,clientobjects);
308 for (size_t i=0; i < clientobjects.size(); i++)
310 if ((self == 0) || (self != clientobjects[i].obj)) {
311 objects.push_back((ActiveObject*)clientobjects[i].obj);
318 ServerEnvironment *s_env = dynamic_cast<ServerEnvironment*>(env);
321 f32 distance = speed_f.getLength();
322 std::set<u16> s_objects = s_env->getObjectsInsideRadius(pos_f,distance * 1.5);
323 for (std::set<u16>::iterator iter = s_objects.begin(); iter != s_objects.end(); iter++)
325 ServerActiveObject *current = s_env->getActiveObject(*iter);
326 if ((self == 0) || (self != current)) {
327 objects.push_back((ActiveObject*)current);
333 for (std::list<ActiveObject*>::const_iterator iter = objects.begin();iter != objects.end(); ++iter)
335 ActiveObject *object = *iter;
339 aabb3f object_collisionbox;
340 if (object->getCollisionBox(&object_collisionbox) &&
341 object->collideWithObjects())
343 cboxes.push_back(object_collisionbox);
344 is_unloaded.push_back(false);
345 is_step_up.push_back(false);
346 bouncy_values.push_back(0);
347 node_positions.push_back(v3s16(0,0,0));
348 is_object.push_back(true);
354 assert(cboxes.size() == is_unloaded.size());
355 assert(cboxes.size() == is_step_up.size());
356 assert(cboxes.size() == bouncy_values.size());
357 assert(cboxes.size() == node_positions.size());
358 assert(cboxes.size() == is_object.size());
365 Collision uncertainty radius
366 Make it a bit larger than the maximum distance of movement
368 f32 d = pos_max_d * 1.1;
369 // A fairly large value in here makes moving smoother
372 // This should always apply, otherwise there are glitches
373 assert(d > pos_max_d);
377 while(dtime > BS*1e-10)
379 //TimeTaker tt3("collisionMoveSimple dtime loop");
380 ScopeProfiler sp(g_profiler, "collisionMoveSimple dtime loop avg", SPT_AVG);
382 // Avoid infinite loop
386 infostream<<"collisionMoveSimple: WARNING: Loop count exceeded, aborting to avoid infiniite loop"<<std::endl;
391 aabb3f movingbox = box_0;
392 movingbox.MinEdge += pos_f;
393 movingbox.MaxEdge += pos_f;
395 int nearest_collided = -1;
396 f32 nearest_dtime = dtime;
397 u32 nearest_boxindex = -1;
400 Go through every nodebox, find nearest collision
402 for(u32 boxindex = 0; boxindex < cboxes.size(); boxindex++)
404 // Ignore if already stepped up this nodebox.
405 if(is_step_up[boxindex])
408 // Find nearest collision of the two boxes (raytracing-like)
410 int collided = axisAlignedCollision(
411 cboxes[boxindex], movingbox, speed_f, d, dtime_tmp);
413 if(collided == -1 || dtime_tmp >= nearest_dtime)
416 nearest_dtime = dtime_tmp;
417 nearest_collided = collided;
418 nearest_boxindex = boxindex;
421 if(nearest_collided == -1)
423 // No collision with any collision box.
424 pos_f += speed_f * dtime;
425 dtime = 0; // Set to 0 to avoid "infinite" loop due to small FP numbers
429 // Otherwise, a collision occurred.
431 const aabb3f& cbox = cboxes[nearest_boxindex];
434 bool step_up = (nearest_collided != 1) && // must not be Y direction
435 (movingbox.MinEdge.Y < cbox.MaxEdge.Y) &&
436 (movingbox.MinEdge.Y + stepheight > cbox.MaxEdge.Y) &&
437 (!wouldCollideWithCeiling(cboxes, movingbox,
438 cbox.MaxEdge.Y - movingbox.MinEdge.Y,
441 // Get bounce multiplier
442 bool bouncy = (bouncy_values[nearest_boxindex] >= 1);
443 float bounce = -(float)bouncy_values[nearest_boxindex] / 100.0;
445 // Move to the point of collision and reduce dtime by nearest_dtime
446 if(nearest_dtime < 0)
448 // Handle negative nearest_dtime (can be caused by the d allowance)
451 if(nearest_collided == 0)
452 pos_f.X += speed_f.X * nearest_dtime;
453 if(nearest_collided == 1)
454 pos_f.Y += speed_f.Y * nearest_dtime;
455 if(nearest_collided == 2)
456 pos_f.Z += speed_f.Z * nearest_dtime;
461 pos_f += speed_f * nearest_dtime;
462 dtime -= nearest_dtime;
465 bool is_collision = true;
466 if(is_unloaded[nearest_boxindex])
467 is_collision = false;
470 if (is_object[nearest_boxindex]) {
471 info.type = COLLISION_OBJECT;
474 info.type = COLLISION_NODE;
476 info.node_p = node_positions[nearest_boxindex];
477 info.bouncy = bouncy;
478 info.old_speed = speed_f;
480 // Set the speed component that caused the collision to zero
483 // Special case: Handle stairs
484 is_step_up[nearest_boxindex] = true;
485 is_collision = false;
487 else if(nearest_collided == 0) // X
489 if(fabs(speed_f.X) > BS*3)
493 result.collides = true;
494 result.collides_xz = true;
496 else if(nearest_collided == 1) // Y
498 if(fabs(speed_f.Y) > BS*3)
502 result.collides = true;
504 else if(nearest_collided == 2) // Z
506 if(fabs(speed_f.Z) > BS*3)
510 result.collides = true;
511 result.collides_xz = true;
514 info.new_speed = speed_f;
515 if(info.new_speed.getDistanceFrom(info.old_speed) < 0.1*BS)
516 is_collision = false;
519 result.collisions.push_back(info);
525 Final touches: Check if standing on ground, step up stairs.
528 box.MinEdge += pos_f;
529 box.MaxEdge += pos_f;
530 for(u32 boxindex = 0; boxindex < cboxes.size(); boxindex++)
532 const aabb3f& cbox = cboxes[boxindex];
535 See if the object is touching ground.
537 Object touches ground if object's minimum Y is near node's
538 maximum Y and object's X-Z-area overlaps with the node's
541 Use 0.15*BS so that it is easier to get on a node.
544 cbox.MaxEdge.X-d > box.MinEdge.X &&
545 cbox.MinEdge.X+d < box.MaxEdge.X &&
546 cbox.MaxEdge.Z-d > box.MinEdge.Z &&
547 cbox.MinEdge.Z+d < box.MaxEdge.Z
549 if(is_step_up[boxindex])
551 pos_f.Y += (cbox.MaxEdge.Y - box.MinEdge.Y);
553 box.MinEdge += pos_f;
554 box.MaxEdge += pos_f;
556 if(fabs(cbox.MaxEdge.Y-box.MinEdge.Y) < 0.15*BS)
558 result.touching_ground = true;
559 if(is_unloaded[boxindex])
560 result.standing_on_unloaded = true;
569 // This doesn't seem to work and isn't used
570 collisionMoveResult collisionMovePrecise(Map *map, IGameDef *gamedef,
571 f32 pos_max_d, const aabb3f &box_0,
572 f32 stepheight, f32 dtime,
573 v3f &pos_f, v3f &speed_f, v3f &accel_f)
575 //TimeTaker tt("collisionMovePrecise");
576 ScopeProfiler sp(g_profiler, "collisionMovePrecise avg", SPT_AVG);
578 collisionMoveResult final_result;
580 // If there is no speed, there are no collisions
581 if(speed_f.getLength() == 0)
584 // Don't allow overly huge dtime
588 f32 dtime_downcount = dtime;
595 // Maximum time increment (for collision detection etc)
596 // time = distance / speed
597 f32 dtime_max_increment = 1.0;
598 if(speed_f.getLength() != 0)
599 dtime_max_increment = pos_max_d / speed_f.getLength();
601 // Maximum time increment is 10ms or lower
602 if(dtime_max_increment > 0.01)
603 dtime_max_increment = 0.01;
606 if(dtime_downcount > dtime_max_increment)
608 dtime_part = dtime_max_increment;
609 dtime_downcount -= dtime_part;
613 dtime_part = dtime_downcount;
615 Setting this to 0 (no -=dtime_part) disables an infinite loop
616 when dtime_part is so small that dtime_downcount -= dtime_part
622 collisionMoveResult result = collisionMoveSimple(map, gamedef,
623 pos_max_d, box_0, stepheight, dtime_part,
624 pos_f, speed_f, accel_f);
626 if(result.touching_ground)
627 final_result.touching_ground = true;
629 final_result.collides = true;
630 if(result.collides_xz)
631 final_result.collides_xz = true;
632 if(result.standing_on_unloaded)
633 final_result.standing_on_unloaded = true;
635 while(dtime_downcount > 0.001);