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"
33 // float error is 10 - 9.96875 = 0.03125
34 //#define COLL_ZERO 0.032 // broken unit tests
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) {
63 *dtime = -relbox.MaxEdge.X / speed.X;
64 if ((relbox.MinEdge.Y + speed.Y * (*dtime) < ysize) &&
65 (relbox.MaxEdge.Y + speed.Y * (*dtime) > COLL_ZERO) &&
66 (relbox.MinEdge.Z + speed.Z * (*dtime) < zsize) &&
67 (relbox.MaxEdge.Z + speed.Z * (*dtime) > COLL_ZERO))
70 else if(relbox.MinEdge.X > xsize)
75 else if(speed.X < 0) // Check for collision with X+ plane
77 if (relbox.MinEdge.X >= xsize - d) {
78 *dtime = (xsize - relbox.MinEdge.X) / speed.X;
79 if ((relbox.MinEdge.Y + speed.Y * (*dtime) < ysize) &&
80 (relbox.MaxEdge.Y + speed.Y * (*dtime) > COLL_ZERO) &&
81 (relbox.MinEdge.Z + speed.Z * (*dtime) < zsize) &&
82 (relbox.MaxEdge.Z + speed.Z * (*dtime) > COLL_ZERO))
85 else if(relbox.MaxEdge.X < 0)
93 if(speed.Y > 0) // Check for collision with Y- plane
95 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) > COLL_ZERO) &&
99 (relbox.MinEdge.Z + speed.Z * (*dtime) < zsize) &&
100 (relbox.MaxEdge.Z + speed.Z * (*dtime) > COLL_ZERO))
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) {
111 *dtime = (ysize - relbox.MinEdge.Y) / speed.Y;
112 if ((relbox.MinEdge.X + speed.X * (*dtime) < xsize) &&
113 (relbox.MaxEdge.X + speed.X * (*dtime) > COLL_ZERO) &&
114 (relbox.MinEdge.Z + speed.Z * (*dtime) < zsize) &&
115 (relbox.MaxEdge.Z + speed.Z * (*dtime) > COLL_ZERO))
118 else if(relbox.MaxEdge.Y < 0)
126 if(speed.Z > 0) // Check for collision with Z- plane
128 if (relbox.MaxEdge.Z <= d) {
129 *dtime = -relbox.MaxEdge.Z / speed.Z;
130 if ((relbox.MinEdge.X + speed.X * (*dtime) < xsize) &&
131 (relbox.MaxEdge.X + speed.X * (*dtime) > COLL_ZERO) &&
132 (relbox.MinEdge.Y + speed.Y * (*dtime) < ysize) &&
133 (relbox.MaxEdge.Y + speed.Y * (*dtime) > COLL_ZERO))
136 //else if(relbox.MinEdge.Z > zsize)
141 else if(speed.Z < 0) // Check for collision with Z+ plane
143 if (relbox.MinEdge.Z >= zsize - d) {
144 *dtime = (zsize - relbox.MinEdge.Z) / speed.Z;
145 if ((relbox.MinEdge.X + speed.X * (*dtime) < xsize) &&
146 (relbox.MaxEdge.X + speed.X * (*dtime) > COLL_ZERO) &&
147 (relbox.MinEdge.Y + speed.Y * (*dtime) < ysize) &&
148 (relbox.MaxEdge.Y + speed.Y * (*dtime) > COLL_ZERO))
151 //else if(relbox.MaxEdge.Z < 0)
161 // Checks if moving the movingbox up by the given distance would hit a ceiling.
162 bool wouldCollideWithCeiling(
163 const std::vector<aabb3f> &staticboxes,
164 const aabb3f &movingbox,
165 f32 y_increase, f32 d)
167 //TimeTaker tt("wouldCollideWithCeiling");
169 assert(y_increase >= 0); // pre-condition
171 for(std::vector<aabb3f>::const_iterator
172 i = staticboxes.begin();
173 i != staticboxes.end(); ++i)
175 const aabb3f& staticbox = *i;
176 if((movingbox.MaxEdge.Y - d <= staticbox.MinEdge.Y) &&
177 (movingbox.MaxEdge.Y + y_increase > staticbox.MinEdge.Y) &&
178 (movingbox.MinEdge.X < staticbox.MaxEdge.X) &&
179 (movingbox.MaxEdge.X > staticbox.MinEdge.X) &&
180 (movingbox.MinEdge.Z < staticbox.MaxEdge.Z) &&
181 (movingbox.MaxEdge.Z > staticbox.MinEdge.Z))
189 collisionMoveResult collisionMoveSimple(Environment *env, IGameDef *gamedef,
190 f32 pos_max_d, const aabb3f &box_0,
191 f32 stepheight, f32 dtime,
192 v3f *pos_f, v3f *speed_f,
193 v3f accel_f, ActiveObject *self,
194 bool collideWithObjects)
196 static bool time_notification_done = false;
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 if (!time_notification_done) {
208 time_notification_done = true;
209 infostream << "collisionMoveSimple: maximum step interval exceeded,"
210 " lost movement details!"<<std::endl;
214 time_notification_done = false;
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 bool any_position_valid = false;
251 // The order is important here, must be y first
252 for(s16 y = max_y; y >= min_y; y--)
253 for(s16 x = min_x; x <= max_x; x++)
254 for(s16 z = min_z; z <= max_z; z++)
258 bool is_position_valid;
259 MapNode n = map->getNodeNoEx(p, &is_position_valid);
261 if (is_position_valid) {
262 // Object collides into walkable nodes
264 any_position_valid = true;
265 const ContentFeatures &f = gamedef->getNodeDefManager()->get(n);
266 if(f.walkable == false)
268 int n_bouncy_value = itemgroup_get(f.groups, "bouncy");
270 std::vector<aabb3f> nodeboxes = n.getCollisionBoxes(gamedef->ndef());
271 for(std::vector<aabb3f>::iterator
272 i = nodeboxes.begin();
273 i != nodeboxes.end(); ++i)
276 box.MinEdge += v3f(x, y, z)*BS;
277 box.MaxEdge += v3f(x, y, z)*BS;
278 cboxes.push_back(box);
279 is_unloaded.push_back(false);
280 is_step_up.push_back(false);
281 bouncy_values.push_back(n_bouncy_value);
282 node_positions.push_back(p);
283 is_object.push_back(false);
287 // Collide with unloaded nodes
288 aabb3f box = getNodeBox(p, BS);
289 cboxes.push_back(box);
290 is_unloaded.push_back(true);
291 is_step_up.push_back(false);
292 bouncy_values.push_back(0);
293 node_positions.push_back(p);
294 is_object.push_back(false);
298 // Do not move if world has not loaded yet, since custom node boxes
299 // are not available for collision detection.
300 if (!any_position_valid)
305 if(collideWithObjects)
307 ScopeProfiler sp(g_profiler, "collisionMoveSimple objects avg", SPT_AVG);
308 //TimeTaker tt3("collisionMoveSimple collect object boxes");
310 /* add object boxes to cboxes */
312 std::vector<ActiveObject*> objects;
314 ClientEnvironment *c_env = dynamic_cast<ClientEnvironment*>(env);
316 f32 distance = speed_f->getLength();
317 std::vector<DistanceSortedActiveObject> clientobjects;
318 c_env->getActiveObjects(*pos_f, distance * 1.5, clientobjects);
319 for (size_t i=0; i < clientobjects.size(); i++) {
320 if ((self == 0) || (self != clientobjects[i].obj)) {
321 objects.push_back((ActiveObject*)clientobjects[i].obj);
328 ServerEnvironment *s_env = dynamic_cast<ServerEnvironment*>(env);
330 f32 distance = speed_f->getLength();
331 std::vector<u16> s_objects;
332 s_env->getObjectsInsideRadius(s_objects, *pos_f, distance * 1.5);
333 for (std::vector<u16>::iterator iter = s_objects.begin(); iter != s_objects.end(); ++iter) {
334 ServerActiveObject *current = s_env->getActiveObject(*iter);
335 if ((self == 0) || (self != current)) {
336 objects.push_back((ActiveObject*)current);
342 for (std::vector<ActiveObject*>::const_iterator iter = objects.begin();
343 iter != objects.end(); ++iter) {
344 ActiveObject *object = *iter;
346 if (object != NULL) {
347 aabb3f object_collisionbox;
348 if (object->getCollisionBox(&object_collisionbox) &&
349 object->collideWithObjects()) {
350 cboxes.push_back(object_collisionbox);
351 is_unloaded.push_back(false);
352 is_step_up.push_back(false);
353 bouncy_values.push_back(0);
354 node_positions.push_back(v3s16(0,0,0));
355 is_object.push_back(true);
361 assert(cboxes.size() == is_unloaded.size()); // post-condition
362 assert(cboxes.size() == is_step_up.size()); // post-condition
363 assert(cboxes.size() == bouncy_values.size()); // post-condition
364 assert(cboxes.size() == node_positions.size()); // post-condition
365 assert(cboxes.size() == is_object.size()); // post-condition
372 Collision uncertainty radius
373 Make it a bit larger than the maximum distance of movement
375 f32 d = pos_max_d * 1.1;
376 // A fairly large value in here makes moving smoother
379 // This should always apply, otherwise there are glitches
380 assert(d > pos_max_d); // invariant
384 while(dtime > BS * 1e-10) {
385 //TimeTaker tt3("collisionMoveSimple dtime loop");
386 ScopeProfiler sp(g_profiler, "collisionMoveSimple dtime loop avg", SPT_AVG);
388 // Avoid infinite loop
390 if (loopcount >= 100) {
391 warningstream << "collisionMoveSimple: Loop count exceeded, aborting to avoid infiniite loop" << std::endl;
396 aabb3f movingbox = box_0;
397 movingbox.MinEdge += *pos_f;
398 movingbox.MaxEdge += *pos_f;
400 int nearest_collided = -1;
401 f32 nearest_dtime = dtime;
402 u32 nearest_boxindex = -1;
405 Go through every nodebox, find nearest collision
407 for (u32 boxindex = 0; boxindex < cboxes.size(); 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 // Ignore if already stepped up this nodebox.
414 if (is_step_up[boxindex]) {
415 pos_f->Y += (cboxes[boxindex].MaxEdge.Y - movingbox.MinEdge.Y);
419 if (collided == -1 || dtime_tmp >= nearest_dtime)
422 nearest_dtime = dtime_tmp;
423 nearest_collided = collided;
424 nearest_boxindex = boxindex;
427 if (nearest_collided == -1) {
428 // No collision with any collision box.
429 *pos_f += *speed_f * dtime;
430 dtime = 0; // Set to 0 to avoid "infinite" loop due to small FP numbers
432 // Otherwise, a collision occurred.
434 const aabb3f& cbox = cboxes[nearest_boxindex];
436 bool step_up = (nearest_collided != 1) && // must not be Y direction
437 (movingbox.MinEdge.Y < cbox.MaxEdge.Y) &&
438 (movingbox.MinEdge.Y + stepheight > cbox.MaxEdge.Y) &&
439 (!wouldCollideWithCeiling(cboxes, movingbox,
440 cbox.MaxEdge.Y - movingbox.MinEdge.Y,
443 // Get bounce multiplier
444 bool bouncy = (bouncy_values[nearest_boxindex] >= 1);
445 float bounce = -(float)bouncy_values[nearest_boxindex] / 100.0;
447 // Move to the point of collision and reduce dtime by nearest_dtime
448 if (nearest_dtime < 0) {
449 // 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;
459 *pos_f += *speed_f * nearest_dtime;
460 dtime -= nearest_dtime;
463 bool is_collision = true;
464 if (is_unloaded[nearest_boxindex])
465 is_collision = false;
468 if (is_object[nearest_boxindex]) {
469 info.type = COLLISION_OBJECT;
470 result.standing_on_object = true;
472 info.type = COLLISION_NODE;
475 info.node_p = node_positions[nearest_boxindex];
476 info.bouncy = bouncy;
477 info.old_speed = *speed_f;
479 // Set the speed component that caused the collision to zero
481 // Special case: Handle stairs
482 is_step_up[nearest_boxindex] = true;
483 is_collision = false;
484 } else if(nearest_collided == 0) { // X
485 if (fabs(speed_f->X) > BS * 3)
486 speed_f->X *= bounce;
489 result.collides = true;
490 result.collides_xz = true;
491 } else if(nearest_collided == 1) { // Y
492 if (fabs(speed_f->Y) > BS * 3) {
493 speed_f->Y *= bounce;
496 result.touching_ground = true;
498 result.collides = true;
499 } else if(nearest_collided == 2) { // Z
500 if (fabs(speed_f->Z) > BS * 3)
501 speed_f->Z *= bounce;
504 result.collides = true;
505 result.collides_xz = true;
508 info.new_speed = *speed_f;
509 if (info.new_speed.getDistanceFrom(info.old_speed) < 0.1 * BS)
510 is_collision = false;
513 result.collisions.push_back(info);