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