Make collisionMoveSimple time overflow message written to log/show up at max once...
[oweals/minetest.git] / src / collision.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
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.
9
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.
14
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.
18 */
19
20 #include "collision.h"
21 #include "mapblock.h"
22 #include "map.h"
23 #include "nodedef.h"
24 #include "gamedef.h"
25 #include "log.h"
26 #include "environment.h"
27 #include "serverobject.h"
28 #include <vector>
29 #include <set>
30 #include "util/timetaker.h"
31 #include "profiler.h"
32
33 // float error is 10 - 9.96875 = 0.03125
34 //#define COLL_ZERO 0.032 // broken unit tests
35 #define COLL_ZERO 0
36
37 // Helper function:
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)
44 {
45         //TimeTaker tt("axisAlignedCollision");
46
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;
50
51         aabb3f relbox(
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
58         );
59
60         if(speed.X > 0) // Check for collision with X- plane
61         {
62                 if(relbox.MaxEdge.X <= d)
63                 {
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))
69                                 return 0;
70                 }
71                 else if(relbox.MinEdge.X > xsize)
72                 {
73                         return -1;
74                 }
75         }
76         else if(speed.X < 0) // Check for collision with X+ plane
77         {
78                 if(relbox.MinEdge.X >= xsize - d)
79                 {
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))
85                                 return 0;
86                 }
87                 else if(relbox.MaxEdge.X < 0)
88                 {
89                         return -1;
90                 }
91         }
92
93         // NO else if here
94
95         if(speed.Y > 0) // Check for collision with Y- plane
96         {
97                 if(relbox.MaxEdge.Y <= d)
98                 {
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))
104                                 return 1;
105                 }
106                 else if(relbox.MinEdge.Y > ysize)
107                 {
108                         return -1;
109                 }
110         }
111         else if(speed.Y < 0) // Check for collision with Y+ plane
112         {
113                 if(relbox.MinEdge.Y >= ysize - d)
114                 {
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))
120                                 return 1;
121                 }
122                 else if(relbox.MaxEdge.Y < 0)
123                 {
124                         return -1;
125                 }
126         }
127
128         // NO else if here
129
130         if(speed.Z > 0) // Check for collision with Z- plane
131         {
132                 if(relbox.MaxEdge.Z <= d)
133                 {
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))
139                                 return 2;
140                 }
141                 //else if(relbox.MinEdge.Z > zsize)
142                 //{
143                 //      return -1;
144                 //}
145         }
146         else if(speed.Z < 0) // Check for collision with Z+ plane
147         {
148                 if(relbox.MinEdge.Z >= zsize - d)
149                 {
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))
155                                 return 2;
156                 }
157                 //else if(relbox.MaxEdge.Z < 0)
158                 //{
159                 //      return -1;
160                 //}
161         }
162
163         return -1;
164 }
165
166 // Helper function:
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)
172 {
173         //TimeTaker tt("wouldCollideWithCeiling");
174
175         assert(y_increase >= 0);        // pre-condition
176
177         for(std::vector<aabb3f>::const_iterator
178                         i = staticboxes.begin();
179                         i != staticboxes.end(); ++i)
180         {
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))
188                         return true;
189         }
190
191         return false;
192 }
193
194
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,
199                 v3f &accel_f,ActiveObject* self,
200                 bool collideWithObjects)
201 {
202         static bool time_notification_done = false;
203         Map *map = &env->getMap();
204         //TimeTaker tt("collisionMoveSimple");
205         ScopeProfiler sp(g_profiler, "collisionMoveSimple avg", SPT_AVG);
206
207         collisionMoveResult result;
208
209         /*
210                 Calculate new velocity
211         */
212         if (dtime > 0.5) {
213                 if (!time_notification_done) {
214                         time_notification_done = true;
215                         infostream << "collisionMoveSimple: maximum step interval exceeded,"
216                                         " lost movement details!"<<std::endl;
217                 }
218                 dtime = 0.5;
219         } else {
220                 time_notification_done = false;
221         }
222         speed_f += accel_f * dtime;
223
224         // If there is no speed, there are no collisions
225         if(speed_f.getLength() == 0)
226                 return result;
227
228         // Limit speed for avoiding hangs
229         speed_f.Y=rangelim(speed_f.Y,-5000,5000);
230         speed_f.X=rangelim(speed_f.X,-5000,5000);
231         speed_f.Z=rangelim(speed_f.Z,-5000,5000);
232
233         /*
234                 Collect node boxes in movement range
235         */
236         std::vector<aabb3f> cboxes;
237         std::vector<bool> is_unloaded;
238         std::vector<bool> is_step_up;
239         std::vector<bool> is_object;
240         std::vector<int> bouncy_values;
241         std::vector<v3s16> node_positions;
242         {
243         //TimeTaker tt2("collisionMoveSimple collect boxes");
244     ScopeProfiler sp(g_profiler, "collisionMoveSimple collect boxes avg", SPT_AVG);
245
246         v3s16 oldpos_i = floatToInt(pos_f, BS);
247         v3s16 newpos_i = floatToInt(pos_f + speed_f * dtime, BS);
248         s16 min_x = MYMIN(oldpos_i.X, newpos_i.X) + (box_0.MinEdge.X / BS) - 1;
249         s16 min_y = MYMIN(oldpos_i.Y, newpos_i.Y) + (box_0.MinEdge.Y / BS) - 1;
250         s16 min_z = MYMIN(oldpos_i.Z, newpos_i.Z) + (box_0.MinEdge.Z / BS) - 1;
251         s16 max_x = MYMAX(oldpos_i.X, newpos_i.X) + (box_0.MaxEdge.X / BS) + 1;
252         s16 max_y = MYMAX(oldpos_i.Y, newpos_i.Y) + (box_0.MaxEdge.Y / BS) + 1;
253         s16 max_z = MYMAX(oldpos_i.Z, newpos_i.Z) + (box_0.MaxEdge.Z / BS) + 1;
254
255         bool any_position_valid = false;
256
257         for(s16 x = min_x; x <= max_x; x++)
258         for(s16 y = min_y; y <= max_y; y++)
259         for(s16 z = min_z; z <= max_z; z++)
260         {
261                 v3s16 p(x,y,z);
262
263                 bool is_position_valid;
264                 MapNode n = map->getNodeNoEx(p, &is_position_valid);
265
266                 if (is_position_valid) {
267                         // Object collides into walkable nodes
268
269                         any_position_valid = true;
270                         const ContentFeatures &f = gamedef->getNodeDefManager()->get(n);
271                         if(f.walkable == false)
272                                 continue;
273                         int n_bouncy_value = itemgroup_get(f.groups, "bouncy");
274
275                         std::vector<aabb3f> nodeboxes = n.getCollisionBoxes(gamedef->ndef());
276                         for(std::vector<aabb3f>::iterator
277                                         i = nodeboxes.begin();
278                                         i != nodeboxes.end(); ++i)
279                         {
280                                 aabb3f box = *i;
281                                 box.MinEdge += v3f(x, y, z)*BS;
282                                 box.MaxEdge += v3f(x, y, z)*BS;
283                                 cboxes.push_back(box);
284                                 is_unloaded.push_back(false);
285                                 is_step_up.push_back(false);
286                                 bouncy_values.push_back(n_bouncy_value);
287                                 node_positions.push_back(p);
288                                 is_object.push_back(false);
289                         }
290                 }
291                 else {
292                         // Collide with unloaded nodes
293                         aabb3f box = getNodeBox(p, BS);
294                         cboxes.push_back(box);
295                         is_unloaded.push_back(true);
296                         is_step_up.push_back(false);
297                         bouncy_values.push_back(0);
298                         node_positions.push_back(p);
299                         is_object.push_back(false);
300                 }
301         }
302
303         // Do not move if world has not loaded yet, since custom node boxes
304         // are not available for collision detection.
305         if (!any_position_valid)
306                 return result;
307
308         } // tt2
309
310         if(collideWithObjects)
311         {
312                 ScopeProfiler sp(g_profiler, "collisionMoveSimple objects avg", SPT_AVG);
313                 //TimeTaker tt3("collisionMoveSimple collect object boxes");
314
315                 /* add object boxes to cboxes */
316
317                 std::vector<ActiveObject*> objects;
318 #ifndef SERVER
319                 ClientEnvironment *c_env = dynamic_cast<ClientEnvironment*>(env);
320                 if (c_env != 0) {
321                         f32 distance = speed_f.getLength();
322                         std::vector<DistanceSortedActiveObject> clientobjects;
323                         c_env->getActiveObjects(pos_f,distance * 1.5,clientobjects);
324                         for (size_t i=0; i < clientobjects.size(); i++) {
325                                 if ((self == 0) || (self != clientobjects[i].obj)) {
326                                         objects.push_back((ActiveObject*)clientobjects[i].obj);
327                                 }
328                         }
329                 }
330                 else
331 #endif
332                 {
333                         ServerEnvironment *s_env = dynamic_cast<ServerEnvironment*>(env);
334                         if (s_env != 0) {
335                                 f32 distance = speed_f.getLength();
336                                 std::vector<u16> s_objects;
337                                 s_env->getObjectsInsideRadius(s_objects, pos_f, distance * 1.5);
338                                 for (std::vector<u16>::iterator iter = s_objects.begin(); iter != s_objects.end(); ++iter) {
339                                         ServerActiveObject *current = s_env->getActiveObject(*iter);
340                                         if ((self == 0) || (self != current)) {
341                                                 objects.push_back((ActiveObject*)current);
342                                         }
343                                 }
344                         }
345                 }
346
347                 for (std::vector<ActiveObject*>::const_iterator iter = objects.begin();
348                                 iter != objects.end(); ++iter) {
349                         ActiveObject *object = *iter;
350
351                         if (object != NULL) {
352                                 aabb3f object_collisionbox;
353                                 if (object->getCollisionBox(&object_collisionbox) &&
354                                                 object->collideWithObjects()) {
355                                         cboxes.push_back(object_collisionbox);
356                                         is_unloaded.push_back(false);
357                                         is_step_up.push_back(false);
358                                         bouncy_values.push_back(0);
359                                         node_positions.push_back(v3s16(0,0,0));
360                                         is_object.push_back(true);
361                                 }
362                         }
363                 }
364         } //tt3
365
366         assert(cboxes.size() == is_unloaded.size());    // post-condition
367         assert(cboxes.size() == is_step_up.size());     // post-condition
368         assert(cboxes.size() == bouncy_values.size());  // post-condition
369         assert(cboxes.size() == node_positions.size()); // post-condition
370         assert(cboxes.size() == is_object.size());      // post-condition
371
372         /*
373                 Collision detection
374         */
375
376         /*
377                 Collision uncertainty radius
378                 Make it a bit larger than the maximum distance of movement
379         */
380         f32 d = pos_max_d * 1.1;
381         // A fairly large value in here makes moving smoother
382         //f32 d = 0.15*BS;
383
384         // This should always apply, otherwise there are glitches
385         assert(d > pos_max_d);  // invariant
386
387         int loopcount = 0;
388
389         while(dtime > BS * 1e-10) {
390                 //TimeTaker tt3("collisionMoveSimple dtime loop");
391         ScopeProfiler sp(g_profiler, "collisionMoveSimple dtime loop avg", SPT_AVG);
392
393                 // Avoid infinite loop
394                 loopcount++;
395                 if (loopcount >= 100) {
396                         warningstream << "collisionMoveSimple: Loop count exceeded, aborting to avoid infiniite loop" << std::endl;
397                         dtime = 0;
398                         break;
399                 }
400
401                 aabb3f movingbox = box_0;
402                 movingbox.MinEdge += pos_f;
403                 movingbox.MaxEdge += pos_f;
404
405                 int nearest_collided = -1;
406                 f32 nearest_dtime = dtime;
407                 u32 nearest_boxindex = -1;
408
409                 /*
410                         Go through every nodebox, find nearest collision
411                 */
412                 for (u32 boxindex = 0; boxindex < cboxes.size(); boxindex++) {
413                         // Ignore if already stepped up this nodebox.
414                         if(is_step_up[boxindex])
415                                 continue;
416
417                         // Find nearest collision of the two boxes (raytracing-like)
418                         f32 dtime_tmp;
419                         int collided = axisAlignedCollision(
420                                         cboxes[boxindex], movingbox, speed_f, d, dtime_tmp);
421
422                         if (collided == -1 || dtime_tmp >= nearest_dtime)
423                                 continue;
424
425                         nearest_dtime = dtime_tmp;
426                         nearest_collided = collided;
427                         nearest_boxindex = boxindex;
428                 }
429
430                 if (nearest_collided == -1) {
431                         // No collision with any collision box.
432                         pos_f += speed_f * dtime;
433                         dtime = 0;  // Set to 0 to avoid "infinite" loop due to small FP numbers
434                 } else {
435                         // Otherwise, a collision occurred.
436
437                         const aabb3f& cbox = cboxes[nearest_boxindex];
438                         // Check for stairs.
439                         bool step_up = (nearest_collided != 1) && // must not be Y direction
440                                         (movingbox.MinEdge.Y < cbox.MaxEdge.Y) &&
441                                         (movingbox.MinEdge.Y + stepheight > cbox.MaxEdge.Y) &&
442                                         (!wouldCollideWithCeiling(cboxes, movingbox,
443                                                         cbox.MaxEdge.Y - movingbox.MinEdge.Y,
444                                                         d));
445
446                         // Get bounce multiplier
447                         bool bouncy = (bouncy_values[nearest_boxindex] >= 1);
448                         float bounce = -(float)bouncy_values[nearest_boxindex] / 100.0;
449
450                         // Move to the point of collision and reduce dtime by nearest_dtime
451                         if (nearest_dtime < 0) {
452                                 // Handle negative nearest_dtime (can be caused by the d allowance)
453                                 if (!step_up) {
454                                         if (nearest_collided == 0)
455                                                 pos_f.X += speed_f.X * nearest_dtime;
456                                         if (nearest_collided == 1)
457                                                 pos_f.Y += speed_f.Y * nearest_dtime;
458                                         if (nearest_collided == 2)
459                                                 pos_f.Z += speed_f.Z * nearest_dtime;
460                                 }
461                         } else {
462                                 pos_f += speed_f * nearest_dtime;
463                                 dtime -= nearest_dtime;
464                         }
465
466                         bool is_collision = true;
467                         if (is_unloaded[nearest_boxindex])
468                                 is_collision = false;
469
470                         CollisionInfo info;
471                         if (is_object[nearest_boxindex])
472                                 info.type = COLLISION_OBJECT;
473                         else
474                                 info.type = COLLISION_NODE;
475
476                         info.node_p = node_positions[nearest_boxindex];
477                         info.bouncy = bouncy;
478                         info.old_speed = speed_f;
479
480                         // Set the speed component that caused the collision to zero
481                         if (step_up) {
482                                 // Special case: Handle stairs
483                                 is_step_up[nearest_boxindex] = true;
484                                 is_collision = false;
485                         } else if(nearest_collided == 0) { // X
486                                 if (fabs(speed_f.X) > BS * 3)
487                                         speed_f.X *= bounce;
488                                 else
489                                         speed_f.X = 0;
490                                 result.collides = true;
491                                 result.collides_xz = true;
492                         }
493                         else if(nearest_collided == 1) { // Y
494                                 if(fabs(speed_f.Y) > BS * 3)
495                                         speed_f.Y *= bounce;
496                                 else
497                                         speed_f.Y = 0;
498                                 result.collides = true;
499                         } else if(nearest_collided == 2) { // Z
500                                 if (fabs(speed_f.Z) > BS * 3)
501                                         speed_f.Z *= bounce;
502                                 else
503                                         speed_f.Z = 0;
504                                 result.collides = true;
505                                 result.collides_xz = true;
506                         }
507
508                         info.new_speed = speed_f;
509                         if (info.new_speed.getDistanceFrom(info.old_speed) < 0.1 * BS)
510                                 is_collision = false;
511
512                         if (is_collision) {
513                                 result.collisions.push_back(info);
514                         }
515                 }
516         }
517
518         /*
519                 Final touches: Check if standing on ground, step up stairs.
520         */
521         aabb3f box = box_0;
522         box.MinEdge += pos_f;
523         box.MaxEdge += pos_f;
524         for (u32 boxindex = 0; boxindex < cboxes.size(); boxindex++) {
525                 const aabb3f& cbox = cboxes[boxindex];
526
527                 /*
528                         See if the object is touching ground.
529
530                         Object touches ground if object's minimum Y is near node's
531                         maximum Y and object's X-Z-area overlaps with the node's
532                         X-Z-area.
533
534                         Use 0.15*BS so that it is easier to get on a node.
535                 */
536                 if (cbox.MaxEdge.X - d > box.MinEdge.X && cbox.MinEdge.X + d < box.MaxEdge.X &&
537                                 cbox.MaxEdge.Z - d > box.MinEdge.Z &&
538                                 cbox.MinEdge.Z + d < box.MaxEdge.Z) {
539                         if (is_step_up[boxindex]) {
540                                 pos_f.Y += (cbox.MaxEdge.Y - box.MinEdge.Y);
541                                 box = box_0;
542                                 box.MinEdge += pos_f;
543                                 box.MaxEdge += pos_f;
544                         }
545                         if (fabs(cbox.MaxEdge.Y - box.MinEdge.Y) < 0.15 * BS) {
546                                 result.touching_ground = true;
547
548                                 if (is_object[boxindex])
549                                         result.standing_on_object = true;
550                                 if (is_unloaded[boxindex])
551                                         result.standing_on_unloaded = true;
552                         }
553                 }
554         }
555
556         return result;
557 }