space_bullet.cpp 58 KB

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