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,ActiveObject* self)
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 if ((self == 0) || (self != clientobjects[i].obj)) {
304 objects.push_back((ActiveObject*)clientobjects[i].obj);
311 ServerEnvironment *s_env = dynamic_cast<ServerEnvironment*>(env);
314 f32 distance = speed_f.getLength();
315 std::set<u16> s_objects = s_env->getObjectsInsideRadius(pos_f,distance * 1.5);
316 for (std::set<u16>::iterator iter = s_objects.begin(); iter != s_objects.end(); iter++)
318 ServerActiveObject *current = s_env->getActiveObject(*iter);
319 if ((self == 0) || (self != current)) {
320 objects.push_back((ActiveObject*)current);
326 for (std::list<ActiveObject*>::const_iterator iter = objects.begin();iter != objects.end(); ++iter)
328 ActiveObject *object = *iter;
332 aabb3f object_collisionbox;
333 if (object->getCollisionBox(&object_collisionbox))
335 cboxes.push_back(object_collisionbox);
336 is_unloaded.push_back(false);
337 is_step_up.push_back(false);
338 bouncy_values.push_back(0);
339 node_positions.push_back(v3s16(0,0,0));
340 is_object.push_back(true);
346 assert(cboxes.size() == is_unloaded.size());
347 assert(cboxes.size() == is_step_up.size());
348 assert(cboxes.size() == bouncy_values.size());
349 assert(cboxes.size() == node_positions.size());
350 assert(cboxes.size() == is_object.size());
357 Collision uncertainty radius
358 Make it a bit larger than the maximum distance of movement
360 f32 d = pos_max_d * 1.1;
361 // A fairly large value in here makes moving smoother
364 // This should always apply, otherwise there are glitches
365 assert(d > pos_max_d);
369 while(dtime > BS*1e-10)
371 //TimeTaker tt3("collisionMoveSimple dtime loop");
372 ScopeProfiler sp(g_profiler, "collisionMoveSimple dtime loop avg", SPT_AVG);
374 // Avoid infinite loop
378 infostream<<"collisionMoveSimple: WARNING: Loop count exceeded, aborting to avoid infiniite loop"<<std::endl;
383 aabb3f movingbox = box_0;
384 movingbox.MinEdge += pos_f;
385 movingbox.MaxEdge += pos_f;
387 int nearest_collided = -1;
388 f32 nearest_dtime = dtime;
389 u32 nearest_boxindex = -1;
392 Go through every nodebox, find nearest collision
394 for(u32 boxindex = 0; boxindex < cboxes.size(); boxindex++)
396 // Ignore if already stepped up this nodebox.
397 if(is_step_up[boxindex])
400 // Find nearest collision of the two boxes (raytracing-like)
402 int collided = axisAlignedCollision(
403 cboxes[boxindex], movingbox, speed_f, d, dtime_tmp);
405 if(collided == -1 || dtime_tmp >= nearest_dtime)
408 nearest_dtime = dtime_tmp;
409 nearest_collided = collided;
410 nearest_boxindex = boxindex;
413 if(nearest_collided == -1)
415 // No collision with any collision box.
416 pos_f += speed_f * dtime;
417 dtime = 0; // Set to 0 to avoid "infinite" loop due to small FP numbers
421 // Otherwise, a collision occurred.
423 const aabb3f& cbox = cboxes[nearest_boxindex];
426 bool step_up = (nearest_collided != 1) && // must not be Y direction
427 (movingbox.MinEdge.Y < cbox.MaxEdge.Y) &&
428 (movingbox.MinEdge.Y + stepheight > cbox.MaxEdge.Y) &&
429 (!wouldCollideWithCeiling(cboxes, movingbox,
430 cbox.MaxEdge.Y - movingbox.MinEdge.Y,
433 // Get bounce multiplier
434 bool bouncy = (bouncy_values[nearest_boxindex] >= 1);
435 float bounce = -(float)bouncy_values[nearest_boxindex] / 100.0;
437 // Move to the point of collision and reduce dtime by nearest_dtime
438 if(nearest_dtime < 0)
440 // Handle negative nearest_dtime (can be caused by the d allowance)
443 if(nearest_collided == 0)
444 pos_f.X += speed_f.X * nearest_dtime;
445 if(nearest_collided == 1)
446 pos_f.Y += speed_f.Y * nearest_dtime;
447 if(nearest_collided == 2)
448 pos_f.Z += speed_f.Z * nearest_dtime;
453 pos_f += speed_f * nearest_dtime;
454 dtime -= nearest_dtime;
457 bool is_collision = true;
458 if(is_unloaded[nearest_boxindex])
459 is_collision = false;
462 if (is_object[nearest_boxindex]) {
463 info.type = COLLISION_OBJECT;
466 info.type = COLLISION_NODE;
468 info.node_p = node_positions[nearest_boxindex];
469 info.bouncy = bouncy;
470 info.old_speed = speed_f;
472 // Set the speed component that caused the collision to zero
475 // Special case: Handle stairs
476 is_step_up[nearest_boxindex] = true;
477 is_collision = false;
479 else if(nearest_collided == 0) // X
481 if(fabs(speed_f.X) > BS*3)
485 result.collides = true;
486 result.collides_xz = true;
488 else if(nearest_collided == 1) // Y
490 if(fabs(speed_f.Y) > BS*3)
494 result.collides = true;
496 else if(nearest_collided == 2) // Z
498 if(fabs(speed_f.Z) > BS*3)
502 result.collides = true;
503 result.collides_xz = true;
506 info.new_speed = speed_f;
507 if(info.new_speed.getDistanceFrom(info.old_speed) < 0.1*BS)
508 is_collision = false;
511 result.collisions.push_back(info);
517 Final touches: Check if standing on ground, step up stairs.
520 box.MinEdge += pos_f;
521 box.MaxEdge += pos_f;
522 for(u32 boxindex = 0; boxindex < cboxes.size(); boxindex++)
524 const aabb3f& cbox = cboxes[boxindex];
527 See if the object is touching ground.
529 Object touches ground if object's minimum Y is near node's
530 maximum Y and object's X-Z-area overlaps with the node's
533 Use 0.15*BS so that it is easier to get on a node.
536 cbox.MaxEdge.X-d > box.MinEdge.X &&
537 cbox.MinEdge.X+d < box.MaxEdge.X &&
538 cbox.MaxEdge.Z-d > box.MinEdge.Z &&
539 cbox.MinEdge.Z+d < box.MaxEdge.Z
541 if(is_step_up[boxindex])
543 pos_f.Y += (cbox.MaxEdge.Y - box.MinEdge.Y);
545 box.MinEdge += pos_f;
546 box.MaxEdge += pos_f;
548 if(fabs(cbox.MaxEdge.Y-box.MinEdge.Y) < 0.15*BS)
550 result.touching_ground = true;
551 if(is_unloaded[boxindex])
552 result.standing_on_unloaded = true;
561 // This doesn't seem to work and isn't used
562 collisionMoveResult collisionMovePrecise(Map *map, IGameDef *gamedef,
563 f32 pos_max_d, const aabb3f &box_0,
564 f32 stepheight, f32 dtime,
565 v3f &pos_f, v3f &speed_f, v3f &accel_f)
567 //TimeTaker tt("collisionMovePrecise");
568 ScopeProfiler sp(g_profiler, "collisionMovePrecise avg", SPT_AVG);
570 collisionMoveResult final_result;
572 // If there is no speed, there are no collisions
573 if(speed_f.getLength() == 0)
576 // Don't allow overly huge dtime
580 f32 dtime_downcount = dtime;
587 // Maximum time increment (for collision detection etc)
588 // time = distance / speed
589 f32 dtime_max_increment = 1.0;
590 if(speed_f.getLength() != 0)
591 dtime_max_increment = pos_max_d / speed_f.getLength();
593 // Maximum time increment is 10ms or lower
594 if(dtime_max_increment > 0.01)
595 dtime_max_increment = 0.01;
598 if(dtime_downcount > dtime_max_increment)
600 dtime_part = dtime_max_increment;
601 dtime_downcount -= dtime_part;
605 dtime_part = dtime_downcount;
607 Setting this to 0 (no -=dtime_part) disables an infinite loop
608 when dtime_part is so small that dtime_downcount -= dtime_part
614 collisionMoveResult result = collisionMoveSimple(map, gamedef,
615 pos_max_d, box_0, stepheight, dtime_part,
616 pos_f, speed_f, accel_f);
618 if(result.touching_ground)
619 final_result.touching_ground = true;
621 final_result.collides = true;
622 if(result.collides_xz)
623 final_result.collides_xz = true;
624 if(result.standing_on_unloaded)
625 final_result.standing_on_unloaded = true;
627 while(dtime_downcount > 0.001);