1 /*
2 collision.cpp
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4 */
5
6 /*
7 This file is part of Freeminer.
8
9 Freeminer is free software: you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation, either version 3 of the License, or
12 (at your option) any later version.
13
14 Freeminer is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with Freeminer. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 #include "collision.h"
24 #include "mapblock.h"
25 #include "map.h"
26 #include "nodedef.h"
27 #include "gamedef.h"
28 #include "log.h"
29 #include "environment.h"
30 #include "serverobject.h"
31 #include <vector>
32 #include <set>
33 #include "util/timetaker.h"
34 #include "main.h" // g_profiler
35 #include "profiler.h"
36
37 // float error is 10 - 9.96875 = 0.03125 // default with bug = 0
38 #define COLL_ZERO 0.032 // broken unit tests
39 #define COLL_ZEROY 0.032 //0.032 // Y only
40
41 // Helper function:
42 // Checks for collision of a moving aabbox with a static aabbox
43 // Returns -1 if no collision, 0 if X collision, 1 if Y collision, 2 if Z collision
44 // The time after which the collision occurs is stored in dtime.
axisAlignedCollision(const aabb3f & staticbox,const aabb3f & movingbox,const v3f & speed,f32 d,f32 & dtime)45 int axisAlignedCollision(
46 const aabb3f &staticbox, const aabb3f &movingbox,
47 const v3f &speed, f32 d, f32 &dtime)
48 {
49 //TimeTaker tt("axisAlignedCollision");
50
51 f32 xsize = (staticbox.MaxEdge.X - staticbox.MinEdge.X); // - COLL_ZEROY; // reduce box size for solve collision stuck (flying sand)
52 f32 ysize = (staticbox.MaxEdge.Y - staticbox.MinEdge.Y); // - COLL_ZERO; // Y - no sense for falling, but maybe try later
53 f32 zsize = (staticbox.MaxEdge.Z - staticbox.MinEdge.Z); // - COLL_ZEROY;
54
55 aabb3f relbox(
56 movingbox.MinEdge.X - staticbox.MinEdge.X,
57 movingbox.MinEdge.Y - staticbox.MinEdge.Y,
58 movingbox.MinEdge.Z - staticbox.MinEdge.Z,
59 movingbox.MaxEdge.X - staticbox.MinEdge.X,
60 movingbox.MaxEdge.Y - staticbox.MinEdge.Y,
61 movingbox.MaxEdge.Z - staticbox.MinEdge.Z
62 );
63
64 // These cases can (and should) be rejected immediately
65 if( (speed.X >= 0 && relbox.MinEdge.X > xsize) ||
66 (speed.X <= 0 && relbox.MaxEdge.X < 0) ||
67 (speed.Y >= 0 && relbox.MinEdge.Y > ysize) ||
68 (speed.Y <= 0 && relbox.MaxEdge.Y < 0) ||
69 (speed.Z >= 0 && relbox.MinEdge.Z > zsize) ||
70 (speed.Z <= 0 && relbox.MaxEdge.Z < 0))
71 return -1;
72
73 if(speed.X > 0) // Check for collision with X- plane
74 {
75 if(relbox.MaxEdge.X <= d)
76 {
77 dtime = - relbox.MaxEdge.X / speed.X;
78 if((relbox.MinEdge.Y + speed.Y * dtime < ysize) &&
79 (relbox.MaxEdge.Y + speed.Y * dtime > COLL_ZERO) &&
80 (relbox.MinEdge.Z + speed.Z * dtime < zsize) &&
81 (relbox.MaxEdge.Z + speed.Z * dtime > COLL_ZERO))
82 return 0;
83 }
84 }
85 else if(speed.X < 0) // Check for collision with X+ plane
86 {
87 if(relbox.MinEdge.X >= xsize - d)
88 {
89 dtime = (xsize - relbox.MinEdge.X) / speed.X;
90 if((relbox.MinEdge.Y + speed.Y * dtime < ysize) &&
91 (relbox.MaxEdge.Y + speed.Y * dtime > COLL_ZERO) &&
92 (relbox.MinEdge.Z + speed.Z * dtime < zsize) &&
93 (relbox.MaxEdge.Z + speed.Z * dtime > COLL_ZERO))
94 return 0;
95 }
96 }
97
98 // NO else if here
99
100 if(speed.Y > 0) // Check for collision with Y- plane
101 {
102 if(relbox.MaxEdge.Y <= d)
103 {
104 dtime = - relbox.MaxEdge.Y / speed.Y;
105 if((relbox.MinEdge.X + speed.X * dtime < xsize) &&
106 (relbox.MaxEdge.X + speed.X * dtime > COLL_ZERO) &&
107 (relbox.MinEdge.Z + speed.Z * dtime < zsize) &&
108 (relbox.MaxEdge.Z + speed.Z * dtime > COLL_ZERO))
109 return 1;
110 }
111 }
112 else if(speed.Y < 0) // Check for collision with Y+ plane
113 {
114 if(relbox.MinEdge.Y >= ysize - d)
115 {
116 dtime = (ysize - relbox.MinEdge.Y) / speed.Y;
117 if((relbox.MinEdge.X + speed.X * dtime < xsize) &&
118 (relbox.MaxEdge.X + speed.X * dtime > COLL_ZEROY) &&
119 (relbox.MinEdge.Z + speed.Z * dtime < zsize) &&
120 (relbox.MaxEdge.Z + speed.Z * dtime > COLL_ZEROY))
121 return 1;
122 }
123 }
124
125 // NO else if here
126
127 if(speed.Z > 0) // Check for collision with Z- plane
128 {
129 if(relbox.MaxEdge.Z <= d)
130 {
131 dtime = - relbox.MaxEdge.Z / speed.Z;
132 if((relbox.MinEdge.X + speed.X * dtime < xsize) &&
133 (relbox.MaxEdge.X + speed.X * dtime > COLL_ZERO) &&
134 (relbox.MinEdge.Y + speed.Y * dtime < ysize) &&
135 (relbox.MaxEdge.Y + speed.Y * dtime > COLL_ZERO))
136 return 2;
137 }
138 }
139 else if(speed.Z < 0) // Check for collision with Z+ plane
140 {
141 if(relbox.MinEdge.Z >= zsize - d)
142 {
143 dtime = (zsize - relbox.MinEdge.Z) / speed.Z;
144 if((relbox.MinEdge.X + speed.X * dtime < xsize) &&
145 (relbox.MaxEdge.X + speed.X * dtime > COLL_ZERO) &&
146 (relbox.MinEdge.Y + speed.Y * dtime < ysize) &&
147 (relbox.MaxEdge.Y + speed.Y * dtime > COLL_ZERO))
148 return 2;
149 }
150 }
151
152 return -1;
153 }
154
155 // Helper function:
156 // Checks if moving the movingbox up by the given distance would hit a ceiling.
wouldCollideWithCeiling(const std::vector<aabb3f> & staticboxes,const aabb3f & movingbox,f32 y_increase,f32 d)157 bool wouldCollideWithCeiling(
158 const std::vector<aabb3f> &staticboxes,
159 const aabb3f &movingbox,
160 f32 y_increase, f32 d)
161 {
162 //TimeTaker tt("wouldCollideWithCeiling");
163
164 assert(y_increase >= 0);
165
166 for(std::vector<aabb3f>::const_iterator
167 i = staticboxes.begin();
168 i != staticboxes.end(); i++)
169 {
170 const aabb3f& staticbox = *i;
171 if((movingbox.MaxEdge.Y - d <= staticbox.MinEdge.Y) &&
172 (movingbox.MaxEdge.Y + y_increase > staticbox.MinEdge.Y) &&
173 (movingbox.MinEdge.X < staticbox.MaxEdge.X) &&
174 (movingbox.MaxEdge.X > staticbox.MinEdge.X) &&
175 (movingbox.MinEdge.Z < staticbox.MaxEdge.Z) &&
176 (movingbox.MaxEdge.Z > staticbox.MinEdge.Z))
177 return true;
178 }
179
180 return false;
181 }
182
183
collisionMoveSimple(Environment * env,IGameDef * gamedef,f32 pos_max_d,const aabb3f & box_0,f32 stepheight,f32 dtime,v3f & pos_f,v3f & speed_f,v3f & accel_f,ActiveObject * self,bool collideWithObjects)184 collisionMoveResult collisionMoveSimple(Environment *env, IGameDef *gamedef,
185 f32 pos_max_d, const aabb3f &box_0,
186 f32 stepheight, f32 dtime,
187 v3f &pos_f, v3f &speed_f,
188 v3f &accel_f,ActiveObject* self,
189 bool collideWithObjects)
190 {
191 Map *map = &env->getMap();
192 //TimeTaker tt("collisionMoveSimple");
193 //ScopeProfiler sp(g_profiler, "collisionMoveSimple avg", SPT_AVG);
194
195 collisionMoveResult result;
196
197 /*
198 Calculate new velocity
199 */
200 if( dtime > 1 ) {
201 /*
202 infostream<<"collisionMoveSimple: WARNING: maximum step interval exceeded, lost movement details!"<<std::endl;
203 */
204 dtime = 1;
205 }
206 speed_f += accel_f * dtime;
207
208 // If there is no speed, there are no collisions
209 if(speed_f.getLength() == 0)
210 return result;
211
212 // Limit speed for avoiding hangs
213 speed_f.Y=rangelim(speed_f.Y,-1000,1000);
214 speed_f.X=rangelim(speed_f.X,-1000,1000);
215 speed_f.Z=rangelim(speed_f.Z,-1000,1000);
216
217 /*
218 Collect node boxes in movement range
219 */
220 std::vector<aabb3f> cboxes;
221 std::vector<bool> is_unloaded;
222 std::vector<bool> is_step_up;
223 std::vector<bool> is_object;
224 std::vector<int> bouncy_values;
225 std::vector<v3s16> node_positions;
226 {
227 //TimeTaker tt2("collisionMoveSimple collect boxes");
228 //ScopeProfiler sp(g_profiler, "collisionMoveSimple collect boxes avg", SPT_AVG);
229
230 v3s16 oldpos_i = floatToInt(pos_f, BS);
231 v3s16 newpos_i = floatToInt(pos_f + speed_f * dtime, BS);
232 s16 min_x = MYMIN(oldpos_i.X, newpos_i.X) + (box_0.MinEdge.X / BS) - 1;
233 s16 min_y = MYMIN(oldpos_i.Y, newpos_i.Y) + (box_0.MinEdge.Y / BS) - 1;
234 s16 min_z = MYMIN(oldpos_i.Z, newpos_i.Z) + (box_0.MinEdge.Z / BS) - 1;
235 s16 max_x = MYMAX(oldpos_i.X, newpos_i.X) + (box_0.MaxEdge.X / BS) + 1;
236 s16 max_y = MYMAX(oldpos_i.Y, newpos_i.Y) + (box_0.MaxEdge.Y / BS) + 1;
237 s16 max_z = MYMAX(oldpos_i.Z, newpos_i.Z) + (box_0.MaxEdge.Z / BS) + 1;
238
239 for(s16 x = min_x; x <= max_x; x++)
240 for(s16 y = min_y; y <= max_y; y++)
241 for(s16 z = min_z; z <= max_z; z++)
242 {
243 v3s16 p(x,y,z);
244
245 bool is_position_valid;
246 MapNode n = map->getNodeNoEx(p, &is_position_valid);
247
248 if (is_position_valid) {
249 // Object collides into walkable nodes
250
251 const ContentFeatures &f = gamedef->getNodeDefManager()->get(n);
252 if(f.walkable == false)
253 continue;
254 int n_bouncy_value = itemgroup_get(f.groups, "bouncy");
255
256 std::vector<aabb3f> nodeboxes = n.getCollisionBoxes(gamedef->ndef());
257 for(std::vector<aabb3f>::iterator
258 i = nodeboxes.begin();
259 i != nodeboxes.end(); i++)
260 {
261 aabb3f box = *i;
262 box.MinEdge += v3f(x, y, z)*BS;
263 box.MaxEdge += v3f(x, y, z)*BS;
264 cboxes.push_back(box);
265 is_unloaded.push_back(false);
266 is_step_up.push_back(false);
267 bouncy_values.push_back(n_bouncy_value);
268 node_positions.push_back(p);
269 is_object.push_back(false);
270 }
271 }
272 else {
273 // Collide with unloaded nodes
274 aabb3f box = getNodeBox(p, BS);
275 cboxes.push_back(box);
276 is_unloaded.push_back(true);
277 is_step_up.push_back(false);
278 bouncy_values.push_back(0);
279 node_positions.push_back(p);
280 is_object.push_back(false);
281 }
282 }
283 } // tt2
284
285 if(collideWithObjects)
286 {
287 //ScopeProfiler sp(g_profiler, "collisionMoveSimple objects avg", SPT_AVG);
288 //TimeTaker tt3("collisionMoveSimple collect object boxes");
289
290 /* add object boxes to cboxes */
291
292
293 std::list<ActiveObject*> objects;
294 #ifndef SERVER
295 ClientEnvironment *c_env = dynamic_cast<ClientEnvironment*>(env);
296 if (c_env != 0)
297 {
298 f32 distance = speed_f.getLength();
299 std::vector<DistanceSortedActiveObject> clientobjects;
300 c_env->getActiveObjects(pos_f,distance * 1.5,clientobjects);
301 for (size_t i=0; i < clientobjects.size(); i++)
302 {
303 if ((self == 0) || (self != clientobjects[i].obj)) {
304 objects.push_back((ActiveObject*)clientobjects[i].obj);
305 }
306 }
307 }
308 else
309 #endif
310 {
311 ServerEnvironment *s_env = dynamic_cast<ServerEnvironment*>(env);
312 if (s_env != 0)
313 {
314 f32 distance = speed_f.getLength();
315 std::set<u16> s_objects = s_env->getObjectsInsideRadius(pos_f,distance * 1.5);
316 for (std::set<u16>::iterator iter = s_objects.begin(); iter != s_objects.end(); iter++)
317 {
318 ServerActiveObject *current = s_env->getActiveObject(*iter);
319 if ((self == 0) || (self != current)) {
320 objects.push_back((ActiveObject*)current);
321 }
322 }
323 }
324 }
325
326 for (std::list<ActiveObject*>::const_iterator iter = objects.begin();iter != objects.end(); ++iter)
327 {
328 ActiveObject *object = *iter;
329
330 if (object != NULL)
331 {
332 aabb3f object_collisionbox;
333 if (object->getCollisionBox(&object_collisionbox) &&
334 object->collideWithObjects())
335 {
336 cboxes.push_back(object_collisionbox);
337 is_unloaded.push_back(false);
338 is_step_up.push_back(false);
339 bouncy_values.push_back(0);
340 node_positions.push_back(v3s16(0,0,0));
341 is_object.push_back(true);
342 }
343 }
344 }
345 } //tt3
346
347 assert(cboxes.size() == is_unloaded.size());
348 assert(cboxes.size() == is_step_up.size());
349 assert(cboxes.size() == bouncy_values.size());
350 assert(cboxes.size() == node_positions.size());
351 assert(cboxes.size() == is_object.size());
352
353 /*
354 Collision detection
355 */
356
357 /*
358 Collision uncertainty radius
359 Make it a bit larger than the maximum distance of movement
360 */
361 f32 d = pos_max_d * 1.1;
362 // A fairly large value in here makes moving smoother
363 //f32 d = 0.15*BS;
364
365 // This should always apply, otherwise there are glitches
366 assert(d > pos_max_d);
367
368 int loopcount = 0;
369
370 while(dtime > BS*1e-10)
371 {
372 //TimeTaker tt3("collisionMoveSimple dtime loop");
373 //ScopeProfiler sp(g_profiler, "collisionMoveSimple dtime loop avg", SPT_AVG);
374
375 // Avoid infinite loop
376 loopcount++;
377 if(loopcount >= 100)
378 {
379 infostream<<"collisionMoveSimple: WARNING: Loop count exceeded, aborting to avoid infiniite loop"<<std::endl;
380 dtime = 0;
381 break;
382 }
383
384 aabb3f movingbox = box_0;
385 movingbox.MinEdge += pos_f;
386 movingbox.MaxEdge += pos_f;
387
388 int nearest_collided = -1;
389 f32 nearest_dtime = dtime;
390 u32 nearest_boxindex = -1;
391
392 /*
393 Go through every nodebox, find nearest collision
394 */
395 for(u32 boxindex = 0; boxindex < cboxes.size(); boxindex++)
396 {
397 // Ignore if already stepped up this nodebox.
398 if(is_step_up[boxindex])
399 continue;
400
401 // Find nearest collision of the two boxes (raytracing-like)
402 f32 dtime_tmp;
403 int collided = axisAlignedCollision(
404 cboxes[boxindex], movingbox, speed_f, d, dtime_tmp);
405
406 if(collided == -1 || dtime_tmp >= nearest_dtime)
407 continue;
408
409 nearest_dtime = dtime_tmp;
410 nearest_collided = collided;
411 nearest_boxindex = boxindex;
412 }
413
414 if(nearest_collided == -1)
415 {
416 // No collision with any collision box.
417 pos_f += speed_f * dtime;
418 dtime = 0; // Set to 0 to avoid "infinite" loop due to small FP numbers
419 }
420 else
421 {
422 // Otherwise, a collision occurred.
423
424 const aabb3f& cbox = cboxes[nearest_boxindex];
425
426 // Check for stairs.
427 bool step_up = (nearest_collided != 1) && // must not be Y direction
428 (movingbox.MinEdge.Y < cbox.MaxEdge.Y) &&
429 (movingbox.MinEdge.Y + stepheight > cbox.MaxEdge.Y) &&
430 (!wouldCollideWithCeiling(cboxes, movingbox,
431 cbox.MaxEdge.Y - movingbox.MinEdge.Y,
432 d));
433
434 // Get bounce multiplier
435 bool bouncy = (bouncy_values[nearest_boxindex] >= 1);
436 float bounce = -(float)bouncy_values[nearest_boxindex] / 100.0;
437
438 // Move to the point of collision and reduce dtime by nearest_dtime
439 if(nearest_dtime < 0)
440 {
441 // Handle negative nearest_dtime (can be caused by the d allowance)
442 if(!step_up)
443 {
444 if(nearest_collided == 0)
445 pos_f.X += speed_f.X * nearest_dtime;
446 if(nearest_collided == 1)
447 pos_f.Y += speed_f.Y * nearest_dtime;
448 if(nearest_collided == 2)
449 pos_f.Z += speed_f.Z * nearest_dtime;
450 }
451 }
452 else
453 {
454 pos_f += speed_f * nearest_dtime;
455 dtime -= nearest_dtime;
456 }
457
458 bool is_collision = true;
459 if(is_unloaded[nearest_boxindex])
460 is_collision = false;
461
462 CollisionInfo info;
463 if (is_object[nearest_boxindex]) {
464 info.type = COLLISION_OBJECT;
465 }
466 else {
467 info.type = COLLISION_NODE;
468 }
469 info.node_p = node_positions[nearest_boxindex];
470 info.bouncy = bouncy;
471 info.old_speed = speed_f;
472
473 // Set the speed component that caused the collision to zero
474 if(step_up)
475 {
476 // Special case: Handle stairs
477 is_step_up[nearest_boxindex] = true;
478 is_collision = false;
479 }
480 else if(nearest_collided == 0) // X
481 {
482 if(fabs(speed_f.X) > BS*3)
483 speed_f.X *= bounce;
484 else
485 speed_f.X = 0;
486 result.collides = true;
487 result.collides_xz = true;
488 }
489 else if(nearest_collided == 1) // Y
490 {
491 if(fabs(speed_f.Y) > BS*3)
492 speed_f.Y *= bounce;
493 else
494 speed_f.Y = 0;
495 result.collides = true;
496 }
497 else if(nearest_collided == 2) // Z
498 {
499 if(fabs(speed_f.Z) > BS*3)
500 speed_f.Z *= bounce;
501 else
502 speed_f.Z = 0;
503 result.collides = true;
504 result.collides_xz = true;
505 }
506
507 info.new_speed = speed_f;
508 if(info.new_speed.getDistanceFrom(info.old_speed) < 0.1*BS)
509 is_collision = false;
510
511 if(is_collision){
512 result.collisions.push_back(info);
513 }
514 }
515 }
516
517 /*
518 Final touches: Check if standing on ground, step up stairs.
519 */
520 aabb3f box = box_0;
521 box.MinEdge += pos_f;
522 box.MaxEdge += pos_f;
523 for(u32 boxindex = 0; boxindex < cboxes.size(); boxindex++)
524 {
525 const aabb3f& cbox = cboxes[boxindex];
526
527 /*
528 See if the object is touching ground.
529
530 Object touches ground if object's minimum Y is near node's
531 maximum Y and object's X-Z-area overlaps with the node's
532 X-Z-area.
533
534 Use 0.15*BS so that it is easier to get on a node.
535 */
536 if(
537 cbox.MaxEdge.X-d > box.MinEdge.X &&
538 cbox.MinEdge.X+d < box.MaxEdge.X &&
539 cbox.MaxEdge.Z-d > box.MinEdge.Z &&
540 cbox.MinEdge.Z+d < box.MaxEdge.Z
541 ){
542 if(is_step_up[boxindex])
543 {
544 pos_f.Y += (cbox.MaxEdge.Y - box.MinEdge.Y);
545 box = box_0;
546 box.MinEdge += pos_f;
547 box.MaxEdge += pos_f;
548 }
549 if(fabs(cbox.MaxEdge.Y-box.MinEdge.Y) < 0.15*BS)
550 {
551 result.touching_ground = true;
552 if(is_unloaded[boxindex])
553 result.standing_on_unloaded = true;
554 }
555 }
556 }
557
558 return result;
559 }
560
561 #if 0
562 // This doesn't seem to work and isn't used
563 collisionMoveResult collisionMovePrecise(Map *map, IGameDef *gamedef,
564 f32 pos_max_d, const aabb3f &box_0,
565 f32 stepheight, f32 dtime,
566 v3f &pos_f, v3f &speed_f, v3f &accel_f)
567 {
568 //TimeTaker tt("collisionMovePrecise");
569 ScopeProfiler sp(g_profiler, "collisionMovePrecise avg", SPT_AVG);
570
571 collisionMoveResult final_result;
572
573 // If there is no speed, there are no collisions
574 if(speed_f.getLength() == 0)
575 return final_result;
576
577 // Don't allow overly huge dtime
578 if(dtime > 2.0)
579 dtime = 2.0;
580
581 f32 dtime_downcount = dtime;
582
583 u32 loopcount = 0;
584 do
585 {
586 loopcount++;
587
588 // Maximum time increment (for collision detection etc)
589 // time = distance / speed
590 f32 dtime_max_increment = 1.0;
591 if(speed_f.getLength() != 0)
592 dtime_max_increment = pos_max_d / speed_f.getLength();
593
594 // Maximum time increment is 10ms or lower
595 if(dtime_max_increment > 0.01)
596 dtime_max_increment = 0.01;
597
598 f32 dtime_part;
599 if(dtime_downcount > dtime_max_increment)
600 {
601 dtime_part = dtime_max_increment;
602 dtime_downcount -= dtime_part;
603 }
604 else
605 {
606 dtime_part = dtime_downcount;
607 /*
608 Setting this to 0 (no -=dtime_part) disables an infinite loop
609 when dtime_part is so small that dtime_downcount -= dtime_part
610 does nothing
611 */
612 dtime_downcount = 0;
613 }
614
615 collisionMoveResult result = collisionMoveSimple(map, gamedef,
616 pos_max_d, box_0, stepheight, dtime_part,
617 pos_f, speed_f, accel_f);
618
619 if(result.touching_ground)
620 final_result.touching_ground = true;
621 if(result.collides)
622 final_result.collides = true;
623 if(result.collides_xz)
624 final_result.collides_xz = true;
625 if(result.standing_on_unloaded)
626 final_result.standing_on_unloaded = true;
627 }
628 while(dtime_downcount > 0.001);
629
630 return final_result;
631 }
632 #endif
633