]> git.lizzy.rs Git - minetest.git/blob - src/collision.cpp
Fix player coordinate rounding in collisionMoveSimple() (#6197)
[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 #ifndef SERVER
26 #include "clientenvironment.h"
27 #endif
28 #include "serverenvironment.h"
29 #include "serverobject.h"
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
38 struct NearbyCollisionInfo {
39         NearbyCollisionInfo(bool is_ul, bool is_obj, int bouncy,
40                         const v3s16 &pos, const aabb3f &box) :
41                 is_unloaded(is_ul),
42                 is_object(is_obj),
43                 bouncy(bouncy),
44                 position(pos),
45                 box(box)
46         {}
47
48         bool is_unloaded;
49         bool is_step_up = false;
50         bool is_object;
51         int bouncy;
52         v3s16 position;
53         aabb3f box;
54 };
55
56
57 // Helper function:
58 // Checks for collision of a moving aabbox with a static aabbox
59 // Returns -1 if no collision, 0 if X collision, 1 if Y collision, 2 if Z collision
60 // The time after which the collision occurs is stored in dtime.
61 int axisAlignedCollision(
62                 const aabb3f &staticbox, const aabb3f &movingbox,
63                 const v3f &speed, f32 d, f32 *dtime)
64 {
65         //TimeTaker tt("axisAlignedCollision");
66
67         f32 xsize = (staticbox.MaxEdge.X - staticbox.MinEdge.X) - COLL_ZERO;     // reduce box size for solve collision stuck (flying sand)
68         f32 ysize = (staticbox.MaxEdge.Y - staticbox.MinEdge.Y); // - COLL_ZERO; // Y - no sense for falling, but maybe try later
69         f32 zsize = (staticbox.MaxEdge.Z - staticbox.MinEdge.Z) - COLL_ZERO;
70
71         aabb3f relbox(
72                         movingbox.MinEdge.X - staticbox.MinEdge.X,
73                         movingbox.MinEdge.Y - staticbox.MinEdge.Y,
74                         movingbox.MinEdge.Z - staticbox.MinEdge.Z,
75                         movingbox.MaxEdge.X - staticbox.MinEdge.X,
76                         movingbox.MaxEdge.Y - staticbox.MinEdge.Y,
77                         movingbox.MaxEdge.Z - staticbox.MinEdge.Z
78         );
79
80         if(speed.X > 0) // Check for collision with X- plane
81         {
82                 if (relbox.MaxEdge.X <= d) {
83                         *dtime = -relbox.MaxEdge.X / speed.X;
84                         if ((relbox.MinEdge.Y + speed.Y * (*dtime) < ysize) &&
85                                         (relbox.MaxEdge.Y + speed.Y * (*dtime) > COLL_ZERO) &&
86                                         (relbox.MinEdge.Z + speed.Z * (*dtime) < zsize) &&
87                                         (relbox.MaxEdge.Z + speed.Z * (*dtime) > COLL_ZERO))
88                                 return 0;
89                 }
90                 else if(relbox.MinEdge.X > xsize)
91                 {
92                         return -1;
93                 }
94         }
95         else if(speed.X < 0) // Check for collision with X+ plane
96         {
97                 if (relbox.MinEdge.X >= xsize - d) {
98                         *dtime = (xsize - relbox.MinEdge.X) / speed.X;
99                         if ((relbox.MinEdge.Y + speed.Y * (*dtime) < ysize) &&
100                                         (relbox.MaxEdge.Y + speed.Y * (*dtime) > COLL_ZERO) &&
101                                         (relbox.MinEdge.Z + speed.Z * (*dtime) < zsize) &&
102                                         (relbox.MaxEdge.Z + speed.Z * (*dtime) > COLL_ZERO))
103                                 return 0;
104                 }
105                 else if(relbox.MaxEdge.X < 0)
106                 {
107                         return -1;
108                 }
109         }
110
111         // NO else if here
112
113         if(speed.Y > 0) // Check for collision with Y- plane
114         {
115                 if (relbox.MaxEdge.Y <= d) {
116                         *dtime = -relbox.MaxEdge.Y / speed.Y;
117                         if ((relbox.MinEdge.X + speed.X * (*dtime) < xsize) &&
118                                         (relbox.MaxEdge.X + speed.X * (*dtime) > COLL_ZERO) &&
119                                         (relbox.MinEdge.Z + speed.Z * (*dtime) < zsize) &&
120                                         (relbox.MaxEdge.Z + speed.Z * (*dtime) > COLL_ZERO))
121                                 return 1;
122                 }
123                 else if(relbox.MinEdge.Y > ysize)
124                 {
125                         return -1;
126                 }
127         }
128         else if(speed.Y < 0) // Check for collision with Y+ plane
129         {
130                 if (relbox.MinEdge.Y >= ysize - d) {
131                         *dtime = (ysize - relbox.MinEdge.Y) / speed.Y;
132                         if ((relbox.MinEdge.X + speed.X * (*dtime) < xsize) &&
133                                         (relbox.MaxEdge.X + speed.X * (*dtime) > COLL_ZERO) &&
134                                         (relbox.MinEdge.Z + speed.Z * (*dtime) < zsize) &&
135                                         (relbox.MaxEdge.Z + speed.Z * (*dtime) > COLL_ZERO))
136                                 return 1;
137                 }
138                 else if(relbox.MaxEdge.Y < 0)
139                 {
140                         return -1;
141                 }
142         }
143
144         // NO else if here
145
146         if(speed.Z > 0) // Check for collision with Z- plane
147         {
148                 if (relbox.MaxEdge.Z <= d) {
149                         *dtime = -relbox.MaxEdge.Z / speed.Z;
150                         if ((relbox.MinEdge.X + speed.X * (*dtime) < xsize) &&
151                                         (relbox.MaxEdge.X + speed.X * (*dtime) > COLL_ZERO) &&
152                                         (relbox.MinEdge.Y + speed.Y * (*dtime) < ysize) &&
153                                         (relbox.MaxEdge.Y + speed.Y * (*dtime) > COLL_ZERO))
154                                 return 2;
155                 }
156                 //else if(relbox.MinEdge.Z > zsize)
157                 //{
158                 //      return -1;
159                 //}
160         }
161         else if(speed.Z < 0) // Check for collision with Z+ plane
162         {
163                 if (relbox.MinEdge.Z >= zsize - d) {
164                         *dtime = (zsize - relbox.MinEdge.Z) / speed.Z;
165                         if ((relbox.MinEdge.X + speed.X * (*dtime) < xsize) &&
166                                         (relbox.MaxEdge.X + speed.X * (*dtime) > COLL_ZERO) &&
167                                         (relbox.MinEdge.Y + speed.Y * (*dtime) < ysize) &&
168                                         (relbox.MaxEdge.Y + speed.Y * (*dtime) > COLL_ZERO))
169                                 return 2;
170                 }
171                 //else if(relbox.MaxEdge.Z < 0)
172                 //{
173                 //      return -1;
174                 //}
175         }
176
177         return -1;
178 }
179
180 // Helper function:
181 // Checks if moving the movingbox up by the given distance would hit a ceiling.
182 bool wouldCollideWithCeiling(
183                 const std::vector<NearbyCollisionInfo> &cinfo,
184                 const aabb3f &movingbox,
185                 f32 y_increase, f32 d)
186 {
187         //TimeTaker tt("wouldCollideWithCeiling");
188
189         assert(y_increase >= 0);        // pre-condition
190
191         for (std::vector<NearbyCollisionInfo>::const_iterator it = cinfo.begin();
192                         it != cinfo.end(); ++it) {
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(v3s16 p, INodeDefManager *nodedef,
207                 Map *map, MapNode n, int v, int *neighbors)
208 {
209         MapNode n2 = map->getNodeNoEx(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         //TimeTaker tt("collisionMoveSimple");
224         ScopeProfiler sp(g_profiler, "collisionMoveSimple avg", SPT_AVG);
225
226         collisionMoveResult result;
227
228         /*
229                 Calculate new velocity
230         */
231         if (dtime > 0.5) {
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.5;
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 sp(g_profiler, "collisionMoveSimple collect boxes avg", 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),
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         for(s16 x = min.X; x <= max.X; x++)
277         for(s16 y = min.Y; y <= max.Y; y++)
278         for(s16 z = min.Z; z <= max.Z; z++)
279         {
280                 v3s16 p(x,y,z);
281
282                 bool is_position_valid;
283                 MapNode n = map->getNodeNoEx(p, &is_position_valid);
284
285                 if (is_position_valid) {
286                         // Object collides into walkable nodes
287
288                         any_position_valid = true;
289                         INodeDefManager *nodedef = gamedef->getNodeDefManager();
290                         const ContentFeatures &f = nodedef->get(n);
291                         if(f.walkable == false)
292                                 continue;
293                         int n_bouncy_value = itemgroup_get(f.groups, "bouncy");
294
295                         int neighbors = 0;
296                         if (f.drawtype == NDT_NODEBOX && f.node_box.type == NODEBOX_CONNECTED) {
297                                 v3s16 p2 = p;
298
299                                 p2.Y++;
300                                 getNeighborConnectingFace(p2, nodedef, map, n, 1, &neighbors);
301
302                                 p2 = p;
303                                 p2.Y--;
304                                 getNeighborConnectingFace(p2, nodedef, map, n, 2, &neighbors);
305
306                                 p2 = p;
307                                 p2.Z--;
308                                 getNeighborConnectingFace(p2, nodedef, map, n, 4, &neighbors);
309
310                                 p2 = p;
311                                 p2.X--;
312                                 getNeighborConnectingFace(p2, nodedef, map, n, 8, &neighbors);
313
314                                 p2 = p;
315                                 p2.Z++;
316                                 getNeighborConnectingFace(p2, nodedef, map, n, 16, &neighbors);
317
318                                 p2 = p;
319                                 p2.X++;
320                                 getNeighborConnectingFace(p2, nodedef, map, n, 32, &neighbors);
321                         }
322                         std::vector<aabb3f> nodeboxes;
323                         n.getCollisionBoxes(gamedef->ndef(), &nodeboxes, neighbors);
324                         for(std::vector<aabb3f>::iterator
325                                         i = nodeboxes.begin();
326                                         i != nodeboxes.end(); ++i)
327                         {
328                                 aabb3f box = *i;
329                                 box.MinEdge += v3f(x, y, z)*BS;
330                                 box.MaxEdge += v3f(x, y, z)*BS;
331                                 cinfo.push_back(NearbyCollisionInfo(false,
332                                         false, n_bouncy_value, p, box));
333                         }
334                 } else {
335                         // Collide with unloaded nodes
336                         aabb3f box = getNodeBox(p, BS);
337                         cinfo.push_back(NearbyCollisionInfo(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         if (!any_position_valid) {
344                 *speed_f = v3f(0, 0, 0);
345                 return result;
346         }
347
348         } // tt2
349
350         if(collideWithObjects)
351         {
352                 ScopeProfiler sp(g_profiler, "collisionMoveSimple objects avg", SPT_AVG);
353                 //TimeTaker tt3("collisionMoveSimple collect object boxes");
354
355                 /* add object boxes to cinfo */
356
357                 std::vector<ActiveObject*> objects;
358 #ifndef SERVER
359                 ClientEnvironment *c_env = dynamic_cast<ClientEnvironment*>(env);
360                 if (c_env != 0) {
361                         f32 distance = speed_f->getLength();
362                         std::vector<DistanceSortedActiveObject> clientobjects;
363                         c_env->getActiveObjects(*pos_f, distance * 1.5, clientobjects);
364                         for (size_t i=0; i < clientobjects.size(); i++) {
365                                 if ((self == 0) || (self != clientobjects[i].obj)) {
366                                         objects.push_back((ActiveObject*)clientobjects[i].obj);
367                                 }
368                         }
369                 }
370                 else
371 #endif
372                 {
373                         ServerEnvironment *s_env = dynamic_cast<ServerEnvironment*>(env);
374                         if (s_env != NULL) {
375                                 f32 distance = speed_f->getLength();
376                                 std::vector<u16> s_objects;
377                                 s_env->getObjectsInsideRadius(s_objects, *pos_f, distance * 1.5);
378                                 for (std::vector<u16>::iterator iter = s_objects.begin(); iter != s_objects.end(); ++iter) {
379                                         ServerActiveObject *current = s_env->getActiveObject(*iter);
380                                         if ((self == 0) || (self != current)) {
381                                                 objects.push_back((ActiveObject*)current);
382                                         }
383                                 }
384                         }
385                 }
386
387                 for (std::vector<ActiveObject*>::const_iterator iter = objects.begin();
388                                 iter != objects.end(); ++iter) {
389                         ActiveObject *object = *iter;
390
391                         if (object != NULL) {
392                                 aabb3f object_collisionbox;
393                                 if (object->getCollisionBox(&object_collisionbox) &&
394                                                 object->collideWithObjects()) {
395                                         cinfo.push_back(NearbyCollisionInfo(false, true, 0, v3s16(), object_collisionbox));
396                                 }
397                         }
398                 }
399         } //tt3
400
401         /*
402                 Collision detection
403         */
404
405         /*
406                 Collision uncertainty radius
407                 Make it a bit larger than the maximum distance of movement
408         */
409         f32 d = pos_max_d * 1.1;
410         // A fairly large value in here makes moving smoother
411         //f32 d = 0.15*BS;
412
413         // This should always apply, otherwise there are glitches
414         assert(d > pos_max_d);  // invariant
415
416         int loopcount = 0;
417
418         while(dtime > BS * 1e-10) {
419                 //TimeTaker tt3("collisionMoveSimple dtime loop");
420                 ScopeProfiler sp(g_profiler, "collisionMoveSimple dtime loop avg", SPT_AVG);
421
422                 // Avoid infinite loop
423                 loopcount++;
424                 if (loopcount >= 100) {
425                         warningstream << "collisionMoveSimple: Loop count exceeded, aborting to avoid infiniite loop" << std::endl;
426                         break;
427                 }
428
429                 aabb3f movingbox = box_0;
430                 movingbox.MinEdge += *pos_f;
431                 movingbox.MaxEdge += *pos_f;
432
433                 int nearest_collided = -1;
434                 f32 nearest_dtime = dtime;
435                 int nearest_boxindex = -1;
436
437                 /*
438                         Go through every nodebox, find nearest collision
439                 */
440                 for (u32 boxindex = 0; boxindex < cinfo.size(); boxindex++) {
441                         NearbyCollisionInfo box_info = cinfo[boxindex];
442                         // Ignore if already stepped up this nodebox.
443                         if (box_info.is_step_up)
444                                 continue;
445
446                         // Find nearest collision of the two boxes (raytracing-like)
447                         f32 dtime_tmp;
448                         int collided = axisAlignedCollision(box_info.box,
449                                         movingbox, *speed_f, d, &dtime_tmp);
450
451                         if (collided == -1 || dtime_tmp >= nearest_dtime)
452                                 continue;
453
454                         nearest_dtime = dtime_tmp;
455                         nearest_collided = collided;
456                         nearest_boxindex = boxindex;
457                 }
458
459                 if (nearest_collided == -1) {
460                         // No collision with any collision box.
461                         *pos_f += *speed_f * dtime;
462                         dtime = 0;  // Set to 0 to avoid "infinite" loop due to small FP numbers
463                 } else {
464                         // Otherwise, a collision occurred.
465                         NearbyCollisionInfo &nearest_info = cinfo[nearest_boxindex];
466                         const aabb3f& cbox = nearest_info.box;
467                         // Check for stairs.
468                         bool step_up = (nearest_collided != 1) && // must not be Y direction
469                                         (movingbox.MinEdge.Y < cbox.MaxEdge.Y) &&
470                                         (movingbox.MinEdge.Y + stepheight > cbox.MaxEdge.Y) &&
471                                         (!wouldCollideWithCeiling(cinfo, movingbox,
472                                                         cbox.MaxEdge.Y - movingbox.MinEdge.Y,
473                                                         d));
474
475                         // Get bounce multiplier
476                         float bounce = -(float)nearest_info.bouncy / 100.0;
477
478                         // Move to the point of collision and reduce dtime by nearest_dtime
479                         if (nearest_dtime < 0) {
480                                 // Handle negative nearest_dtime (can be caused by the d allowance)
481                                 if (!step_up) {
482                                         if (nearest_collided == 0)
483                                                 pos_f->X += speed_f->X * nearest_dtime;
484                                         if (nearest_collided == 1)
485                                                 pos_f->Y += speed_f->Y * nearest_dtime;
486                                         if (nearest_collided == 2)
487                                                 pos_f->Z += speed_f->Z * nearest_dtime;
488                                 }
489                         } else {
490                                 *pos_f += *speed_f * nearest_dtime;
491                                 dtime -= nearest_dtime;
492                         }
493
494                         bool is_collision = true;
495                         if (nearest_info.is_unloaded)
496                                 is_collision = false;
497
498                         CollisionInfo info;
499                         if (nearest_info.is_object)
500                                 info.type = COLLISION_OBJECT;
501                         else
502                                 info.type = COLLISION_NODE;
503
504                         info.node_p = nearest_info.position;
505                         info.old_speed = *speed_f;
506
507                         // Set the speed component that caused the collision to zero
508                         if (step_up) {
509                                 // Special case: Handle stairs
510                                 nearest_info.is_step_up = true;
511                                 is_collision = false;
512                         } else if (nearest_collided == 0) { // X
513                                 if (fabs(speed_f->X) > BS * 3)
514                                         speed_f->X *= bounce;
515                                 else
516                                         speed_f->X = 0;
517                                 result.collides = true;
518                         } else if (nearest_collided == 1) { // Y
519                                 if(fabs(speed_f->Y) > BS * 3)
520                                         speed_f->Y *= bounce;
521                                 else
522                                         speed_f->Y = 0;
523                                 result.collides = true;
524                         } else if (nearest_collided == 2) { // Z
525                                 if (fabs(speed_f->Z) > BS * 3)
526                                         speed_f->Z *= bounce;
527                                 else
528                                         speed_f->Z = 0;
529                                 result.collides = true;
530                         }
531
532                         info.new_speed = *speed_f;
533                         if (info.new_speed.getDistanceFrom(info.old_speed) < 0.1 * BS)
534                                 is_collision = false;
535
536                         if (is_collision) {
537                                 result.collisions.push_back(info);
538                         }
539                 }
540         }
541
542         /*
543                 Final touches: Check if standing on ground, step up stairs.
544         */
545         aabb3f box = box_0;
546         box.MinEdge += *pos_f;
547         box.MaxEdge += *pos_f;
548         for (u32 boxindex = 0; boxindex < cinfo.size(); boxindex++) {
549                 NearbyCollisionInfo &box_info = cinfo[boxindex];
550                 const aabb3f &cbox = box_info.box;
551
552                 /*
553                         See if the object is touching ground.
554
555                         Object touches ground if object's minimum Y is near node's
556                         maximum Y and object's X-Z-area overlaps with the node's
557                         X-Z-area.
558
559                         Use 0.15*BS so that it is easier to get on a node.
560                 */
561                 if (cbox.MaxEdge.X - d > box.MinEdge.X && cbox.MinEdge.X + d < box.MaxEdge.X &&
562                                 cbox.MaxEdge.Z - d > box.MinEdge.Z &&
563                                 cbox.MinEdge.Z + d < box.MaxEdge.Z) {
564                         if (box_info.is_step_up) {
565                                 pos_f->Y += cbox.MaxEdge.Y - box.MinEdge.Y;
566                                 box = box_0;
567                                 box.MinEdge += *pos_f;
568                                 box.MaxEdge += *pos_f;
569                         }
570                         if (fabs(cbox.MaxEdge.Y - box.MinEdge.Y) < 0.15 * BS) {
571                                 result.touching_ground = true;
572
573                                 if (box_info.is_object)
574                                         result.standing_on_object = true;
575                         }
576                 }
577         }
578
579         return result;
580 }