space_bullet.cpp 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480
  1. /*************************************************************************/
  2. /* space_bullet.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "space_bullet.h"
  31. #include "bullet_physics_server.h"
  32. #include "bullet_types_converter.h"
  33. #include "bullet_utilities.h"
  34. #include "constraint_bullet.h"
  35. #include "core/project_settings.h"
  36. #include "core/ustring.h"
  37. #include "godot_collision_configuration.h"
  38. #include "godot_collision_dispatcher.h"
  39. #include "rigid_body_bullet.h"
  40. #include "servers/physics_server.h"
  41. #include "soft_body_bullet.h"
  42. #include <BulletCollision/BroadphaseCollision/btBroadphaseProxy.h>
  43. #include <BulletCollision/CollisionDispatch/btCollisionObject.h>
  44. #include <BulletCollision/CollisionDispatch/btGhostObject.h>
  45. #include <BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h>
  46. #include <BulletCollision/NarrowPhaseCollision/btGjkPairDetector.h>
  47. #include <BulletCollision/NarrowPhaseCollision/btPointCollector.h>
  48. #include <BulletSoftBody/btSoftBodyRigidBodyCollisionConfiguration.h>
  49. #include <BulletSoftBody/btSoftRigidDynamicsWorld.h>
  50. #include <btBulletDynamicsCommon.h>
  51. #include <assert.h>
  52. /**
  53. @author AndreaCatania
  54. */
  55. BulletPhysicsDirectSpaceState::BulletPhysicsDirectSpaceState(SpaceBullet *p_space) :
  56. PhysicsDirectSpaceState(),
  57. space(p_space) {}
  58. int BulletPhysicsDirectSpaceState::intersect_point(const Vector3 &p_point, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) {
  59. if (p_result_max <= 0)
  60. return 0;
  61. btVector3 bt_point;
  62. G_TO_B(p_point, bt_point);
  63. btSphereShape sphere_point(0.001f);
  64. btCollisionObject collision_object_point;
  65. collision_object_point.setCollisionShape(&sphere_point);
  66. collision_object_point.setWorldTransform(btTransform(btQuaternion::getIdentity(), bt_point));
  67. // Setup query
  68. GodotAllContactResultCallback btResult(&collision_object_point, r_results, p_result_max, &p_exclude, p_collide_with_bodies, p_collide_with_areas);
  69. btResult.m_collisionFilterGroup = 0;
  70. btResult.m_collisionFilterMask = p_collision_mask;
  71. space->dynamicsWorld->contactTest(&collision_object_point, btResult);
  72. // The results is already populated by GodotAllConvexResultCallback
  73. return btResult.m_count;
  74. }
  75. bool BulletPhysicsDirectSpaceState::intersect_ray(const Vector3 &p_from, const Vector3 &p_to, RayResult &r_result, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas, bool p_pick_ray) {
  76. btVector3 btVec_from;
  77. btVector3 btVec_to;
  78. G_TO_B(p_from, btVec_from);
  79. G_TO_B(p_to, btVec_to);
  80. // setup query
  81. GodotClosestRayResultCallback btResult(btVec_from, btVec_to, &p_exclude, p_collide_with_bodies, p_collide_with_areas);
  82. btResult.m_collisionFilterGroup = 0;
  83. btResult.m_collisionFilterMask = p_collision_mask;
  84. btResult.m_pickRay = p_pick_ray;
  85. space->dynamicsWorld->rayTest(btVec_from, btVec_to, btResult);
  86. if (btResult.hasHit()) {
  87. B_TO_G(btResult.m_hitPointWorld, r_result.position);
  88. B_TO_G(btResult.m_hitNormalWorld.normalize(), r_result.normal);
  89. CollisionObjectBullet *gObj = static_cast<CollisionObjectBullet *>(btResult.m_collisionObject->getUserPointer());
  90. if (gObj) {
  91. r_result.shape = btResult.m_shapeId;
  92. r_result.rid = gObj->get_self();
  93. r_result.collider_id = gObj->get_instance_id();
  94. r_result.collider = 0 == r_result.collider_id ? NULL : ObjectDB::get_instance(r_result.collider_id);
  95. } else {
  96. WARN_PRINTS("The raycast performed has hit a collision object that is not part of Godot scene, please check it.");
  97. }
  98. return true;
  99. } else {
  100. return false;
  101. }
  102. }
  103. int BulletPhysicsDirectSpaceState::intersect_shape(const RID &p_shape, const Transform &p_xform, float p_margin, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) {
  104. if (p_result_max <= 0)
  105. return 0;
  106. ShapeBullet *shape = space->get_physics_server()->get_shape_owner()->get(p_shape);
  107. ERR_FAIL_COND_V(!shape, 0);
  108. btCollisionShape *btShape = shape->create_bt_shape(p_xform.basis.get_scale_abs(), p_margin);
  109. if (!btShape->isConvex()) {
  110. bulletdelete(btShape);
  111. ERR_PRINTS("The shape is not a convex shape, then is not supported: shape type: " + itos(shape->get_type()));
  112. return 0;
  113. }
  114. btConvexShape *btConvex = static_cast<btConvexShape *>(btShape);
  115. btTransform bt_xform;
  116. G_TO_B(p_xform, bt_xform);
  117. UNSCALE_BT_BASIS(bt_xform);
  118. btCollisionObject collision_object;
  119. collision_object.setCollisionShape(btConvex);
  120. collision_object.setWorldTransform(bt_xform);
  121. GodotAllContactResultCallback btQuery(&collision_object, r_results, p_result_max, &p_exclude, p_collide_with_bodies, p_collide_with_areas);
  122. btQuery.m_collisionFilterGroup = 0;
  123. btQuery.m_collisionFilterMask = p_collision_mask;
  124. btQuery.m_closestDistanceThreshold = 0;
  125. space->dynamicsWorld->contactTest(&collision_object, btQuery);
  126. bulletdelete(btConvex);
  127. return btQuery.m_count;
  128. }
  129. bool BulletPhysicsDirectSpaceState::cast_motion(const RID &p_shape, const Transform &p_xform, const Vector3 &p_motion, float p_margin, float &r_closest_safe, float &r_closest_unsafe, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas, ShapeRestInfo *r_info) {
  130. r_closest_safe = 0.0f;
  131. r_closest_unsafe = 0.0f;
  132. btVector3 bt_motion;
  133. G_TO_B(p_motion, bt_motion);
  134. ShapeBullet *shape = space->get_physics_server()->get_shape_owner()->get(p_shape);
  135. ERR_FAIL_COND_V(!shape, false);
  136. btCollisionShape *btShape = shape->create_bt_shape(p_xform.basis.get_scale(), p_margin);
  137. if (!btShape->isConvex()) {
  138. bulletdelete(btShape);
  139. ERR_PRINTS("The shape is not a convex shape, then is not supported: shape type: " + itos(shape->get_type()));
  140. return false;
  141. }
  142. btConvexShape *bt_convex_shape = static_cast<btConvexShape *>(btShape);
  143. btTransform bt_xform_from;
  144. G_TO_B(p_xform, bt_xform_from);
  145. UNSCALE_BT_BASIS(bt_xform_from);
  146. btTransform bt_xform_to(bt_xform_from);
  147. bt_xform_to.getOrigin() += bt_motion;
  148. if ((bt_xform_to.getOrigin() - bt_xform_from.getOrigin()).fuzzyZero()) {
  149. bulletdelete(btShape);
  150. return false;
  151. }
  152. GodotClosestConvexResultCallback btResult(bt_xform_from.getOrigin(), bt_xform_to.getOrigin(), &p_exclude, p_collide_with_bodies, p_collide_with_areas);
  153. btResult.m_collisionFilterGroup = 0;
  154. btResult.m_collisionFilterMask = p_collision_mask;
  155. space->dynamicsWorld->convexSweepTest(bt_convex_shape, bt_xform_from, bt_xform_to, btResult, space->dynamicsWorld->getDispatchInfo().m_allowedCcdPenetration);
  156. if (btResult.hasHit()) {
  157. const btScalar l = bt_motion.length();
  158. r_closest_unsafe = btResult.m_closestHitFraction;
  159. r_closest_safe = MAX(r_closest_unsafe - (1 - ((l - 0.01) / l)), 0);
  160. if (r_info) {
  161. if (btCollisionObject::CO_RIGID_BODY == btResult.m_hitCollisionObject->getInternalType()) {
  162. B_TO_G(static_cast<const btRigidBody *>(btResult.m_hitCollisionObject)->getVelocityInLocalPoint(btResult.m_hitPointWorld), r_info->linear_velocity);
  163. }
  164. CollisionObjectBullet *collision_object = static_cast<CollisionObjectBullet *>(btResult.m_hitCollisionObject->getUserPointer());
  165. B_TO_G(btResult.m_hitPointWorld, r_info->point);
  166. B_TO_G(btResult.m_hitNormalWorld, r_info->normal);
  167. r_info->rid = collision_object->get_self();
  168. r_info->collider_id = collision_object->get_instance_id();
  169. r_info->shape = btResult.m_shapeId;
  170. }
  171. } else {
  172. r_closest_safe = 1.0f;
  173. r_closest_unsafe = 1.0f;
  174. }
  175. bulletdelete(bt_convex_shape);
  176. return true; // Mean success
  177. }
  178. /// Returns the list of contacts pairs in this order: Local contact, other body contact
  179. bool BulletPhysicsDirectSpaceState::collide_shape(RID p_shape, const Transform &p_shape_xform, float p_margin, Vector3 *r_results, int p_result_max, int &r_result_count, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) {
  180. if (p_result_max <= 0)
  181. return 0;
  182. ShapeBullet *shape = space->get_physics_server()->get_shape_owner()->get(p_shape);
  183. ERR_FAIL_COND_V(!shape, false);
  184. btCollisionShape *btShape = shape->create_bt_shape(p_shape_xform.basis.get_scale_abs(), p_margin);
  185. if (!btShape->isConvex()) {
  186. bulletdelete(btShape);
  187. ERR_PRINTS("The shape is not a convex shape, then is not supported: shape type: " + itos(shape->get_type()));
  188. return 0;
  189. }
  190. btConvexShape *btConvex = static_cast<btConvexShape *>(btShape);
  191. btTransform bt_xform;
  192. G_TO_B(p_shape_xform, bt_xform);
  193. UNSCALE_BT_BASIS(bt_xform);
  194. btCollisionObject collision_object;
  195. collision_object.setCollisionShape(btConvex);
  196. collision_object.setWorldTransform(bt_xform);
  197. GodotContactPairContactResultCallback btQuery(&collision_object, r_results, p_result_max, &p_exclude, p_collide_with_bodies, p_collide_with_areas);
  198. btQuery.m_collisionFilterGroup = 0;
  199. btQuery.m_collisionFilterMask = p_collision_mask;
  200. btQuery.m_closestDistanceThreshold = 0;
  201. space->dynamicsWorld->contactTest(&collision_object, btQuery);
  202. r_result_count = btQuery.m_count;
  203. bulletdelete(btConvex);
  204. return btQuery.m_count;
  205. }
  206. bool BulletPhysicsDirectSpaceState::rest_info(RID p_shape, const Transform &p_shape_xform, float p_margin, ShapeRestInfo *r_info, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) {
  207. ShapeBullet *shape = space->get_physics_server()->get_shape_owner()->get(p_shape);
  208. ERR_FAIL_COND_V(!shape, false);
  209. btCollisionShape *btShape = shape->create_bt_shape(p_shape_xform.basis.get_scale_abs(), p_margin);
  210. if (!btShape->isConvex()) {
  211. bulletdelete(btShape);
  212. ERR_PRINTS("The shape is not a convex shape, then is not supported: shape type: " + itos(shape->get_type()));
  213. return 0;
  214. }
  215. btConvexShape *btConvex = static_cast<btConvexShape *>(btShape);
  216. btTransform bt_xform;
  217. G_TO_B(p_shape_xform, bt_xform);
  218. UNSCALE_BT_BASIS(bt_xform);
  219. btCollisionObject collision_object;
  220. collision_object.setCollisionShape(btConvex);
  221. collision_object.setWorldTransform(bt_xform);
  222. GodotRestInfoContactResultCallback btQuery(&collision_object, r_info, &p_exclude, p_collide_with_bodies, p_collide_with_areas);
  223. btQuery.m_collisionFilterGroup = 0;
  224. btQuery.m_collisionFilterMask = p_collision_mask;
  225. btQuery.m_closestDistanceThreshold = 0;
  226. space->dynamicsWorld->contactTest(&collision_object, btQuery);
  227. bulletdelete(btConvex);
  228. if (btQuery.m_collided) {
  229. if (btCollisionObject::CO_RIGID_BODY == btQuery.m_rest_info_collision_object->getInternalType()) {
  230. B_TO_G(static_cast<const btRigidBody *>(btQuery.m_rest_info_collision_object)->getVelocityInLocalPoint(btQuery.m_rest_info_bt_point), r_info->linear_velocity);
  231. }
  232. B_TO_G(btQuery.m_rest_info_bt_point, r_info->point);
  233. }
  234. return btQuery.m_collided;
  235. }
  236. Vector3 BulletPhysicsDirectSpaceState::get_closest_point_to_object_volume(RID p_object, const Vector3 p_point) const {
  237. RigidCollisionObjectBullet *rigid_object = space->get_physics_server()->get_rigid_collisin_object(p_object);
  238. ERR_FAIL_COND_V(!rigid_object, Vector3());
  239. btVector3 out_closest_point(0, 0, 0);
  240. btScalar out_distance = 1e20;
  241. btVector3 bt_point;
  242. G_TO_B(p_point, bt_point);
  243. btSphereShape point_shape(0.);
  244. btCollisionShape *shape;
  245. btConvexShape *convex_shape;
  246. btTransform child_transform;
  247. btTransform body_transform(rigid_object->get_bt_collision_object()->getWorldTransform());
  248. btGjkPairDetector::ClosestPointInput input;
  249. input.m_transformA.getBasis().setIdentity();
  250. input.m_transformA.setOrigin(bt_point);
  251. bool shapes_found = false;
  252. for (int i = rigid_object->get_shape_count() - 1; 0 <= i; --i) {
  253. shape = rigid_object->get_bt_shape(i);
  254. if (shape->isConvex()) {
  255. child_transform = rigid_object->get_bt_shape_transform(i);
  256. convex_shape = static_cast<btConvexShape *>(shape);
  257. input.m_transformB = body_transform * child_transform;
  258. btPointCollector result;
  259. btGjkPairDetector gjk_pair_detector(&point_shape, convex_shape, space->gjk_simplex_solver, space->gjk_epa_pen_solver);
  260. gjk_pair_detector.getClosestPoints(input, result, 0);
  261. if (out_distance > result.m_distance) {
  262. out_distance = result.m_distance;
  263. out_closest_point = result.m_pointInWorld;
  264. }
  265. }
  266. shapes_found = true;
  267. }
  268. if (shapes_found) {
  269. Vector3 out;
  270. B_TO_G(out_closest_point, out);
  271. return out;
  272. } else {
  273. // no shapes found, use distance to origin.
  274. return rigid_object->get_transform().get_origin();
  275. }
  276. }
  277. SpaceBullet::SpaceBullet() :
  278. broadphase(NULL),
  279. collisionConfiguration(NULL),
  280. dispatcher(NULL),
  281. solver(NULL),
  282. dynamicsWorld(NULL),
  283. soft_body_world_info(NULL),
  284. ghostPairCallback(NULL),
  285. godotFilterCallback(NULL),
  286. gravityDirection(0, -1, 0),
  287. gravityMagnitude(10),
  288. linear_damp(0.0),
  289. angular_damp(0.0),
  290. contactDebugCount(0),
  291. delta_time(0.) {
  292. create_empty_world(GLOBAL_DEF("physics/3d/active_soft_world", true));
  293. direct_access = memnew(BulletPhysicsDirectSpaceState(this));
  294. }
  295. SpaceBullet::~SpaceBullet() {
  296. memdelete(direct_access);
  297. destroy_world();
  298. }
  299. void SpaceBullet::flush_queries() {
  300. const btCollisionObjectArray &colObjArray = dynamicsWorld->getCollisionObjectArray();
  301. for (int i = colObjArray.size() - 1; 0 <= i; --i) {
  302. static_cast<CollisionObjectBullet *>(colObjArray[i]->getUserPointer())->dispatch_callbacks();
  303. }
  304. }
  305. void SpaceBullet::step(real_t p_delta_time) {
  306. delta_time = p_delta_time;
  307. dynamicsWorld->stepSimulation(p_delta_time, 0, 0);
  308. }
  309. void SpaceBullet::set_param(PhysicsServer::AreaParameter p_param, const Variant &p_value) {
  310. assert(dynamicsWorld);
  311. switch (p_param) {
  312. case PhysicsServer::AREA_PARAM_GRAVITY:
  313. gravityMagnitude = p_value;
  314. update_gravity();
  315. break;
  316. case PhysicsServer::AREA_PARAM_GRAVITY_VECTOR:
  317. gravityDirection = p_value;
  318. update_gravity();
  319. break;
  320. case PhysicsServer::AREA_PARAM_LINEAR_DAMP:
  321. linear_damp = p_value;
  322. break;
  323. case PhysicsServer::AREA_PARAM_ANGULAR_DAMP:
  324. angular_damp = p_value;
  325. break;
  326. case PhysicsServer::AREA_PARAM_PRIORITY:
  327. // Priority is always 0, the lower
  328. break;
  329. case PhysicsServer::AREA_PARAM_GRAVITY_IS_POINT:
  330. case PhysicsServer::AREA_PARAM_GRAVITY_DISTANCE_SCALE:
  331. case PhysicsServer::AREA_PARAM_GRAVITY_POINT_ATTENUATION:
  332. break;
  333. default:
  334. WARN_PRINTS("This set parameter (" + itos(p_param) + ") is ignored, the SpaceBullet doesn't support it.");
  335. break;
  336. }
  337. }
  338. Variant SpaceBullet::get_param(PhysicsServer::AreaParameter p_param) {
  339. switch (p_param) {
  340. case PhysicsServer::AREA_PARAM_GRAVITY:
  341. return gravityMagnitude;
  342. case PhysicsServer::AREA_PARAM_GRAVITY_VECTOR:
  343. return gravityDirection;
  344. case PhysicsServer::AREA_PARAM_LINEAR_DAMP:
  345. return linear_damp;
  346. case PhysicsServer::AREA_PARAM_ANGULAR_DAMP:
  347. return angular_damp;
  348. case PhysicsServer::AREA_PARAM_PRIORITY:
  349. return 0; // Priority is always 0, the lower
  350. case PhysicsServer::AREA_PARAM_GRAVITY_IS_POINT:
  351. return false;
  352. case PhysicsServer::AREA_PARAM_GRAVITY_DISTANCE_SCALE:
  353. return 0;
  354. case PhysicsServer::AREA_PARAM_GRAVITY_POINT_ATTENUATION:
  355. return 0;
  356. default:
  357. WARN_PRINTS("This get parameter (" + itos(p_param) + ") is ignored, the SpaceBullet doesn't support it.");
  358. return Variant();
  359. }
  360. }
  361. void SpaceBullet::set_param(PhysicsServer::SpaceParameter p_param, real_t p_value) {
  362. switch (p_param) {
  363. case PhysicsServer::SPACE_PARAM_CONTACT_RECYCLE_RADIUS:
  364. case PhysicsServer::SPACE_PARAM_CONTACT_MAX_SEPARATION:
  365. case PhysicsServer::SPACE_PARAM_BODY_MAX_ALLOWED_PENETRATION:
  366. case PhysicsServer::SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_THRESHOLD:
  367. case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_THRESHOLD:
  368. case PhysicsServer::SPACE_PARAM_BODY_TIME_TO_SLEEP:
  369. case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_DAMP_RATIO:
  370. case PhysicsServer::SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS:
  371. default:
  372. WARN_PRINTS("This set parameter (" + itos(p_param) + ") is ignored, the SpaceBullet doesn't support it.");
  373. break;
  374. }
  375. }
  376. real_t SpaceBullet::get_param(PhysicsServer::SpaceParameter p_param) {
  377. switch (p_param) {
  378. case PhysicsServer::SPACE_PARAM_CONTACT_RECYCLE_RADIUS:
  379. case PhysicsServer::SPACE_PARAM_CONTACT_MAX_SEPARATION:
  380. case PhysicsServer::SPACE_PARAM_BODY_MAX_ALLOWED_PENETRATION:
  381. case PhysicsServer::SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_THRESHOLD:
  382. case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_THRESHOLD:
  383. case PhysicsServer::SPACE_PARAM_BODY_TIME_TO_SLEEP:
  384. case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_DAMP_RATIO:
  385. case PhysicsServer::SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS:
  386. default:
  387. WARN_PRINTS("The SpaceBullet doesn't support this get parameter (" + itos(p_param) + "), 0 is returned.");
  388. return 0.f;
  389. }
  390. }
  391. void SpaceBullet::add_area(AreaBullet *p_area) {
  392. areas.push_back(p_area);
  393. dynamicsWorld->addCollisionObject(p_area->get_bt_ghost(), p_area->get_collision_layer(), p_area->get_collision_mask());
  394. }
  395. void SpaceBullet::remove_area(AreaBullet *p_area) {
  396. areas.erase(p_area);
  397. dynamicsWorld->removeCollisionObject(p_area->get_bt_ghost());
  398. }
  399. void SpaceBullet::reload_collision_filters(AreaBullet *p_area) {
  400. btGhostObject *ghost_object = p_area->get_bt_ghost();
  401. btBroadphaseProxy *ghost_proxy = ghost_object->getBroadphaseHandle();
  402. ghost_proxy->m_collisionFilterGroup = p_area->get_collision_layer();
  403. ghost_proxy->m_collisionFilterMask = p_area->get_collision_mask();
  404. dynamicsWorld->refreshBroadphaseProxy(ghost_object);
  405. }
  406. void SpaceBullet::add_rigid_body(RigidBodyBullet *p_body) {
  407. if (p_body->is_static()) {
  408. dynamicsWorld->addCollisionObject(p_body->get_bt_rigid_body(), p_body->get_collision_layer(), p_body->get_collision_mask());
  409. } else {
  410. dynamicsWorld->addRigidBody(p_body->get_bt_rigid_body(), p_body->get_collision_layer(), p_body->get_collision_mask());
  411. p_body->scratch_space_override_modificator();
  412. }
  413. }
  414. void SpaceBullet::remove_rigid_body(RigidBodyBullet *p_body) {
  415. if (p_body->is_static()) {
  416. dynamicsWorld->removeCollisionObject(p_body->get_bt_rigid_body());
  417. } else {
  418. dynamicsWorld->removeRigidBody(p_body->get_bt_rigid_body());
  419. }
  420. }
  421. void SpaceBullet::reload_collision_filters(RigidBodyBullet *p_body) {
  422. btRigidBody *rigid_body = p_body->get_bt_rigid_body();
  423. btBroadphaseProxy *body_proxy = rigid_body->getBroadphaseProxy();
  424. body_proxy->m_collisionFilterGroup = p_body->get_collision_layer();
  425. body_proxy->m_collisionFilterMask = p_body->get_collision_mask();
  426. dynamicsWorld->refreshBroadphaseProxy(rigid_body);
  427. }
  428. void SpaceBullet::add_soft_body(SoftBodyBullet *p_body) {
  429. if (is_using_soft_world()) {
  430. if (p_body->get_bt_soft_body()) {
  431. p_body->get_bt_soft_body()->m_worldInfo = get_soft_body_world_info();
  432. static_cast<btSoftRigidDynamicsWorld *>(dynamicsWorld)->addSoftBody(p_body->get_bt_soft_body(), p_body->get_collision_layer(), p_body->get_collision_mask());
  433. }
  434. } else {
  435. ERR_PRINT("This soft body can't be added to non soft world");
  436. }
  437. }
  438. void SpaceBullet::remove_soft_body(SoftBodyBullet *p_body) {
  439. if (is_using_soft_world()) {
  440. if (p_body->get_bt_soft_body()) {
  441. static_cast<btSoftRigidDynamicsWorld *>(dynamicsWorld)->removeSoftBody(p_body->get_bt_soft_body());
  442. p_body->get_bt_soft_body()->m_worldInfo = NULL;
  443. }
  444. }
  445. }
  446. void SpaceBullet::reload_collision_filters(SoftBodyBullet *p_body) {
  447. // This is necessary to change collision filter
  448. remove_soft_body(p_body);
  449. add_soft_body(p_body);
  450. }
  451. void SpaceBullet::add_constraint(ConstraintBullet *p_constraint, bool disableCollisionsBetweenLinkedBodies) {
  452. p_constraint->set_space(this);
  453. dynamicsWorld->addConstraint(p_constraint->get_bt_constraint(), disableCollisionsBetweenLinkedBodies);
  454. }
  455. void SpaceBullet::remove_constraint(ConstraintBullet *p_constraint) {
  456. dynamicsWorld->removeConstraint(p_constraint->get_bt_constraint());
  457. }
  458. int SpaceBullet::get_num_collision_objects() const {
  459. return dynamicsWorld->getNumCollisionObjects();
  460. }
  461. void SpaceBullet::remove_all_collision_objects() {
  462. for (int i = dynamicsWorld->getNumCollisionObjects() - 1; 0 <= i; --i) {
  463. btCollisionObject *btObj = dynamicsWorld->getCollisionObjectArray()[i];
  464. CollisionObjectBullet *colObj = static_cast<CollisionObjectBullet *>(btObj->getUserPointer());
  465. colObj->set_space(NULL);
  466. }
  467. }
  468. void onBulletPreTickCallback(btDynamicsWorld *p_dynamicsWorld, btScalar timeStep) {
  469. static_cast<SpaceBullet *>(p_dynamicsWorld->getWorldUserInfo())->flush_queries();
  470. }
  471. void onBulletTickCallback(btDynamicsWorld *p_dynamicsWorld, btScalar timeStep) {
  472. const btCollisionObjectArray &colObjArray = p_dynamicsWorld->getCollisionObjectArray();
  473. // Notify all Collision objects the collision checker is started
  474. for (int i = colObjArray.size() - 1; 0 <= i; --i) {
  475. static_cast<CollisionObjectBullet *>(colObjArray[i]->getUserPointer())->on_collision_checker_start();
  476. }
  477. SpaceBullet *sb = static_cast<SpaceBullet *>(p_dynamicsWorld->getWorldUserInfo());
  478. sb->check_ghost_overlaps();
  479. sb->check_body_collision();
  480. for (int i = colObjArray.size() - 1; 0 <= i; --i) {
  481. static_cast<CollisionObjectBullet *>(colObjArray[i]->getUserPointer())->on_collision_checker_end();
  482. }
  483. }
  484. BulletPhysicsDirectSpaceState *SpaceBullet::get_direct_state() {
  485. return direct_access;
  486. }
  487. btScalar calculateGodotCombinedRestitution(const btCollisionObject *body0, const btCollisionObject *body1) {
  488. return CLAMP(body0->getRestitution() + body1->getRestitution(), 0, 1);
  489. }
  490. btScalar calculateGodotCombinedFriction(const btCollisionObject *body0, const btCollisionObject *body1) {
  491. return ABS(MIN(body0->getFriction(), body1->getFriction()));
  492. }
  493. void SpaceBullet::create_empty_world(bool p_create_soft_world) {
  494. gjk_epa_pen_solver = bulletnew(btGjkEpaPenetrationDepthSolver);
  495. gjk_simplex_solver = bulletnew(btVoronoiSimplexSolver);
  496. void *world_mem;
  497. if (p_create_soft_world) {
  498. world_mem = malloc(sizeof(btSoftRigidDynamicsWorld));
  499. } else {
  500. world_mem = malloc(sizeof(btDiscreteDynamicsWorld));
  501. }
  502. ERR_FAIL_COND_MSG(!world_mem, "Out of memory.");
  503. if (p_create_soft_world) {
  504. collisionConfiguration = bulletnew(GodotSoftCollisionConfiguration(static_cast<btDiscreteDynamicsWorld *>(world_mem)));
  505. } else {
  506. collisionConfiguration = bulletnew(GodotCollisionConfiguration(static_cast<btDiscreteDynamicsWorld *>(world_mem)));
  507. }
  508. dispatcher = bulletnew(GodotCollisionDispatcher(collisionConfiguration));
  509. broadphase = bulletnew(btDbvtBroadphase);
  510. solver = bulletnew(btSequentialImpulseConstraintSolver);
  511. if (p_create_soft_world) {
  512. dynamicsWorld = new (world_mem) btSoftRigidDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
  513. soft_body_world_info = bulletnew(btSoftBodyWorldInfo);
  514. } else {
  515. dynamicsWorld = new (world_mem) btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
  516. }
  517. ghostPairCallback = bulletnew(btGhostPairCallback);
  518. godotFilterCallback = bulletnew(GodotFilterCallback);
  519. gCalculateCombinedRestitutionCallback = &calculateGodotCombinedRestitution;
  520. gCalculateCombinedFrictionCallback = &calculateGodotCombinedFriction;
  521. gContactAddedCallback = &godotContactAddedCallback;
  522. dynamicsWorld->setWorldUserInfo(this);
  523. dynamicsWorld->setInternalTickCallback(onBulletPreTickCallback, this, true);
  524. dynamicsWorld->setInternalTickCallback(onBulletTickCallback, this, false);
  525. dynamicsWorld->getBroadphase()->getOverlappingPairCache()->setInternalGhostPairCallback(ghostPairCallback); // Setup ghost check
  526. dynamicsWorld->getPairCache()->setOverlapFilterCallback(godotFilterCallback);
  527. if (soft_body_world_info) {
  528. soft_body_world_info->m_broadphase = broadphase;
  529. soft_body_world_info->m_dispatcher = dispatcher;
  530. soft_body_world_info->m_sparsesdf.Initialize();
  531. }
  532. update_gravity();
  533. }
  534. void SpaceBullet::destroy_world() {
  535. /// The world elements (like: Collision Objects, Constraints, Shapes) are managed by godot
  536. dynamicsWorld->getBroadphase()->getOverlappingPairCache()->setInternalGhostPairCallback(NULL);
  537. dynamicsWorld->getPairCache()->setOverlapFilterCallback(NULL);
  538. bulletdelete(ghostPairCallback);
  539. bulletdelete(godotFilterCallback);
  540. // Deallocate world
  541. dynamicsWorld->~btDiscreteDynamicsWorld();
  542. free(dynamicsWorld);
  543. dynamicsWorld = NULL;
  544. bulletdelete(solver);
  545. bulletdelete(broadphase);
  546. bulletdelete(dispatcher);
  547. bulletdelete(collisionConfiguration);
  548. bulletdelete(soft_body_world_info);
  549. bulletdelete(gjk_simplex_solver);
  550. bulletdelete(gjk_epa_pen_solver);
  551. }
  552. void SpaceBullet::check_ghost_overlaps() {
  553. /// Algorithm support variables
  554. btCollisionShape *other_body_shape;
  555. btConvexShape *area_shape;
  556. btGjkPairDetector::ClosestPointInput gjk_input;
  557. AreaBullet *area;
  558. int x(-1), i(-1), y(-1), z(-1), indexOverlap(-1);
  559. /// For each areas
  560. for (x = areas.size() - 1; 0 <= x; --x) {
  561. area = areas[x];
  562. btVector3 area_scale(area->get_bt_body_scale());
  563. if (!area->is_monitoring())
  564. continue;
  565. /// 1. Reset all states
  566. for (i = area->overlappingObjects.size() - 1; 0 <= i; --i) {
  567. AreaBullet::OverlappingObjectData &otherObj = area->overlappingObjects.write[i];
  568. // This check prevent the overwrite of ENTER state
  569. // if this function is called more times before dispatchCallbacks
  570. if (otherObj.state != AreaBullet::OVERLAP_STATE_ENTER) {
  571. otherObj.state = AreaBullet::OVERLAP_STATE_DIRTY;
  572. }
  573. }
  574. /// 2. Check all overlapping objects using GJK
  575. const btAlignedObjectArray<btCollisionObject *> ghostOverlaps = area->get_bt_ghost()->getOverlappingPairs();
  576. // For each overlapping
  577. for (i = ghostOverlaps.size() - 1; 0 <= i; --i) {
  578. bool hasOverlap = false;
  579. btCollisionObject *overlapped_bt_co = ghostOverlaps[i];
  580. RigidCollisionObjectBullet *otherObject = static_cast<RigidCollisionObjectBullet *>(overlapped_bt_co->getUserPointer());
  581. btVector3 other_body_scale(otherObject->get_bt_body_scale());
  582. if (!area->is_transform_changed() && !otherObject->is_transform_changed()) {
  583. hasOverlap = -1 != area->find_overlapping_object(otherObject);
  584. goto collision_found;
  585. }
  586. if (overlapped_bt_co->getUserIndex() == CollisionObjectBullet::TYPE_AREA) {
  587. if (!static_cast<AreaBullet *>(overlapped_bt_co->getUserPointer())->is_monitorable())
  588. continue;
  589. } else if (overlapped_bt_co->getUserIndex() != CollisionObjectBullet::TYPE_RIGID_BODY)
  590. continue;
  591. // For each area shape
  592. for (y = area->get_shape_count() - 1; 0 <= y; --y) {
  593. if (!area->get_bt_shape(y)->isConvex())
  594. continue;
  595. btTransform area_shape_treansform(area->get_bt_shape_transform(y));
  596. area_shape_treansform.getOrigin() *= area_scale;
  597. gjk_input.m_transformA =
  598. area->get_transform__bullet() *
  599. area_shape_treansform;
  600. area_shape = static_cast<btConvexShape *>(area->get_bt_shape(y));
  601. // For each other object shape
  602. for (z = otherObject->get_shape_count() - 1; 0 <= z; --z) {
  603. other_body_shape = static_cast<btCollisionShape *>(otherObject->get_bt_shape(z));
  604. btTransform other_shape_transform(otherObject->get_bt_shape_transform(z));
  605. other_shape_transform.getOrigin() *= other_body_scale;
  606. gjk_input.m_transformB =
  607. otherObject->get_transform__bullet() *
  608. other_shape_transform;
  609. if (other_body_shape->isConvex()) {
  610. btPointCollector result;
  611. btGjkPairDetector gjk_pair_detector(
  612. area_shape,
  613. static_cast<btConvexShape *>(other_body_shape),
  614. gjk_simplex_solver,
  615. gjk_epa_pen_solver);
  616. gjk_pair_detector.getClosestPoints(gjk_input, result, 0);
  617. if (0 >= result.m_distance) {
  618. hasOverlap = true;
  619. goto collision_found;
  620. }
  621. } else {
  622. btCollisionObjectWrapper obA(NULL, area_shape, area->get_bt_ghost(), gjk_input.m_transformA, -1, y);
  623. btCollisionObjectWrapper obB(NULL, other_body_shape, otherObject->get_bt_collision_object(), gjk_input.m_transformB, -1, z);
  624. btCollisionAlgorithm *algorithm = dispatcher->findAlgorithm(&obA, &obB, NULL, BT_CONTACT_POINT_ALGORITHMS);
  625. if (!algorithm)
  626. continue;
  627. GodotDeepPenetrationContactResultCallback contactPointResult(&obA, &obB);
  628. algorithm->processCollision(&obA, &obB, dynamicsWorld->getDispatchInfo(), &contactPointResult);
  629. algorithm->~btCollisionAlgorithm();
  630. dispatcher->freeCollisionAlgorithm(algorithm);
  631. if (contactPointResult.hasHit()) {
  632. hasOverlap = true;
  633. goto collision_found;
  634. }
  635. }
  636. } // ~For each other object shape
  637. } // ~For each area shape
  638. collision_found:
  639. if (!hasOverlap)
  640. continue;
  641. indexOverlap = area->find_overlapping_object(otherObject);
  642. if (-1 == indexOverlap) {
  643. // Not found
  644. area->add_overlap(otherObject);
  645. } else {
  646. // Found
  647. area->put_overlap_as_inside(indexOverlap);
  648. }
  649. }
  650. /// 3. Remove not overlapping
  651. for (i = area->overlappingObjects.size() - 1; 0 <= i; --i) {
  652. // If the overlap has DIRTY state it means that it's no more overlapping
  653. if (area->overlappingObjects[i].state == AreaBullet::OVERLAP_STATE_DIRTY) {
  654. area->put_overlap_as_exit(i);
  655. }
  656. }
  657. }
  658. }
  659. void SpaceBullet::check_body_collision() {
  660. #ifdef DEBUG_ENABLED
  661. reset_debug_contact_count();
  662. #endif
  663. const int numManifolds = dynamicsWorld->getDispatcher()->getNumManifolds();
  664. for (int i = 0; i < numManifolds; ++i) {
  665. btPersistentManifold *contactManifold = dynamicsWorld->getDispatcher()->getManifoldByIndexInternal(i);
  666. // I know this static cast is a bit risky. But I'm checking its type just after it.
  667. // This allow me to avoid a lot of other cast and checks
  668. RigidBodyBullet *bodyA = static_cast<RigidBodyBullet *>(contactManifold->getBody0()->getUserPointer());
  669. RigidBodyBullet *bodyB = static_cast<RigidBodyBullet *>(contactManifold->getBody1()->getUserPointer());
  670. if (CollisionObjectBullet::TYPE_RIGID_BODY == bodyA->getType() && CollisionObjectBullet::TYPE_RIGID_BODY == bodyB->getType()) {
  671. if (!bodyA->can_add_collision() && !bodyB->can_add_collision()) {
  672. continue;
  673. }
  674. const int numContacts = contactManifold->getNumContacts();
  675. /// Since I don't need report all contacts for these objects,
  676. /// So report only the first
  677. #define REPORT_ALL_CONTACTS 0
  678. #if REPORT_ALL_CONTACTS
  679. for (int j = 0; j < numContacts; j++) {
  680. btManifoldPoint &pt = contactManifold->getContactPoint(j);
  681. #else
  682. if (numContacts) {
  683. btManifoldPoint &pt = contactManifold->getContactPoint(0);
  684. #endif
  685. if (
  686. pt.getDistance() <= 0.0 ||
  687. bodyA->was_colliding(bodyB) ||
  688. bodyB->was_colliding(bodyA)) {
  689. Vector3 collisionWorldPosition;
  690. Vector3 collisionLocalPosition;
  691. Vector3 normalOnB;
  692. float appliedImpulse = pt.m_appliedImpulse;
  693. B_TO_G(pt.m_normalWorldOnB, normalOnB);
  694. if (bodyA->can_add_collision()) {
  695. B_TO_G(pt.getPositionWorldOnB(), collisionWorldPosition);
  696. /// pt.m_localPointB Doesn't report the exact point in local space
  697. B_TO_G(pt.getPositionWorldOnB() - contactManifold->getBody1()->getWorldTransform().getOrigin(), collisionLocalPosition);
  698. bodyA->add_collision_object(bodyB, collisionWorldPosition, collisionLocalPosition, normalOnB, appliedImpulse, pt.m_index1, pt.m_index0);
  699. }
  700. if (bodyB->can_add_collision()) {
  701. B_TO_G(pt.getPositionWorldOnA(), collisionWorldPosition);
  702. /// pt.m_localPointA Doesn't report the exact point in local space
  703. B_TO_G(pt.getPositionWorldOnA() - contactManifold->getBody0()->getWorldTransform().getOrigin(), collisionLocalPosition);
  704. bodyB->add_collision_object(bodyA, collisionWorldPosition, collisionLocalPosition, normalOnB * -1, appliedImpulse * -1, pt.m_index0, pt.m_index1);
  705. }
  706. #ifdef DEBUG_ENABLED
  707. if (is_debugging_contacts()) {
  708. add_debug_contact(collisionWorldPosition);
  709. }
  710. #endif
  711. }
  712. }
  713. }
  714. }
  715. }
  716. void SpaceBullet::update_gravity() {
  717. btVector3 btGravity;
  718. G_TO_B(gravityDirection * gravityMagnitude, btGravity);
  719. //dynamicsWorld->setGravity(btGravity);
  720. dynamicsWorld->setGravity(btVector3(0, 0, 0));
  721. if (soft_body_world_info) {
  722. soft_body_world_info->m_gravity = btGravity;
  723. }
  724. }
  725. /// IMPORTANT: Please don't turn it ON this is not managed correctly!!
  726. /// I'm leaving this here just for future tests.
  727. /// Debug motion and normal vector drawing
  728. #define debug_test_motion 0
  729. #define RECOVERING_MOVEMENT_SCALE 0.4
  730. #define RECOVERING_MOVEMENT_CYCLES 4
  731. #if debug_test_motion
  732. #include "scene/3d/immediate_geometry.h"
  733. static ImmediateGeometry *motionVec(NULL);
  734. static ImmediateGeometry *normalLine(NULL);
  735. static Ref<SpatialMaterial> red_mat;
  736. static Ref<SpatialMaterial> blue_mat;
  737. #endif
  738. bool SpaceBullet::test_body_motion(RigidBodyBullet *p_body, const Transform &p_from, const Vector3 &p_motion, bool p_infinite_inertia, PhysicsServer::MotionResult *r_result, bool p_exclude_raycast_shapes) {
  739. #if debug_test_motion
  740. /// Yes I know this is not good, but I've used it as fast debugging hack.
  741. /// I'm leaving it here just for speedup the other eventual debugs
  742. if (!normalLine) {
  743. motionVec = memnew(ImmediateGeometry);
  744. normalLine = memnew(ImmediateGeometry);
  745. SceneTree::get_singleton()->get_current_scene()->add_child(motionVec);
  746. SceneTree::get_singleton()->get_current_scene()->add_child(normalLine);
  747. motionVec->set_as_toplevel(true);
  748. normalLine->set_as_toplevel(true);
  749. red_mat = Ref<SpatialMaterial>(memnew(SpatialMaterial));
  750. red_mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  751. red_mat->set_line_width(20.0);
  752. red_mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  753. red_mat->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  754. red_mat->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
  755. red_mat->set_albedo(Color(1, 0, 0, 1));
  756. motionVec->set_material_override(red_mat);
  757. blue_mat = Ref<SpatialMaterial>(memnew(SpatialMaterial));
  758. blue_mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  759. blue_mat->set_line_width(20.0);
  760. blue_mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  761. blue_mat->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  762. blue_mat->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
  763. blue_mat->set_albedo(Color(0, 0, 1, 1));
  764. normalLine->set_material_override(blue_mat);
  765. }
  766. #endif
  767. btTransform body_transform;
  768. G_TO_B(p_from, body_transform);
  769. UNSCALE_BT_BASIS(body_transform);
  770. btVector3 initial_recover_motion(0, 0, 0);
  771. { /// Phase one - multi shapes depenetration using margin
  772. for (int t(RECOVERING_MOVEMENT_CYCLES); 0 < t; --t) {
  773. if (!recover_from_penetration(p_body, body_transform, RECOVERING_MOVEMENT_SCALE, p_infinite_inertia, initial_recover_motion)) {
  774. break;
  775. }
  776. }
  777. // Add recover movement in order to make it safe
  778. body_transform.getOrigin() += initial_recover_motion;
  779. }
  780. btVector3 motion;
  781. G_TO_B(p_motion, motion);
  782. {
  783. // Phase two - sweep test, from a secure position without margin
  784. const int shape_count(p_body->get_shape_count());
  785. #if debug_test_motion
  786. Vector3 sup_line;
  787. B_TO_G(body_safe_position.getOrigin(), sup_line);
  788. motionVec->clear();
  789. motionVec->begin(Mesh::PRIMITIVE_LINES, NULL);
  790. motionVec->add_vertex(sup_line);
  791. motionVec->add_vertex(sup_line + p_motion * 10);
  792. motionVec->end();
  793. #endif
  794. for (int shIndex = 0; shIndex < shape_count; ++shIndex) {
  795. if (p_body->is_shape_disabled(shIndex)) {
  796. continue;
  797. }
  798. if (!p_body->get_bt_shape(shIndex)->isConvex()) {
  799. // Skip no convex shape
  800. continue;
  801. }
  802. if (p_exclude_raycast_shapes && p_body->get_bt_shape(shIndex)->getShapeType() == CUSTOM_CONVEX_SHAPE_TYPE) {
  803. // Skip rayshape in order to implement custom separation process
  804. continue;
  805. }
  806. btConvexShape *convex_shape_test(static_cast<btConvexShape *>(p_body->get_bt_shape(shIndex)));
  807. btTransform shape_world_from = body_transform * p_body->get_kinematic_utilities()->shapes[shIndex].transform;
  808. btTransform shape_world_to(shape_world_from);
  809. shape_world_to.getOrigin() += motion;
  810. if ((shape_world_to.getOrigin() - shape_world_from.getOrigin()).fuzzyZero()) {
  811. motion = btVector3(0, 0, 0);
  812. break;
  813. }
  814. GodotKinClosestConvexResultCallback btResult(shape_world_from.getOrigin(), shape_world_to.getOrigin(), p_body, p_infinite_inertia);
  815. btResult.m_collisionFilterGroup = p_body->get_collision_layer();
  816. btResult.m_collisionFilterMask = p_body->get_collision_mask();
  817. dynamicsWorld->convexSweepTest(convex_shape_test, shape_world_from, shape_world_to, btResult, dynamicsWorld->getDispatchInfo().m_allowedCcdPenetration);
  818. if (btResult.hasHit()) {
  819. /// Since for each sweep test I fix the motion of new shapes in base the recover result,
  820. /// if another shape will hit something it means that has a deepest penetration respect the previous shape
  821. motion *= btResult.m_closestHitFraction;
  822. }
  823. }
  824. body_transform.getOrigin() += motion;
  825. }
  826. bool has_penetration = false;
  827. { /// Phase three - contact test with margin
  828. btVector3 __rec(0, 0, 0);
  829. RecoverResult r_recover_result;
  830. has_penetration = recover_from_penetration(p_body, body_transform, 1, p_infinite_inertia, __rec, &r_recover_result);
  831. // Parse results
  832. if (r_result) {
  833. B_TO_G(motion + initial_recover_motion + __rec, r_result->motion);
  834. if (has_penetration) {
  835. const btRigidBody *btRigid = static_cast<const btRigidBody *>(r_recover_result.other_collision_object);
  836. CollisionObjectBullet *collisionObject = static_cast<CollisionObjectBullet *>(btRigid->getUserPointer());
  837. B_TO_G(motion, r_result->remainder); // is the remaining movements
  838. r_result->remainder = p_motion - r_result->remainder;
  839. B_TO_G(r_recover_result.pointWorld, r_result->collision_point);
  840. B_TO_G(r_recover_result.normal, r_result->collision_normal);
  841. B_TO_G(btRigid->getVelocityInLocalPoint(r_recover_result.pointWorld - btRigid->getWorldTransform().getOrigin()), r_result->collider_velocity); // It calculates velocity at point and assign it using special function Bullet_to_Godot
  842. r_result->collider = collisionObject->get_self();
  843. r_result->collider_id = collisionObject->get_instance_id();
  844. r_result->collider_shape = r_recover_result.other_compound_shape_index;
  845. r_result->collision_local_shape = r_recover_result.local_shape_most_recovered;
  846. #if debug_test_motion
  847. Vector3 sup_line2;
  848. B_TO_G(motion, sup_line2);
  849. normalLine->clear();
  850. normalLine->begin(Mesh::PRIMITIVE_LINES, NULL);
  851. normalLine->add_vertex(r_result->collision_point);
  852. normalLine->add_vertex(r_result->collision_point + r_result->collision_normal * 10);
  853. normalLine->end();
  854. #endif
  855. } else {
  856. r_result->remainder = Vector3();
  857. }
  858. }
  859. }
  860. return has_penetration;
  861. }
  862. int SpaceBullet::test_ray_separation(RigidBodyBullet *p_body, const Transform &p_transform, bool p_infinite_inertia, Vector3 &r_recover_motion, PhysicsServer::SeparationResult *r_results, int p_result_max, float p_margin) {
  863. btTransform body_transform;
  864. G_TO_B(p_transform, body_transform);
  865. UNSCALE_BT_BASIS(body_transform);
  866. btVector3 recover_motion(0, 0, 0);
  867. int rays_found = 0;
  868. int rays_found_this_round = 0;
  869. for (int t(RECOVERING_MOVEMENT_CYCLES); 0 < t; --t) {
  870. PhysicsServer::SeparationResult *next_results = &r_results[rays_found];
  871. rays_found_this_round = recover_from_penetration_ray(p_body, body_transform, RECOVERING_MOVEMENT_SCALE, p_infinite_inertia, p_result_max - rays_found, recover_motion, next_results);
  872. rays_found += rays_found_this_round;
  873. if (rays_found_this_round == 0) {
  874. body_transform.getOrigin() += recover_motion;
  875. break;
  876. }
  877. }
  878. B_TO_G(recover_motion, r_recover_motion);
  879. return rays_found;
  880. }
  881. struct RecoverPenetrationBroadPhaseCallback : public btBroadphaseAabbCallback {
  882. private:
  883. btDbvtVolume bounds;
  884. const btCollisionObject *self_collision_object;
  885. uint32_t collision_layer;
  886. uint32_t collision_mask;
  887. struct CompoundLeafCallback : btDbvt::ICollide {
  888. private:
  889. RecoverPenetrationBroadPhaseCallback *parent_callback;
  890. btCollisionObject *collision_object;
  891. public:
  892. CompoundLeafCallback(RecoverPenetrationBroadPhaseCallback *p_parent_callback, btCollisionObject *p_collision_object) :
  893. parent_callback(p_parent_callback),
  894. collision_object(p_collision_object) {
  895. }
  896. void Process(const btDbvtNode *leaf) {
  897. BroadphaseResult result;
  898. result.collision_object = collision_object;
  899. result.compound_child_index = leaf->dataAsInt;
  900. parent_callback->results.push_back(result);
  901. }
  902. };
  903. public:
  904. struct BroadphaseResult {
  905. btCollisionObject *collision_object;
  906. int compound_child_index;
  907. };
  908. Vector<BroadphaseResult> results;
  909. public:
  910. RecoverPenetrationBroadPhaseCallback(const btCollisionObject *p_self_collision_object, uint32_t p_collision_layer, uint32_t p_collision_mask, btVector3 p_aabb_min, btVector3 p_aabb_max) :
  911. self_collision_object(p_self_collision_object),
  912. collision_layer(p_collision_layer),
  913. collision_mask(p_collision_mask) {
  914. bounds = btDbvtVolume::FromMM(p_aabb_min, p_aabb_max);
  915. }
  916. virtual ~RecoverPenetrationBroadPhaseCallback() {}
  917. virtual bool process(const btBroadphaseProxy *proxy) {
  918. btCollisionObject *co = static_cast<btCollisionObject *>(proxy->m_clientObject);
  919. if (co->getInternalType() <= btCollisionObject::CO_RIGID_BODY) {
  920. if (self_collision_object != proxy->m_clientObject && GodotFilterCallback::test_collision_filters(collision_layer, collision_mask, proxy->m_collisionFilterGroup, proxy->m_collisionFilterMask)) {
  921. if (co->getCollisionShape()->isCompound()) {
  922. const btCompoundShape *cs = static_cast<btCompoundShape *>(co->getCollisionShape());
  923. if (cs->getNumChildShapes() > 1) {
  924. const btDbvt *tree = cs->getDynamicAabbTree();
  925. ERR_FAIL_COND_V(tree == NULL, true);
  926. // Transform bounds into compound shape local space
  927. const btTransform other_in_compound_space = co->getWorldTransform().inverse();
  928. const btMatrix3x3 abs_b = other_in_compound_space.getBasis().absolute();
  929. const btVector3 local_center = other_in_compound_space(bounds.Center());
  930. const btVector3 local_extent = bounds.Extents().dot3(abs_b[0], abs_b[1], abs_b[2]);
  931. const btVector3 local_aabb_min = local_center - local_extent;
  932. const btVector3 local_aabb_max = local_center + local_extent;
  933. const btDbvtVolume local_bounds = btDbvtVolume::FromMM(local_aabb_min, local_aabb_max);
  934. // Test collision against compound child shapes using its AABB tree
  935. CompoundLeafCallback compound_leaf_callback(this, co);
  936. tree->collideTV(tree->m_root, local_bounds, compound_leaf_callback);
  937. } else {
  938. // If there's only a single child shape then there's no need to search any more, we know which child overlaps
  939. BroadphaseResult result;
  940. result.collision_object = co;
  941. result.compound_child_index = 0;
  942. results.push_back(result);
  943. }
  944. } else {
  945. BroadphaseResult result;
  946. result.collision_object = co;
  947. result.compound_child_index = -1;
  948. results.push_back(result);
  949. }
  950. return true;
  951. }
  952. }
  953. return false;
  954. }
  955. };
  956. bool SpaceBullet::recover_from_penetration(RigidBodyBullet *p_body, const btTransform &p_body_position, btScalar p_recover_movement_scale, bool p_infinite_inertia, btVector3 &r_delta_recover_movement, RecoverResult *r_recover_result) {
  957. // Calculate the cumulative AABB of all shapes of the kinematic body
  958. btVector3 aabb_min, aabb_max;
  959. bool shapes_found = false;
  960. for (int kinIndex = p_body->get_kinematic_utilities()->shapes.size() - 1; 0 <= kinIndex; --kinIndex) {
  961. const RigidBodyBullet::KinematicShape &kin_shape(p_body->get_kinematic_utilities()->shapes[kinIndex]);
  962. if (!kin_shape.is_active()) {
  963. continue;
  964. }
  965. if (kin_shape.shape->getShapeType() == CUSTOM_CONVEX_SHAPE_TYPE) {
  966. // Skip rayshape in order to implement custom separation process
  967. continue;
  968. }
  969. btTransform shape_transform = p_body_position * kin_shape.transform;
  970. shape_transform.getOrigin() += r_delta_recover_movement;
  971. btVector3 shape_aabb_min, shape_aabb_max;
  972. kin_shape.shape->getAabb(shape_transform, shape_aabb_min, shape_aabb_max);
  973. if (!shapes_found) {
  974. aabb_min = shape_aabb_min;
  975. aabb_max = shape_aabb_max;
  976. shapes_found = true;
  977. } else {
  978. aabb_min.setX((aabb_min.x() < shape_aabb_min.x()) ? aabb_min.x() : shape_aabb_min.x());
  979. aabb_min.setY((aabb_min.y() < shape_aabb_min.y()) ? aabb_min.y() : shape_aabb_min.y());
  980. aabb_min.setZ((aabb_min.z() < shape_aabb_min.z()) ? aabb_min.z() : shape_aabb_min.z());
  981. aabb_max.setX((aabb_max.x() > shape_aabb_max.x()) ? aabb_max.x() : shape_aabb_max.x());
  982. aabb_max.setY((aabb_max.y() > shape_aabb_max.y()) ? aabb_max.y() : shape_aabb_max.y());
  983. aabb_max.setZ((aabb_max.z() > shape_aabb_max.z()) ? aabb_max.z() : shape_aabb_max.z());
  984. }
  985. }
  986. // If there are no shapes then there is no penetration either
  987. if (!shapes_found) {
  988. return false;
  989. }
  990. // Perform broadphase test
  991. RecoverPenetrationBroadPhaseCallback recover_broad_result(p_body->get_bt_collision_object(), p_body->get_collision_layer(), p_body->get_collision_mask(), aabb_min, aabb_max);
  992. dynamicsWorld->getBroadphase()->aabbTest(aabb_min, aabb_max, recover_broad_result);
  993. bool penetration = false;
  994. // Perform narrowphase per shape
  995. for (int kinIndex = p_body->get_kinematic_utilities()->shapes.size() - 1; 0 <= kinIndex; --kinIndex) {
  996. const RigidBodyBullet::KinematicShape &kin_shape(p_body->get_kinematic_utilities()->shapes[kinIndex]);
  997. if (!kin_shape.is_active()) {
  998. continue;
  999. }
  1000. if (kin_shape.shape->getShapeType() == CUSTOM_CONVEX_SHAPE_TYPE) {
  1001. // Skip rayshape in order to implement custom separation process
  1002. continue;
  1003. }
  1004. btTransform shape_transform = p_body_position * kin_shape.transform;
  1005. shape_transform.getOrigin() += r_delta_recover_movement;
  1006. for (int i = recover_broad_result.results.size() - 1; 0 <= i; --i) {
  1007. btCollisionObject *otherObject = recover_broad_result.results[i].collision_object;
  1008. if (p_infinite_inertia && !otherObject->isStaticOrKinematicObject()) {
  1009. otherObject->activate(); // Force activation of hitten rigid, soft body
  1010. continue;
  1011. } else if (!p_body->get_bt_collision_object()->checkCollideWith(otherObject) || !otherObject->checkCollideWith(p_body->get_bt_collision_object()))
  1012. continue;
  1013. if (otherObject->getCollisionShape()->isCompound()) {
  1014. const btCompoundShape *cs = static_cast<const btCompoundShape *>(otherObject->getCollisionShape());
  1015. int shape_idx = recover_broad_result.results[i].compound_child_index;
  1016. ERR_FAIL_COND_V(shape_idx < 0 || shape_idx >= cs->getNumChildShapes(), false);
  1017. if (cs->getChildShape(shape_idx)->isConvex()) {
  1018. if (RFP_convex_convex_test(kin_shape.shape, static_cast<const btConvexShape *>(cs->getChildShape(shape_idx)), otherObject, kinIndex, shape_idx, shape_transform, otherObject->getWorldTransform() * cs->getChildTransform(shape_idx), p_recover_movement_scale, r_delta_recover_movement, r_recover_result)) {
  1019. penetration = true;
  1020. }
  1021. } else {
  1022. if (RFP_convex_world_test(kin_shape.shape, cs->getChildShape(shape_idx), p_body->get_bt_collision_object(), otherObject, kinIndex, shape_idx, shape_transform, otherObject->getWorldTransform() * cs->getChildTransform(shape_idx), p_recover_movement_scale, r_delta_recover_movement, r_recover_result)) {
  1023. penetration = true;
  1024. }
  1025. }
  1026. } else if (otherObject->getCollisionShape()->isConvex()) { /// Execute GJK test against object shape
  1027. if (RFP_convex_convex_test(kin_shape.shape, static_cast<const btConvexShape *>(otherObject->getCollisionShape()), otherObject, kinIndex, 0, shape_transform, otherObject->getWorldTransform(), p_recover_movement_scale, r_delta_recover_movement, r_recover_result)) {
  1028. penetration = true;
  1029. }
  1030. } else {
  1031. if (RFP_convex_world_test(kin_shape.shape, otherObject->getCollisionShape(), p_body->get_bt_collision_object(), otherObject, kinIndex, 0, shape_transform, otherObject->getWorldTransform(), p_recover_movement_scale, r_delta_recover_movement, r_recover_result)) {
  1032. penetration = true;
  1033. }
  1034. }
  1035. }
  1036. }
  1037. return penetration;
  1038. }
  1039. bool SpaceBullet::RFP_convex_convex_test(const btConvexShape *p_shapeA, const btConvexShape *p_shapeB, btCollisionObject *p_objectB, int p_shapeId_A, int p_shapeId_B, const btTransform &p_transformA, const btTransform &p_transformB, btScalar p_recover_movement_scale, btVector3 &r_delta_recover_movement, RecoverResult *r_recover_result) {
  1040. // Initialize GJK input
  1041. btGjkPairDetector::ClosestPointInput gjk_input;
  1042. gjk_input.m_transformA = p_transformA;
  1043. gjk_input.m_transformB = p_transformB;
  1044. // Perform GJK test
  1045. btPointCollector result;
  1046. btGjkPairDetector gjk_pair_detector(p_shapeA, p_shapeB, gjk_simplex_solver, gjk_epa_pen_solver);
  1047. gjk_pair_detector.getClosestPoints(gjk_input, result, 0);
  1048. if (0 > result.m_distance) {
  1049. // Has penetration
  1050. r_delta_recover_movement += result.m_normalOnBInWorld * (result.m_distance * -1 * p_recover_movement_scale);
  1051. if (r_recover_result) {
  1052. if (result.m_distance < r_recover_result->penetration_distance) {
  1053. r_recover_result->hasPenetration = true;
  1054. r_recover_result->local_shape_most_recovered = p_shapeId_A;
  1055. r_recover_result->other_collision_object = p_objectB;
  1056. r_recover_result->other_compound_shape_index = p_shapeId_B;
  1057. r_recover_result->penetration_distance = result.m_distance;
  1058. r_recover_result->pointWorld = result.m_pointInWorld;
  1059. r_recover_result->normal = result.m_normalOnBInWorld;
  1060. }
  1061. }
  1062. return true;
  1063. }
  1064. return false;
  1065. }
  1066. bool SpaceBullet::RFP_convex_world_test(const btConvexShape *p_shapeA, const btCollisionShape *p_shapeB, btCollisionObject *p_objectA, btCollisionObject *p_objectB, int p_shapeId_A, int p_shapeId_B, const btTransform &p_transformA, const btTransform &p_transformB, btScalar p_recover_movement_scale, btVector3 &r_delta_recover_movement, RecoverResult *r_recover_result) {
  1067. /// Contact test
  1068. btTransform tA(p_transformA);
  1069. btCollisionObjectWrapper obA(NULL, p_shapeA, p_objectA, tA, -1, p_shapeId_A);
  1070. btCollisionObjectWrapper obB(NULL, p_shapeB, p_objectB, p_transformB, -1, p_shapeId_B);
  1071. btCollisionAlgorithm *algorithm = dispatcher->findAlgorithm(&obA, &obB, NULL, BT_CONTACT_POINT_ALGORITHMS);
  1072. if (algorithm) {
  1073. GodotDeepPenetrationContactResultCallback contactPointResult(&obA, &obB);
  1074. //discrete collision detection query
  1075. algorithm->processCollision(&obA, &obB, dynamicsWorld->getDispatchInfo(), &contactPointResult);
  1076. algorithm->~btCollisionAlgorithm();
  1077. dispatcher->freeCollisionAlgorithm(algorithm);
  1078. if (contactPointResult.hasHit()) {
  1079. r_delta_recover_movement += contactPointResult.m_pointNormalWorld * (contactPointResult.m_penetration_distance * -1 * p_recover_movement_scale);
  1080. if (r_recover_result) {
  1081. if (contactPointResult.m_penetration_distance < r_recover_result->penetration_distance) {
  1082. r_recover_result->hasPenetration = true;
  1083. r_recover_result->local_shape_most_recovered = p_shapeId_A;
  1084. r_recover_result->other_collision_object = p_objectB;
  1085. r_recover_result->other_compound_shape_index = p_shapeId_B;
  1086. r_recover_result->penetration_distance = contactPointResult.m_penetration_distance;
  1087. r_recover_result->pointWorld = contactPointResult.m_pointWorld;
  1088. r_recover_result->normal = contactPointResult.m_pointNormalWorld;
  1089. }
  1090. }
  1091. return true;
  1092. }
  1093. }
  1094. return false;
  1095. }
  1096. int SpaceBullet::add_separation_result(PhysicsServer::SeparationResult *r_result, const SpaceBullet::RecoverResult &p_recover_result, int p_shape_id, const btCollisionObject *p_other_object) const {
  1097. // optimize results (ignore non-colliding)
  1098. if (p_recover_result.penetration_distance < 0.0) {
  1099. const btRigidBody *btRigid = static_cast<const btRigidBody *>(p_other_object);
  1100. CollisionObjectBullet *collisionObject = static_cast<CollisionObjectBullet *>(p_other_object->getUserPointer());
  1101. r_result->collision_depth = p_recover_result.penetration_distance;
  1102. B_TO_G(p_recover_result.pointWorld, r_result->collision_point);
  1103. B_TO_G(p_recover_result.normal, r_result->collision_normal);
  1104. B_TO_G(btRigid->getVelocityInLocalPoint(p_recover_result.pointWorld - btRigid->getWorldTransform().getOrigin()), r_result->collider_velocity);
  1105. r_result->collision_local_shape = p_shape_id;
  1106. r_result->collider_id = collisionObject->get_instance_id();
  1107. r_result->collider = collisionObject->get_self();
  1108. r_result->collider_shape = p_recover_result.other_compound_shape_index;
  1109. return 1;
  1110. } else {
  1111. return 0;
  1112. }
  1113. }
  1114. int SpaceBullet::recover_from_penetration_ray(RigidBodyBullet *p_body, const btTransform &p_body_position, btScalar p_recover_movement_scale, bool p_infinite_inertia, int p_result_max, btVector3 &r_delta_recover_movement, PhysicsServer::SeparationResult *r_results) {
  1115. // Calculate the cumulative AABB of all shapes of the kinematic body
  1116. btVector3 aabb_min, aabb_max;
  1117. bool shapes_found = false;
  1118. for (int kinIndex = p_body->get_kinematic_utilities()->shapes.size() - 1; 0 <= kinIndex; --kinIndex) {
  1119. const RigidBodyBullet::KinematicShape &kin_shape(p_body->get_kinematic_utilities()->shapes[kinIndex]);
  1120. if (!kin_shape.is_active()) {
  1121. continue;
  1122. }
  1123. if (kin_shape.shape->getShapeType() != CUSTOM_CONVEX_SHAPE_TYPE) {
  1124. continue;
  1125. }
  1126. btTransform shape_transform = p_body_position * kin_shape.transform;
  1127. shape_transform.getOrigin() += r_delta_recover_movement;
  1128. btVector3 shape_aabb_min, shape_aabb_max;
  1129. kin_shape.shape->getAabb(shape_transform, shape_aabb_min, shape_aabb_max);
  1130. if (!shapes_found) {
  1131. aabb_min = shape_aabb_min;
  1132. aabb_max = shape_aabb_max;
  1133. shapes_found = true;
  1134. } else {
  1135. aabb_min.setX((aabb_min.x() < shape_aabb_min.x()) ? aabb_min.x() : shape_aabb_min.x());
  1136. aabb_min.setY((aabb_min.y() < shape_aabb_min.y()) ? aabb_min.y() : shape_aabb_min.y());
  1137. aabb_min.setZ((aabb_min.z() < shape_aabb_min.z()) ? aabb_min.z() : shape_aabb_min.z());
  1138. aabb_max.setX((aabb_max.x() > shape_aabb_max.x()) ? aabb_max.x() : shape_aabb_max.x());
  1139. aabb_max.setY((aabb_max.y() > shape_aabb_max.y()) ? aabb_max.y() : shape_aabb_max.y());
  1140. aabb_max.setZ((aabb_max.z() > shape_aabb_max.z()) ? aabb_max.z() : shape_aabb_max.z());
  1141. }
  1142. }
  1143. // If there are no shapes then there is no penetration either
  1144. if (!shapes_found) {
  1145. return 0;
  1146. }
  1147. // Perform broadphase test
  1148. RecoverPenetrationBroadPhaseCallback recover_broad_result(p_body->get_bt_collision_object(), p_body->get_collision_layer(), p_body->get_collision_mask(), aabb_min, aabb_max);
  1149. dynamicsWorld->getBroadphase()->aabbTest(aabb_min, aabb_max, recover_broad_result);
  1150. int ray_count = 0;
  1151. // Perform narrowphase per shape
  1152. for (int kinIndex = p_body->get_kinematic_utilities()->shapes.size() - 1; 0 <= kinIndex; --kinIndex) {
  1153. if (ray_count >= p_result_max) {
  1154. break;
  1155. }
  1156. const RigidBodyBullet::KinematicShape &kin_shape(p_body->get_kinematic_utilities()->shapes[kinIndex]);
  1157. if (!kin_shape.is_active()) {
  1158. continue;
  1159. }
  1160. if (kin_shape.shape->getShapeType() != CUSTOM_CONVEX_SHAPE_TYPE) {
  1161. continue;
  1162. }
  1163. btTransform shape_transform = p_body_position * kin_shape.transform;
  1164. shape_transform.getOrigin() += r_delta_recover_movement;
  1165. for (int i = recover_broad_result.results.size() - 1; 0 <= i; --i) {
  1166. btCollisionObject *otherObject = recover_broad_result.results[i].collision_object;
  1167. if (p_infinite_inertia && !otherObject->isStaticOrKinematicObject()) {
  1168. otherObject->activate(); // Force activation of hitten rigid, soft body
  1169. continue;
  1170. } else if (!p_body->get_bt_collision_object()->checkCollideWith(otherObject) || !otherObject->checkCollideWith(p_body->get_bt_collision_object()))
  1171. continue;
  1172. if (otherObject->getCollisionShape()->isCompound()) {
  1173. const btCompoundShape *cs = static_cast<const btCompoundShape *>(otherObject->getCollisionShape());
  1174. int shape_idx = recover_broad_result.results[i].compound_child_index;
  1175. ERR_FAIL_COND_V(shape_idx < 0 || shape_idx >= cs->getNumChildShapes(), false);
  1176. RecoverResult recover_result;
  1177. if (RFP_convex_world_test(kin_shape.shape, cs->getChildShape(shape_idx), p_body->get_bt_collision_object(), otherObject, kinIndex, shape_idx, shape_transform, otherObject->getWorldTransform() * cs->getChildTransform(shape_idx), p_recover_movement_scale, r_delta_recover_movement, &recover_result)) {
  1178. ray_count = add_separation_result(&r_results[ray_count], recover_result, kinIndex, otherObject);
  1179. }
  1180. } else {
  1181. RecoverResult recover_result;
  1182. if (RFP_convex_world_test(kin_shape.shape, otherObject->getCollisionShape(), p_body->get_bt_collision_object(), otherObject, kinIndex, 0, shape_transform, otherObject->getWorldTransform(), p_recover_movement_scale, r_delta_recover_movement, &recover_result)) {
  1183. ray_count = add_separation_result(&r_results[ray_count], recover_result, kinIndex, otherObject);
  1184. }
  1185. }
  1186. }
  1187. }
  1188. return ray_count;
  1189. }