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