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
35 // Checks for collision of a moving aabbox with a static aabbox
36 // Returns -1 if no collision, 0 if X collision, 1 if Y collision, 2 if Z collision
37 // The time after which the collision occurs is stored in dtime.
38 int axisAlignedCollision(
39 const aabb3f &staticbox, const aabb3f &movingbox,
40 const v3f &speed, f32 d, f32 &dtime)
42 //TimeTaker tt("axisAlignedCollision");
44 f32 xsize = (staticbox.MaxEdge.X - staticbox.MinEdge.X);
45 f32 ysize = (staticbox.MaxEdge.Y - staticbox.MinEdge.Y);
46 f32 zsize = (staticbox.MaxEdge.Z - staticbox.MinEdge.Z);
49 movingbox.MinEdge.X - staticbox.MinEdge.X,
50 movingbox.MinEdge.Y - staticbox.MinEdge.Y,
51 movingbox.MinEdge.Z - staticbox.MinEdge.Z,
52 movingbox.MaxEdge.X - staticbox.MinEdge.X,
53 movingbox.MaxEdge.Y - staticbox.MinEdge.Y,
54 movingbox.MaxEdge.Z - staticbox.MinEdge.Z
57 if(speed.X > 0) // Check for collision with X- plane
59 if(relbox.MaxEdge.X <= d)
61 dtime = - relbox.MaxEdge.X / speed.X;
62 if((relbox.MinEdge.Y + speed.Y * dtime < ysize) &&
63 (relbox.MaxEdge.Y + speed.Y * dtime > 0) &&
64 (relbox.MinEdge.Z + speed.Z * dtime < zsize) &&
65 (relbox.MaxEdge.Z + speed.Z * dtime > 0))
68 else if(relbox.MinEdge.X > xsize)
73 else if(speed.X < 0) // Check for collision with X+ plane
75 if(relbox.MinEdge.X >= xsize - d)
77 dtime = (xsize - relbox.MinEdge.X) / speed.X;
78 if((relbox.MinEdge.Y + speed.Y * dtime < ysize) &&
79 (relbox.MaxEdge.Y + speed.Y * dtime > 0) &&
80 (relbox.MinEdge.Z + speed.Z * dtime < zsize) &&
81 (relbox.MaxEdge.Z + speed.Z * dtime > 0))
84 else if(relbox.MaxEdge.X < 0)
92 if(speed.Y > 0) // Check for collision with Y- plane
94 if(relbox.MaxEdge.Y <= d)
96 dtime = - relbox.MaxEdge.Y / speed.Y;
97 if((relbox.MinEdge.X + speed.X * dtime < xsize) &&
98 (relbox.MaxEdge.X + speed.X * dtime > 0) &&
99 (relbox.MinEdge.Z + speed.Z * dtime < zsize) &&
100 (relbox.MaxEdge.Z + speed.Z * dtime > 0))
103 else if(relbox.MinEdge.Y > ysize)
108 else if(speed.Y < 0) // Check for collision with Y+ plane
110 if(relbox.MinEdge.Y >= ysize - d)
112 dtime = (ysize - relbox.MinEdge.Y) / speed.Y;
113 if((relbox.MinEdge.X + speed.X * dtime < xsize) &&
114 (relbox.MaxEdge.X + speed.X * dtime > 0) &&
115 (relbox.MinEdge.Z + speed.Z * dtime < zsize) &&
116 (relbox.MaxEdge.Z + speed.Z * dtime > 0))
119 else if(relbox.MaxEdge.Y < 0)
127 if(speed.Z > 0) // Check for collision with Z- plane
129 if(relbox.MaxEdge.Z <= d)
131 dtime = - relbox.MaxEdge.Z / speed.Z;
132 if((relbox.MinEdge.X + speed.X * dtime < xsize) &&
133 (relbox.MaxEdge.X + speed.X * dtime > 0) &&
134 (relbox.MinEdge.Y + speed.Y * dtime < ysize) &&
135 (relbox.MaxEdge.Y + speed.Y * dtime > 0))
138 //else if(relbox.MinEdge.Z > zsize)
143 else if(speed.Z < 0) // Check for collision with Z+ plane
145 if(relbox.MinEdge.Z >= zsize - d)
147 dtime = (zsize - relbox.MinEdge.Z) / speed.Z;
148 if((relbox.MinEdge.X + speed.X * dtime < xsize) &&
149 (relbox.MaxEdge.X + speed.X * dtime > 0) &&
150 (relbox.MinEdge.Y + speed.Y * dtime < ysize) &&
151 (relbox.MaxEdge.Y + speed.Y * dtime > 0))
154 //else if(relbox.MaxEdge.Z < 0)
164 // Checks if moving the movingbox up by the given distance would hit a ceiling.
165 bool wouldCollideWithCeiling(
166 const std::vector<aabb3f> &staticboxes,
167 const aabb3f &movingbox,
168 f32 y_increase, f32 d)
170 //TimeTaker tt("wouldCollideWithCeiling");
172 assert(y_increase >= 0);
174 for(std::vector<aabb3f>::const_iterator
175 i = staticboxes.begin();
176 i != staticboxes.end(); i++)
178 const aabb3f& staticbox = *i;
179 if((movingbox.MaxEdge.Y - d <= staticbox.MinEdge.Y) &&
180 (movingbox.MaxEdge.Y + y_increase > staticbox.MinEdge.Y) &&
181 (movingbox.MinEdge.X < staticbox.MaxEdge.X) &&
182 (movingbox.MaxEdge.X > staticbox.MinEdge.X) &&
183 (movingbox.MinEdge.Z < staticbox.MaxEdge.Z) &&
184 (movingbox.MaxEdge.Z > staticbox.MinEdge.Z))
192 collisionMoveResult collisionMoveSimple(Environment *env, IGameDef *gamedef,
193 f32 pos_max_d, const aabb3f &box_0,
194 f32 stepheight, f32 dtime,
195 v3f &pos_f, v3f &speed_f, v3f &accel_f)
197 Map *map = &env->getMap();
198 //TimeTaker tt("collisionMoveSimple");
199 ScopeProfiler sp(g_profiler, "collisionMoveSimple avg", SPT_AVG);
201 collisionMoveResult result;
204 Calculate new velocity
207 infostream<<"collisionMoveSimple: WARNING: maximum step interval exceeded, lost movement details!"<<std::endl;
210 speed_f += accel_f * dtime;
212 // If there is no speed, there are no collisions
213 if(speed_f.getLength() == 0)
216 // Limit speed for avoiding hangs
217 speed_f.Y=rangelim(speed_f.Y,-5000,5000);
218 speed_f.X=rangelim(speed_f.X,-5000,5000);
219 speed_f.Z=rangelim(speed_f.Z,-5000,5000);
222 Collect node boxes in movement range
224 std::vector<aabb3f> cboxes;
225 std::vector<bool> is_unloaded;
226 std::vector<bool> is_step_up;
227 std::vector<bool> is_object;
228 std::vector<int> bouncy_values;
229 std::vector<v3s16> node_positions;
231 //TimeTaker tt2("collisionMoveSimple collect boxes");
232 ScopeProfiler sp(g_profiler, "collisionMoveSimple collect boxes avg", SPT_AVG);
234 v3s16 oldpos_i = floatToInt(pos_f, BS);
235 v3s16 newpos_i = floatToInt(pos_f + speed_f * dtime, BS);
236 s16 min_x = MYMIN(oldpos_i.X, newpos_i.X) + (box_0.MinEdge.X / BS) - 1;
237 s16 min_y = MYMIN(oldpos_i.Y, newpos_i.Y) + (box_0.MinEdge.Y / BS) - 1;
238 s16 min_z = MYMIN(oldpos_i.Z, newpos_i.Z) + (box_0.MinEdge.Z / BS) - 1;
239 s16 max_x = MYMAX(oldpos_i.X, newpos_i.X) + (box_0.MaxEdge.X / BS) + 1;
240 s16 max_y = MYMAX(oldpos_i.Y, newpos_i.Y) + (box_0.MaxEdge.Y / BS) + 1;
241 s16 max_z = MYMAX(oldpos_i.Z, newpos_i.Z) + (box_0.MaxEdge.Z / BS) + 1;
243 for(s16 x = min_x; x <= max_x; x++)
244 for(s16 y = min_y; y <= max_y; y++)
245 for(s16 z = min_z; z <= max_z; z++)
249 // Object collides into walkable nodes
250 MapNode n = map->getNode(p);
251 const ContentFeatures &f = gamedef->getNodeDefManager()->get(n);
252 if(f.walkable == false)
254 int n_bouncy_value = itemgroup_get(f.groups, "bouncy");
256 std::vector<aabb3f> nodeboxes = n.getNodeBoxes(gamedef->ndef());
257 for(std::vector<aabb3f>::iterator
258 i = nodeboxes.begin();
259 i != nodeboxes.end(); i++)
262 box.MinEdge += v3f(x, y, z)*BS;
263 box.MaxEdge += v3f(x, y, z)*BS;
264 cboxes.push_back(box);
265 is_unloaded.push_back(false);
266 is_step_up.push_back(false);
267 bouncy_values.push_back(n_bouncy_value);
268 node_positions.push_back(p);
269 is_object.push_back(false);
272 catch(InvalidPositionException &e)
274 // Collide with unloaded nodes
275 aabb3f box = getNodeBox(p, BS);
276 cboxes.push_back(box);
277 is_unloaded.push_back(true);
278 is_step_up.push_back(false);
279 bouncy_values.push_back(0);
280 node_positions.push_back(p);
281 is_object.push_back(false);
287 ScopeProfiler sp(g_profiler, "collisionMoveSimple objects avg", SPT_AVG);
288 //TimeTaker tt3("collisionMoveSimple collect object boxes");
290 /* add object boxes to cboxes */
293 std::list<ActiveObject*> objects;
295 ClientEnvironment *c_env = dynamic_cast<ClientEnvironment*>(env);
298 f32 distance = speed_f.getLength();
299 std::vector<DistanceSortedActiveObject> clientobjects;
300 c_env->getActiveObjects(pos_f,distance * 1.5,clientobjects);
301 for (int i=0; i < clientobjects.size(); i++)
303 objects.push_back((ActiveObject*)clientobjects[i].obj);
309 ServerEnvironment *s_env = dynamic_cast<ServerEnvironment*>(env);
312 f32 distance = speed_f.getLength();
313 std::set<u16> s_objects = s_env->getObjectsInsideRadius(pos_f,distance * 1.5);
314 for (std::set<u16>::iterator iter = s_objects.begin(); iter != s_objects.end(); iter++)
316 ServerActiveObject *current = s_env->getActiveObject(*iter);
317 objects.push_back((ActiveObject*)current);
322 for (std::list<ActiveObject*>::const_iterator iter = objects.begin();iter != objects.end(); ++iter)
324 ActiveObject *object = *iter;
328 aabb3f object_collisionbox;
329 if (object->getCollisionBox(&object_collisionbox))
331 cboxes.push_back(object_collisionbox);
332 is_unloaded.push_back(false);
333 is_step_up.push_back(false);
334 bouncy_values.push_back(0);
335 node_positions.push_back(v3s16(0,0,0));
336 is_object.push_back(true);
342 assert(cboxes.size() == is_unloaded.size());
343 assert(cboxes.size() == is_step_up.size());
344 assert(cboxes.size() == bouncy_values.size());
345 assert(cboxes.size() == node_positions.size());
346 assert(cboxes.size() == is_object.size());
353 Collision uncertainty radius
354 Make it a bit larger than the maximum distance of movement
356 f32 d = pos_max_d * 1.1;
357 // A fairly large value in here makes moving smoother
360 // This should always apply, otherwise there are glitches
361 assert(d > pos_max_d);
365 while(dtime > BS*1e-10)
367 //TimeTaker tt3("collisionMoveSimple dtime loop");
368 ScopeProfiler sp(g_profiler, "collisionMoveSimple dtime loop avg", SPT_AVG);
370 // Avoid infinite loop
374 infostream<<"collisionMoveSimple: WARNING: Loop count exceeded, aborting to avoid infiniite loop"<<std::endl;
379 aabb3f movingbox = box_0;
380 movingbox.MinEdge += pos_f;
381 movingbox.MaxEdge += pos_f;
383 int nearest_collided = -1;
384 f32 nearest_dtime = dtime;
385 u32 nearest_boxindex = -1;
388 Go through every nodebox, find nearest collision
390 for(u32 boxindex = 0; boxindex < cboxes.size(); boxindex++)
392 // Ignore if already stepped up this nodebox.
393 if(is_step_up[boxindex])
396 // Find nearest collision of the two boxes (raytracing-like)
398 int collided = axisAlignedCollision(
399 cboxes[boxindex], movingbox, speed_f, d, dtime_tmp);
401 if(collided == -1 || dtime_tmp >= nearest_dtime)
404 nearest_dtime = dtime_tmp;
405 nearest_collided = collided;
406 nearest_boxindex = boxindex;
409 if(nearest_collided == -1)
411 // No collision with any collision box.
412 pos_f += speed_f * dtime;
413 dtime = 0; // Set to 0 to avoid "infinite" loop due to small FP numbers
417 // Otherwise, a collision occurred.
419 const aabb3f& cbox = cboxes[nearest_boxindex];
422 bool step_up = (nearest_collided != 1) && // must not be Y direction
423 (movingbox.MinEdge.Y < cbox.MaxEdge.Y) &&
424 (movingbox.MinEdge.Y + stepheight > cbox.MaxEdge.Y) &&
425 (!wouldCollideWithCeiling(cboxes, movingbox,
426 cbox.MaxEdge.Y - movingbox.MinEdge.Y,
429 // Get bounce multiplier
430 bool bouncy = (bouncy_values[nearest_boxindex] >= 1);
431 float bounce = -(float)bouncy_values[nearest_boxindex] / 100.0;
433 // Move to the point of collision and reduce dtime by nearest_dtime
434 if(nearest_dtime < 0)
436 // Handle negative nearest_dtime (can be caused by the d allowance)
439 if(nearest_collided == 0)
440 pos_f.X += speed_f.X * nearest_dtime;
441 if(nearest_collided == 1)
442 pos_f.Y += speed_f.Y * nearest_dtime;
443 if(nearest_collided == 2)
444 pos_f.Z += speed_f.Z * nearest_dtime;
449 pos_f += speed_f * nearest_dtime;
450 dtime -= nearest_dtime;
453 bool is_collision = true;
454 if(is_unloaded[nearest_boxindex])
455 is_collision = false;
458 if (is_object[nearest_boxindex]) {
459 info.type = COLLISION_OBJECT;
462 info.type = COLLISION_NODE;
463 info.node_p = node_positions[nearest_boxindex];
464 info.bouncy = bouncy;
465 info.old_speed = speed_f;
467 // Set the speed component that caused the collision to zero
470 // Special case: Handle stairs
471 is_step_up[nearest_boxindex] = true;
472 is_collision = false;
474 else if(nearest_collided == 0) // X
476 if(fabs(speed_f.X) > BS*3)
480 result.collides = true;
481 result.collides_xz = true;
483 else if(nearest_collided == 1) // Y
485 if(fabs(speed_f.Y) > BS*3)
489 result.collides = true;
491 else if(nearest_collided == 2) // Z
493 if(fabs(speed_f.Z) > BS*3)
497 result.collides = true;
498 result.collides_xz = true;
501 info.new_speed = speed_f;
502 if(info.new_speed.getDistanceFrom(info.old_speed) < 0.1*BS)
503 is_collision = false;
506 result.collisions.push_back(info);
512 Final touches: Check if standing on ground, step up stairs.
515 box.MinEdge += pos_f;
516 box.MaxEdge += pos_f;
517 for(u32 boxindex = 0; boxindex < cboxes.size(); boxindex++)
519 const aabb3f& cbox = cboxes[boxindex];
522 See if the object is touching ground.
524 Object touches ground if object's minimum Y is near node's
525 maximum Y and object's X-Z-area overlaps with the node's
528 Use 0.15*BS so that it is easier to get on a node.
531 cbox.MaxEdge.X-d > box.MinEdge.X &&
532 cbox.MinEdge.X+d < box.MaxEdge.X &&
533 cbox.MaxEdge.Z-d > box.MinEdge.Z &&
534 cbox.MinEdge.Z+d < box.MaxEdge.Z
536 if(is_step_up[boxindex])
538 pos_f.Y += (cbox.MaxEdge.Y - box.MinEdge.Y);
540 box.MinEdge += pos_f;
541 box.MaxEdge += pos_f;
543 if(fabs(cbox.MaxEdge.Y-box.MinEdge.Y) < 0.15*BS)
545 result.touching_ground = true;
546 if(is_unloaded[boxindex])
547 result.standing_on_unloaded = true;
556 // This doesn't seem to work and isn't used
557 collisionMoveResult collisionMovePrecise(Map *map, IGameDef *gamedef,
558 f32 pos_max_d, const aabb3f &box_0,
559 f32 stepheight, f32 dtime,
560 v3f &pos_f, v3f &speed_f, v3f &accel_f)
562 //TimeTaker tt("collisionMovePrecise");
563 ScopeProfiler sp(g_profiler, "collisionMovePrecise avg", SPT_AVG);
565 collisionMoveResult final_result;
567 // If there is no speed, there are no collisions
568 if(speed_f.getLength() == 0)
571 // Don't allow overly huge dtime
575 f32 dtime_downcount = dtime;
582 // Maximum time increment (for collision detection etc)
583 // time = distance / speed
584 f32 dtime_max_increment = 1.0;
585 if(speed_f.getLength() != 0)
586 dtime_max_increment = pos_max_d / speed_f.getLength();
588 // Maximum time increment is 10ms or lower
589 if(dtime_max_increment > 0.01)
590 dtime_max_increment = 0.01;
593 if(dtime_downcount > dtime_max_increment)
595 dtime_part = dtime_max_increment;
596 dtime_downcount -= dtime_part;
600 dtime_part = dtime_downcount;
602 Setting this to 0 (no -=dtime_part) disables an infinite loop
603 when dtime_part is so small that dtime_downcount -= dtime_part
609 collisionMoveResult result = collisionMoveSimple(map, gamedef,
610 pos_max_d, box_0, stepheight, dtime_part,
611 pos_f, speed_f, accel_f);
613 if(result.touching_ground)
614 final_result.touching_ground = true;
616 final_result.collides = true;
617 if(result.collides_xz)
618 final_result.collides_xz = true;
619 if(result.standing_on_unloaded)
620 final_result.standing_on_unloaded = true;
622 while(dtime_downcount > 0.001);