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