Collision detection tweak #2 (#9365)
[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 <cmath>
22 #include "mapblock.h"
23 #include "map.h"
24 #include "nodedef.h"
25 #include "gamedef.h"
26 #ifndef SERVER
27 #include "client/clientenvironment.h"
28 #endif
29 #include "serverenvironment.h"
30 #include "serverobject.h"
31 #include "util/timetaker.h"
32 #include "profiler.h"
33
34 // float error is 10 - 9.96875 = 0.03125
35 //#define COLL_ZERO 0.032 // broken unit tests
36 #define COLL_ZERO 0
37
38
39 struct NearbyCollisionInfo {
40         NearbyCollisionInfo(bool is_ul, bool is_obj, int bouncy,
41                         const v3s16 &pos, const aabb3f &box) :
42                 is_unloaded(is_ul),
43                 is_object(is_obj),
44                 bouncy(bouncy),
45                 position(pos),
46                 box(box)
47         {}
48
49         bool is_unloaded;
50         bool is_step_up = false;
51         bool is_object;
52         int bouncy;
53         v3s16 position;
54         aabb3f box;
55 };
56
57
58 // Helper function:
59 // Checks for collision of a moving aabbox with a static aabbox
60 // Returns -1 if no collision, 0 if X collision, 1 if Y collision, 2 if Z collision
61 // The time after which the collision occurs is stored in dtime.
62 CollisionAxis axisAlignedCollision(
63                 const aabb3f &staticbox, const aabb3f &movingbox,
64                 const v3f &speed, f32 d, f32 *dtime)
65 {
66         //TimeTaker tt("axisAlignedCollision");
67
68         f32 xsize = (staticbox.MaxEdge.X - staticbox.MinEdge.X) - COLL_ZERO;     // reduce box size for solve collision stuck (flying sand)
69         f32 ysize = (staticbox.MaxEdge.Y - staticbox.MinEdge.Y); // - COLL_ZERO; // Y - no sense for falling, but maybe try later
70         f32 zsize = (staticbox.MaxEdge.Z - staticbox.MinEdge.Z) - COLL_ZERO;
71
72         aabb3f relbox(
73                         movingbox.MinEdge.X - staticbox.MinEdge.X,
74                         movingbox.MinEdge.Y - staticbox.MinEdge.Y,
75                         movingbox.MinEdge.Z - staticbox.MinEdge.Z,
76                         movingbox.MaxEdge.X - staticbox.MinEdge.X,
77                         movingbox.MaxEdge.Y - staticbox.MinEdge.Y,
78                         movingbox.MaxEdge.Z - staticbox.MinEdge.Z
79         );
80
81         if(speed.X > 0) // Check for collision with X- plane
82         {
83                 if (relbox.MaxEdge.X <= d) {
84                         *dtime = -relbox.MaxEdge.X / speed.X;
85                         if ((relbox.MinEdge.Y + speed.Y * (*dtime) < ysize) &&
86                                         (relbox.MaxEdge.Y + speed.Y * (*dtime) > COLL_ZERO) &&
87                                         (relbox.MinEdge.Z + speed.Z * (*dtime) < zsize) &&
88                                         (relbox.MaxEdge.Z + speed.Z * (*dtime) > COLL_ZERO))
89                                 return COLLISION_AXIS_X;
90                 }
91                 else if(relbox.MinEdge.X > xsize)
92                 {
93                         return COLLISION_AXIS_NONE;
94                 }
95         }
96         else if(speed.X < 0) // Check for collision with X+ plane
97         {
98                 if (relbox.MinEdge.X >= xsize - d) {
99                         *dtime = (xsize - relbox.MinEdge.X) / speed.X;
100                         if ((relbox.MinEdge.Y + speed.Y * (*dtime) < ysize) &&
101                                         (relbox.MaxEdge.Y + speed.Y * (*dtime) > COLL_ZERO) &&
102                                         (relbox.MinEdge.Z + speed.Z * (*dtime) < zsize) &&
103                                         (relbox.MaxEdge.Z + speed.Z * (*dtime) > COLL_ZERO))
104                                 return COLLISION_AXIS_X;
105                 }
106                 else if(relbox.MaxEdge.X < 0)
107                 {
108                         return COLLISION_AXIS_NONE;
109                 }
110         }
111
112         // NO else if here
113
114         if(speed.Y > 0) // Check for collision with Y- plane
115         {
116                 if (relbox.MaxEdge.Y <= d) {
117                         *dtime = -relbox.MaxEdge.Y / speed.Y;
118                         if ((relbox.MinEdge.X + speed.X * (*dtime) < xsize) &&
119                                         (relbox.MaxEdge.X + speed.X * (*dtime) > COLL_ZERO) &&
120                                         (relbox.MinEdge.Z + speed.Z * (*dtime) < zsize) &&
121                                         (relbox.MaxEdge.Z + speed.Z * (*dtime) > COLL_ZERO))
122                                 return COLLISION_AXIS_Y;
123                 }
124                 else if(relbox.MinEdge.Y > ysize)
125                 {
126                         return COLLISION_AXIS_NONE;
127                 }
128         }
129         else if(speed.Y < 0) // Check for collision with Y+ plane
130         {
131                 if (relbox.MinEdge.Y >= ysize - d) {
132                         *dtime = (ysize - relbox.MinEdge.Y) / speed.Y;
133                         if ((relbox.MinEdge.X + speed.X * (*dtime) < xsize) &&
134                                         (relbox.MaxEdge.X + speed.X * (*dtime) > COLL_ZERO) &&
135                                         (relbox.MinEdge.Z + speed.Z * (*dtime) < zsize) &&
136                                         (relbox.MaxEdge.Z + speed.Z * (*dtime) > COLL_ZERO))
137                                 return COLLISION_AXIS_Y;
138                 }
139                 else if(relbox.MaxEdge.Y < 0)
140                 {
141                         return COLLISION_AXIS_NONE;
142                 }
143         }
144
145         // NO else if here
146
147         if(speed.Z > 0) // Check for collision with Z- plane
148         {
149                 if (relbox.MaxEdge.Z <= d) {
150                         *dtime = -relbox.MaxEdge.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 COLLISION_AXIS_Z;
156                 }
157                 //else if(relbox.MinEdge.Z > zsize)
158                 //{
159                 //      return COLLISION_AXIS_NONE;
160                 //}
161         }
162         else if(speed.Z < 0) // Check for collision with Z+ plane
163         {
164                 if (relbox.MinEdge.Z >= zsize - d) {
165                         *dtime = (zsize - relbox.MinEdge.Z) / speed.Z;
166                         if ((relbox.MinEdge.X + speed.X * (*dtime) < xsize) &&
167                                         (relbox.MaxEdge.X + speed.X * (*dtime) > COLL_ZERO) &&
168                                         (relbox.MinEdge.Y + speed.Y * (*dtime) < ysize) &&
169                                         (relbox.MaxEdge.Y + speed.Y * (*dtime) > COLL_ZERO))
170                                 return COLLISION_AXIS_Z;
171                 }
172                 //else if(relbox.MaxEdge.Z < 0)
173                 //{
174                 //      return COLLISION_AXIS_NONE;
175                 //}
176         }
177
178         return COLLISION_AXIS_NONE;
179 }
180
181 // Helper function:
182 // Checks if moving the movingbox up by the given distance would hit a ceiling.
183 bool wouldCollideWithCeiling(
184                 const std::vector<NearbyCollisionInfo> &cinfo,
185                 const aabb3f &movingbox,
186                 f32 y_increase, f32 d)
187 {
188         //TimeTaker tt("wouldCollideWithCeiling");
189
190         assert(y_increase >= 0);        // pre-condition
191
192         for (const auto &it : cinfo) {
193                 const aabb3f &staticbox = it.box;
194                 if ((movingbox.MaxEdge.Y - d <= staticbox.MinEdge.Y) &&
195                                 (movingbox.MaxEdge.Y + y_increase > staticbox.MinEdge.Y) &&
196                                 (movingbox.MinEdge.X < staticbox.MaxEdge.X) &&
197                                 (movingbox.MaxEdge.X > staticbox.MinEdge.X) &&
198                                 (movingbox.MinEdge.Z < staticbox.MaxEdge.Z) &&
199                                 (movingbox.MaxEdge.Z > staticbox.MinEdge.Z))
200                         return true;
201         }
202
203         return false;
204 }
205
206 static inline void getNeighborConnectingFace(const v3s16 &p,
207         const NodeDefManager *nodedef, Map *map, MapNode n, int v, int *neighbors)
208 {
209         MapNode n2 = map->getNode(p);
210         if (nodedef->nodeboxConnects(n, n2, v))
211                 *neighbors |= v;
212 }
213
214 collisionMoveResult collisionMoveSimple(Environment *env, IGameDef *gamedef,
215                 f32 pos_max_d, const aabb3f &box_0,
216                 f32 stepheight, f32 dtime,
217                 v3f *pos_f, v3f *speed_f,
218                 v3f accel_f, ActiveObject *self,
219                 bool collideWithObjects)
220 {
221         static bool time_notification_done = false;
222         Map *map = &env->getMap();
223
224         ScopeProfiler sp(g_profiler, "collisionMoveSimple()", SPT_AVG);
225
226         collisionMoveResult result;
227
228         /*
229                 Calculate new velocity
230         */
231         if (dtime > 0.5f) {
232                 if (!time_notification_done) {
233                         time_notification_done = true;
234                         infostream << "collisionMoveSimple: maximum step interval exceeded,"
235                                         " lost movement details!"<<std::endl;
236                 }
237                 dtime = 0.5f;
238         } else {
239                 time_notification_done = false;
240         }
241         *speed_f += accel_f * dtime;
242
243         // If there is no speed, there are no collisions
244         if (speed_f->getLength() == 0)
245                 return result;
246
247         // Limit speed for avoiding hangs
248         speed_f->Y = rangelim(speed_f->Y, -5000, 5000);
249         speed_f->X = rangelim(speed_f->X, -5000, 5000);
250         speed_f->Z = rangelim(speed_f->Z, -5000, 5000);
251
252         /*
253                 Collect node boxes in movement range
254         */
255         std::vector<NearbyCollisionInfo> cinfo;
256         {
257         //TimeTaker tt2("collisionMoveSimple collect boxes");
258         ScopeProfiler sp2(g_profiler, "collisionMoveSimple(): collect boxes", SPT_AVG);
259
260         v3f newpos_f = *pos_f + *speed_f * dtime;
261         v3f minpos_f(
262                 MYMIN(pos_f->X, newpos_f.X),
263                 MYMIN(pos_f->Y, newpos_f.Y) + 0.01f * BS, // bias rounding, player often at +/-n.5
264                 MYMIN(pos_f->Z, newpos_f.Z)
265         );
266         v3f maxpos_f(
267                 MYMAX(pos_f->X, newpos_f.X),
268                 MYMAX(pos_f->Y, newpos_f.Y),
269                 MYMAX(pos_f->Z, newpos_f.Z)
270         );
271         v3s16 min = floatToInt(minpos_f + box_0.MinEdge, BS) - v3s16(1, 1, 1);
272         v3s16 max = floatToInt(maxpos_f + box_0.MaxEdge, BS) + v3s16(1, 1, 1);
273
274         bool any_position_valid = false;
275
276         v3s16 p;
277         for (p.X = min.X; p.X <= max.X; p.X++)
278         for (p.Y = min.Y; p.Y <= max.Y; p.Y++)
279         for (p.Z = min.Z; p.Z <= max.Z; p.Z++) {
280                 bool is_position_valid;
281                 MapNode n = map->getNode(p, &is_position_valid);
282
283                 if (is_position_valid && n.getContent() != CONTENT_IGNORE) {
284                         // Object collides into walkable nodes
285
286                         any_position_valid = true;
287                         const NodeDefManager *nodedef = gamedef->getNodeDefManager();
288                         const ContentFeatures &f = nodedef->get(n);
289
290                         if (!f.walkable)
291                                 continue;
292
293                         int n_bouncy_value = itemgroup_get(f.groups, "bouncy");
294
295                         int neighbors = 0;
296                         if (f.drawtype == NDT_NODEBOX &&
297                                 f.node_box.type == NODEBOX_CONNECTED) {
298                                 v3s16 p2 = p;
299
300                                 p2.Y++;
301                                 getNeighborConnectingFace(p2, nodedef, map, n, 1, &neighbors);
302
303                                 p2 = p;
304                                 p2.Y--;
305                                 getNeighborConnectingFace(p2, nodedef, map, n, 2, &neighbors);
306
307                                 p2 = p;
308                                 p2.Z--;
309                                 getNeighborConnectingFace(p2, nodedef, map, n, 4, &neighbors);
310
311                                 p2 = p;
312                                 p2.X--;
313                                 getNeighborConnectingFace(p2, nodedef, map, n, 8, &neighbors);
314
315                                 p2 = p;
316                                 p2.Z++;
317                                 getNeighborConnectingFace(p2, nodedef, map, n, 16, &neighbors);
318
319                                 p2 = p;
320                                 p2.X++;
321                                 getNeighborConnectingFace(p2, nodedef, map, n, 32, &neighbors);
322                         }
323                         std::vector<aabb3f> nodeboxes;
324                         n.getCollisionBoxes(gamedef->ndef(), &nodeboxes, neighbors);
325
326                         // Calculate float position only once
327                         v3f posf = intToFloat(p, BS);
328                         for (auto box : nodeboxes) {
329                                 box.MinEdge += posf;
330                                 box.MaxEdge += posf;
331                                 cinfo.emplace_back(false, false, n_bouncy_value, p, box);
332                         }
333                 } else {
334                         // Collide with unloaded nodes (position invalid) and loaded
335                         // CONTENT_IGNORE nodes (position valid)
336                         aabb3f box = getNodeBox(p, BS);
337                         cinfo.emplace_back(true, false, 0, p, box);
338                 }
339         }
340
341         // Do not move if world has not loaded yet, since custom node boxes
342         // are not available for collision detection.
343         // This also intentionally occurs in the case of the object being positioned
344         // solely on loaded CONTENT_IGNORE nodes, no matter where they come from.
345         if (!any_position_valid) {
346                 *speed_f = v3f(0, 0, 0);
347                 return result;
348         }
349
350         } // tt2
351
352         if(collideWithObjects)
353         {
354                 /* add object boxes to cinfo */
355
356                 std::vector<ActiveObject*> objects;
357 #ifndef SERVER
358                 ClientEnvironment *c_env = dynamic_cast<ClientEnvironment*>(env);
359                 if (c_env != 0) {
360                         // Calculate distance by speed, add own extent and 1.5m of tolerance
361                         f32 distance = speed_f->getLength() * dtime +
362                                 box_0.getExtent().getLength() + 1.5f * BS;
363                         std::vector<DistanceSortedActiveObject> clientobjects;
364                         c_env->getActiveObjects(*pos_f, distance, clientobjects);
365
366                         for (auto &clientobject : clientobjects) {
367                                 // Do collide with everything but itself and the parent CAO
368                                 if (!self || (self != clientobject.obj &&
369                                                 self != clientobject.obj->getParent())) {
370                                         objects.push_back((ActiveObject*) clientobject.obj);
371                                 }
372                         }
373                 }
374                 else
375 #endif
376                 {
377                         ServerEnvironment *s_env = dynamic_cast<ServerEnvironment*>(env);
378                         if (s_env != NULL) {
379                                 // Calculate distance by speed, add own extent and 1.5m of tolerance
380                                 f32 distance = speed_f->getLength() * dtime +
381                                         box_0.getExtent().getLength() + 1.5f * BS;
382                                 std::vector<u16> s_objects;
383                                 s_env->getObjectsInsideRadius(s_objects, *pos_f, distance);
384
385                                 for (u16 obj_id : s_objects) {
386                                         ServerActiveObject *current = s_env->getActiveObject(obj_id);
387
388                                         if (!self || (self != current &&
389                                                         self != current->getParent())) {
390                                                 objects.push_back((ActiveObject*)current);
391                                         }
392                                 }
393                         }
394                 }
395
396                 for (std::vector<ActiveObject*>::const_iterator iter = objects.begin();
397                                 iter != objects.end(); ++iter) {
398                         ActiveObject *object = *iter;
399
400                         if (object) {
401                                 aabb3f object_collisionbox;
402                                 if (object->getCollisionBox(&object_collisionbox) &&
403                                                 object->collideWithObjects()) {
404                                         cinfo.emplace_back(false, true, 0, v3s16(), object_collisionbox);
405                                 }
406                         }
407                 }
408         } //tt3
409
410         /*
411                 Collision detection
412         */
413
414         /*
415                 Collision uncertainty radius
416                 Make it a bit larger than the maximum distance of movement
417         */
418         //f32 d = pos_max_d * 1.1f;
419
420
421         f32 d = 0.3f;   // Temporary fix, any nonzero d causes collision glitches, the more the greater it is.
422         // ultimately it has to be determined if any uncertainty is involved, and if it is, eliminated
423         // and d & pos_max_d params removed from function calls.
424
425         int loopcount = 0;
426
427         while(dtime > BS * 1e-10f) {
428                 // Avoid infinite loop
429                 loopcount++;
430                 if (loopcount >= 100) {
431                         warningstream << "collisionMoveSimple: Loop count exceeded, aborting to avoid infiniite loop" << std::endl;
432                         break;
433                 }
434
435                 aabb3f movingbox = box_0;
436                 movingbox.MinEdge += *pos_f;
437                 movingbox.MaxEdge += *pos_f;
438
439                 CollisionAxis nearest_collided = COLLISION_AXIS_NONE;
440                 f32 nearest_dtime = dtime;
441                 int nearest_boxindex = -1;
442
443                 /*
444                         Go through every nodebox, find nearest collision
445                 */
446                 for (u32 boxindex = 0; boxindex < cinfo.size(); boxindex++) {
447                         const NearbyCollisionInfo &box_info = cinfo[boxindex];
448                         // Ignore if already stepped up this nodebox.
449                         if (box_info.is_step_up)
450                                 continue;
451
452                         // Find nearest collision of the two boxes (raytracing-like)
453                         f32 dtime_tmp;
454                         CollisionAxis collided = axisAlignedCollision(box_info.box,
455                                         movingbox, *speed_f, d, &dtime_tmp);
456
457                         if (collided == -1 || dtime_tmp >= nearest_dtime)
458                                 continue;
459
460                         nearest_dtime = dtime_tmp;
461                         nearest_collided = collided;
462                         nearest_boxindex = boxindex;
463                 }
464
465                 if (nearest_collided == COLLISION_AXIS_NONE) {
466                         // No collision with any collision box.
467                         *pos_f += *speed_f * dtime;
468                         dtime = 0;  // Set to 0 to avoid "infinite" loop due to small FP numbers
469                 } else {
470                         // Otherwise, a collision occurred.
471                         NearbyCollisionInfo &nearest_info = cinfo[nearest_boxindex];
472                         const aabb3f& cbox = nearest_info.box;
473                         // Check for stairs.
474                         bool step_up = (nearest_collided != COLLISION_AXIS_Y) && // must not be Y direction
475                                         (movingbox.MinEdge.Y < cbox.MaxEdge.Y) &&
476                                         (movingbox.MinEdge.Y + stepheight > cbox.MaxEdge.Y) &&
477                                         (!wouldCollideWithCeiling(cinfo, movingbox,
478                                                         cbox.MaxEdge.Y - movingbox.MinEdge.Y,
479                                                         d));
480
481                         // Get bounce multiplier
482                         float bounce = -(float)nearest_info.bouncy / 100.0f;
483
484                         // Move to the point of collision and reduce dtime by nearest_dtime
485                         if (nearest_dtime < 0) {
486                                 // Handle negative nearest_dtime (can be caused by the d allowance)
487                                 if (!step_up) {
488                                         if (nearest_collided == COLLISION_AXIS_X)
489                                                 pos_f->X += speed_f->X * nearest_dtime;
490                                         if (nearest_collided == COLLISION_AXIS_Y)
491                                                 pos_f->Y += speed_f->Y * nearest_dtime;
492                                         if (nearest_collided == COLLISION_AXIS_Z)
493                                                 pos_f->Z += speed_f->Z * nearest_dtime;
494                                 }
495                         } else {
496                                 *pos_f += *speed_f * nearest_dtime;
497                                 dtime -= nearest_dtime;
498                         }
499
500                         bool is_collision = true;
501                         if (nearest_info.is_unloaded)
502                                 is_collision = false;
503
504                         CollisionInfo info;
505                         if (nearest_info.is_object)
506                                 info.type = COLLISION_OBJECT;
507                         else
508                                 info.type = COLLISION_NODE;
509
510                         info.node_p = nearest_info.position;
511                         info.old_speed = *speed_f;
512                         info.plane = nearest_collided;
513
514                         // Set the speed component that caused the collision to zero
515                         if (step_up) {
516                                 // Special case: Handle stairs
517                                 nearest_info.is_step_up = true;
518                                 is_collision = false;
519                         } else if (nearest_collided == COLLISION_AXIS_X) {
520                                 if (fabs(speed_f->X) > BS * 3)
521                                         speed_f->X *= bounce;
522                                 else
523                                         speed_f->X = 0;
524                                 result.collides = true;
525                         } else if (nearest_collided == COLLISION_AXIS_Y) {
526                                 if(fabs(speed_f->Y) > BS * 3)
527                                         speed_f->Y *= bounce;
528                                 else
529                                         speed_f->Y = 0;
530                                 result.collides = true;
531                         } else if (nearest_collided == COLLISION_AXIS_Z) {
532                                 if (fabs(speed_f->Z) > BS * 3)
533                                         speed_f->Z *= bounce;
534                                 else
535                                         speed_f->Z = 0;
536                                 result.collides = true;
537                         }
538
539                         info.new_speed = *speed_f;
540                         if (info.new_speed.getDistanceFrom(info.old_speed) < 0.1f * BS)
541                                 is_collision = false;
542
543                         if (is_collision) {
544                                 info.axis = nearest_collided;
545                                 result.collisions.push_back(info);
546                         }
547                 }
548         }
549
550         /*
551                 Final touches: Check if standing on ground, step up stairs.
552         */
553         aabb3f box = box_0;
554         box.MinEdge += *pos_f;
555         box.MaxEdge += *pos_f;
556         for (const auto &box_info : cinfo) {
557                 const aabb3f &cbox = box_info.box;
558
559                 /*
560                         See if the object is touching ground.
561
562                         Object touches ground if object's minimum Y is near node's
563                         maximum Y and object's X-Z-area overlaps with the node's
564                         X-Z-area.
565
566                         Use 0.15*BS so that it is easier to get on a node.
567                 */
568                 if (cbox.MaxEdge.X - d > box.MinEdge.X && cbox.MinEdge.X + d < box.MaxEdge.X &&
569                                 cbox.MaxEdge.Z - d > box.MinEdge.Z &&
570                                 cbox.MinEdge.Z + d < box.MaxEdge.Z) {
571                         if (box_info.is_step_up) {
572                                 pos_f->Y += cbox.MaxEdge.Y - box.MinEdge.Y;
573                                 box = box_0;
574                                 box.MinEdge += *pos_f;
575                                 box.MaxEdge += *pos_f;
576                         }
577                         if (std::fabs(cbox.MaxEdge.Y - box.MinEdge.Y) < 0.15f * BS) {
578                                 result.touching_ground = true;
579
580                                 if (box_info.is_object)
581                                         result.standing_on_object = true;
582                         }
583                 }
584         }
585
586         return result;
587 }