space_bullet.cpp 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474
  1. /**************************************************************************/
  2. /* space_bullet.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  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. }
  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 = 0 == r_result.collider_id ? 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, 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) {
  105. if (p_result_max <= 0) {
  106. return 0;
  107. }
  108. ShapeBullet *shape = space->get_physics_server()->get_shape_owner()->get(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, 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) {
  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()->get(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, 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) {
  184. if (p_result_max <= 0) {
  185. return false;
  186. }
  187. ShapeBullet *shape = space->get_physics_server()->get_shape_owner()->get(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, 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) {
  212. ShapeBullet *shape = space->get_physics_server()->get_shape_owner()->get(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. broadphase(nullptr),
  284. collisionConfiguration(nullptr),
  285. dispatcher(nullptr),
  286. solver(nullptr),
  287. dynamicsWorld(nullptr),
  288. soft_body_world_info(nullptr),
  289. ghostPairCallback(nullptr),
  290. godotFilterCallback(nullptr),
  291. gravityDirection(0, -1, 0),
  292. gravityMagnitude(10),
  293. linear_damp(0.0),
  294. angular_damp(0.0),
  295. contactDebugCount(0),
  296. delta_time(0.) {
  297. create_empty_world(GLOBAL_DEF("physics/3d/active_soft_world", true));
  298. direct_access = memnew(BulletPhysicsDirectSpaceState(this));
  299. }
  300. SpaceBullet::~SpaceBullet() {
  301. memdelete(direct_access);
  302. destroy_world();
  303. }
  304. void SpaceBullet::flush_queries() {
  305. const btCollisionObjectArray &colObjArray = dynamicsWorld->getCollisionObjectArray();
  306. for (int i = colObjArray.size() - 1; 0 <= i; --i) {
  307. static_cast<CollisionObjectBullet *>(colObjArray[i]->getUserPointer())->dispatch_callbacks();
  308. }
  309. }
  310. void SpaceBullet::step(real_t p_delta_time) {
  311. delta_time = p_delta_time;
  312. dynamicsWorld->stepSimulation(p_delta_time, 0, 0);
  313. }
  314. void SpaceBullet::set_param(PhysicsServer::AreaParameter p_param, const Variant &p_value) {
  315. assert(dynamicsWorld);
  316. switch (p_param) {
  317. case PhysicsServer::AREA_PARAM_GRAVITY:
  318. gravityMagnitude = p_value;
  319. update_gravity();
  320. break;
  321. case PhysicsServer::AREA_PARAM_GRAVITY_VECTOR:
  322. gravityDirection = p_value;
  323. update_gravity();
  324. break;
  325. case PhysicsServer::AREA_PARAM_LINEAR_DAMP:
  326. linear_damp = p_value;
  327. break;
  328. case PhysicsServer::AREA_PARAM_ANGULAR_DAMP:
  329. angular_damp = p_value;
  330. break;
  331. case PhysicsServer::AREA_PARAM_PRIORITY:
  332. // Priority is always 0, the lower
  333. break;
  334. case PhysicsServer::AREA_PARAM_GRAVITY_IS_POINT:
  335. case PhysicsServer::AREA_PARAM_GRAVITY_DISTANCE_SCALE:
  336. case PhysicsServer::AREA_PARAM_GRAVITY_POINT_ATTENUATION:
  337. break;
  338. default:
  339. WARN_PRINT("This set parameter (" + itos(p_param) + ") is ignored, the SpaceBullet doesn't support it.");
  340. break;
  341. }
  342. }
  343. Variant SpaceBullet::get_param(PhysicsServer::AreaParameter p_param) {
  344. switch (p_param) {
  345. case PhysicsServer::AREA_PARAM_GRAVITY:
  346. return gravityMagnitude;
  347. case PhysicsServer::AREA_PARAM_GRAVITY_VECTOR:
  348. return gravityDirection;
  349. case PhysicsServer::AREA_PARAM_LINEAR_DAMP:
  350. return linear_damp;
  351. case PhysicsServer::AREA_PARAM_ANGULAR_DAMP:
  352. return angular_damp;
  353. case PhysicsServer::AREA_PARAM_PRIORITY:
  354. return 0; // Priority is always 0, the lower
  355. case PhysicsServer::AREA_PARAM_GRAVITY_IS_POINT:
  356. return false;
  357. case PhysicsServer::AREA_PARAM_GRAVITY_DISTANCE_SCALE:
  358. return 0;
  359. case PhysicsServer::AREA_PARAM_GRAVITY_POINT_ATTENUATION:
  360. return 0;
  361. default:
  362. WARN_PRINT("This get parameter (" + itos(p_param) + ") is ignored, the SpaceBullet doesn't support it.");
  363. return Variant();
  364. }
  365. }
  366. void SpaceBullet::set_param(PhysicsServer::SpaceParameter p_param, real_t p_value) {
  367. switch (p_param) {
  368. case PhysicsServer::SPACE_PARAM_CONTACT_RECYCLE_RADIUS:
  369. case PhysicsServer::SPACE_PARAM_CONTACT_MAX_SEPARATION:
  370. case PhysicsServer::SPACE_PARAM_BODY_MAX_ALLOWED_PENETRATION:
  371. case PhysicsServer::SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_THRESHOLD:
  372. case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_THRESHOLD:
  373. case PhysicsServer::SPACE_PARAM_BODY_TIME_TO_SLEEP:
  374. case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_DAMP_RATIO:
  375. case PhysicsServer::SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS:
  376. default:
  377. WARN_PRINT("This set parameter (" + itos(p_param) + ") is ignored, the SpaceBullet doesn't support it.");
  378. break;
  379. }
  380. }
  381. real_t SpaceBullet::get_param(PhysicsServer::SpaceParameter p_param) {
  382. switch (p_param) {
  383. case PhysicsServer::SPACE_PARAM_CONTACT_RECYCLE_RADIUS:
  384. case PhysicsServer::SPACE_PARAM_CONTACT_MAX_SEPARATION:
  385. case PhysicsServer::SPACE_PARAM_BODY_MAX_ALLOWED_PENETRATION:
  386. case PhysicsServer::SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_THRESHOLD:
  387. case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_THRESHOLD:
  388. case PhysicsServer::SPACE_PARAM_BODY_TIME_TO_SLEEP:
  389. case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_DAMP_RATIO:
  390. case PhysicsServer::SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS:
  391. default:
  392. WARN_PRINT("The SpaceBullet doesn't support this get parameter (" + itos(p_param) + "), 0 is returned.");
  393. return 0.f;
  394. }
  395. }
  396. void SpaceBullet::add_area(AreaBullet *p_area) {
  397. areas.push_back(p_area);
  398. dynamicsWorld->addCollisionObject(p_area->get_bt_ghost(), p_area->get_collision_layer(), p_area->get_collision_mask());
  399. }
  400. void SpaceBullet::remove_area(AreaBullet *p_area) {
  401. areas.erase(p_area);
  402. dynamicsWorld->removeCollisionObject(p_area->get_bt_ghost());
  403. }
  404. void SpaceBullet::reload_collision_filters(AreaBullet *p_area) {
  405. btGhostObject *ghost_object = p_area->get_bt_ghost();
  406. btBroadphaseProxy *ghost_proxy = ghost_object->getBroadphaseHandle();
  407. ghost_proxy->m_collisionFilterGroup = p_area->get_collision_layer();
  408. ghost_proxy->m_collisionFilterMask = p_area->get_collision_mask();
  409. dynamicsWorld->refreshBroadphaseProxy(ghost_object);
  410. }
  411. void SpaceBullet::add_rigid_body(RigidBodyBullet *p_body) {
  412. if (p_body->is_static()) {
  413. dynamicsWorld->addCollisionObject(p_body->get_bt_rigid_body(), p_body->get_collision_layer(), p_body->get_collision_mask());
  414. } else {
  415. dynamicsWorld->addRigidBody(p_body->get_bt_rigid_body(), p_body->get_collision_layer(), p_body->get_collision_mask());
  416. p_body->scratch_space_override_modificator();
  417. }
  418. }
  419. void SpaceBullet::remove_rigid_body_constraints(RigidBodyBullet *p_body) {
  420. btRigidBody *btBody = p_body->get_bt_rigid_body();
  421. int constraints = btBody->getNumConstraintRefs();
  422. if (constraints > 0) {
  423. ERR_PRINT("A body connected to joints was removed.");
  424. for (int i = 0; i < constraints; i++) {
  425. dynamicsWorld->removeConstraint(btBody->getConstraintRef(i));
  426. }
  427. }
  428. }
  429. void SpaceBullet::remove_rigid_body(RigidBodyBullet *p_body) {
  430. btRigidBody *btBody = p_body->get_bt_rigid_body();
  431. if (p_body->is_static()) {
  432. dynamicsWorld->removeCollisionObject(btBody);
  433. } else {
  434. dynamicsWorld->removeRigidBody(btBody);
  435. }
  436. }
  437. void SpaceBullet::reload_collision_filters(RigidBodyBullet *p_body) {
  438. btRigidBody *rigid_body = p_body->get_bt_rigid_body();
  439. btBroadphaseProxy *body_proxy = rigid_body->getBroadphaseProxy();
  440. body_proxy->m_collisionFilterGroup = p_body->get_collision_layer();
  441. body_proxy->m_collisionFilterMask = p_body->get_collision_mask();
  442. dynamicsWorld->refreshBroadphaseProxy(rigid_body);
  443. }
  444. void SpaceBullet::add_soft_body(SoftBodyBullet *p_body) {
  445. if (is_using_soft_world()) {
  446. if (p_body->get_bt_soft_body()) {
  447. p_body->get_bt_soft_body()->m_worldInfo = get_soft_body_world_info();
  448. static_cast<btSoftRigidDynamicsWorld *>(dynamicsWorld)->addSoftBody(p_body->get_bt_soft_body(), p_body->get_collision_layer(), p_body->get_collision_mask());
  449. }
  450. } else {
  451. ERR_PRINT("This soft body can't be added to non soft world");
  452. }
  453. }
  454. void SpaceBullet::remove_soft_body(SoftBodyBullet *p_body) {
  455. if (is_using_soft_world()) {
  456. if (p_body->get_bt_soft_body()) {
  457. static_cast<btSoftRigidDynamicsWorld *>(dynamicsWorld)->removeSoftBody(p_body->get_bt_soft_body());
  458. p_body->get_bt_soft_body()->m_worldInfo = nullptr;
  459. }
  460. }
  461. }
  462. void SpaceBullet::reload_collision_filters(SoftBodyBullet *p_body) {
  463. // This is necessary to change collision filter
  464. remove_soft_body(p_body);
  465. add_soft_body(p_body);
  466. }
  467. void SpaceBullet::add_constraint(ConstraintBullet *p_constraint, bool disableCollisionsBetweenLinkedBodies) {
  468. p_constraint->set_space(this);
  469. dynamicsWorld->addConstraint(p_constraint->get_bt_constraint(), disableCollisionsBetweenLinkedBodies);
  470. }
  471. void SpaceBullet::remove_constraint(ConstraintBullet *p_constraint) {
  472. dynamicsWorld->removeConstraint(p_constraint->get_bt_constraint());
  473. }
  474. int SpaceBullet::get_num_collision_objects() const {
  475. return dynamicsWorld->getNumCollisionObjects();
  476. }
  477. void SpaceBullet::remove_all_collision_objects() {
  478. for (int i = dynamicsWorld->getNumCollisionObjects() - 1; 0 <= i; --i) {
  479. btCollisionObject *btObj = dynamicsWorld->getCollisionObjectArray()[i];
  480. CollisionObjectBullet *colObj = static_cast<CollisionObjectBullet *>(btObj->getUserPointer());
  481. colObj->set_space(nullptr);
  482. }
  483. }
  484. void onBulletPreTickCallback(btDynamicsWorld *p_dynamicsWorld, btScalar timeStep) {
  485. static_cast<SpaceBullet *>(p_dynamicsWorld->getWorldUserInfo())->flush_queries();
  486. }
  487. void onBulletTickCallback(btDynamicsWorld *p_dynamicsWorld, btScalar timeStep) {
  488. const btCollisionObjectArray &colObjArray = p_dynamicsWorld->getCollisionObjectArray();
  489. // Notify all Collision objects the collision checker is started
  490. for (int i = colObjArray.size() - 1; 0 <= i; --i) {
  491. static_cast<CollisionObjectBullet *>(colObjArray[i]->getUserPointer())->on_collision_checker_start();
  492. }
  493. SpaceBullet *sb = static_cast<SpaceBullet *>(p_dynamicsWorld->getWorldUserInfo());
  494. sb->check_ghost_overlaps();
  495. sb->check_body_collision();
  496. for (int i = colObjArray.size() - 1; 0 <= i; --i) {
  497. static_cast<CollisionObjectBullet *>(colObjArray[i]->getUserPointer())->on_collision_checker_end();
  498. }
  499. }
  500. BulletPhysicsDirectSpaceState *SpaceBullet::get_direct_state() {
  501. return direct_access;
  502. }
  503. btScalar calculateGodotCombinedRestitution(const btCollisionObject *body0, const btCollisionObject *body1) {
  504. return CLAMP(body0->getRestitution() + body1->getRestitution(), 0, 1);
  505. }
  506. btScalar calculateGodotCombinedFriction(const btCollisionObject *body0, const btCollisionObject *body1) {
  507. return ABS(MIN(body0->getFriction(), body1->getFriction()));
  508. }
  509. void SpaceBullet::create_empty_world(bool p_create_soft_world) {
  510. gjk_epa_pen_solver = bulletnew(btGjkEpaPenetrationDepthSolver);
  511. gjk_simplex_solver = bulletnew(btVoronoiSimplexSolver);
  512. void *world_mem;
  513. if (p_create_soft_world) {
  514. world_mem = malloc(sizeof(btSoftRigidDynamicsWorld));
  515. } else {
  516. world_mem = malloc(sizeof(btDiscreteDynamicsWorld));
  517. }
  518. ERR_FAIL_COND_MSG(!world_mem, "Out of memory.");
  519. if (p_create_soft_world) {
  520. collisionConfiguration = bulletnew(GodotSoftCollisionConfiguration(static_cast<btDiscreteDynamicsWorld *>(world_mem)));
  521. } else {
  522. collisionConfiguration = bulletnew(GodotCollisionConfiguration(static_cast<btDiscreteDynamicsWorld *>(world_mem)));
  523. }
  524. dispatcher = bulletnew(GodotCollisionDispatcher(collisionConfiguration));
  525. broadphase = bulletnew(btDbvtBroadphase);
  526. solver = bulletnew(btSequentialImpulseConstraintSolver);
  527. if (p_create_soft_world) {
  528. dynamicsWorld = new (world_mem) btSoftRigidDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
  529. soft_body_world_info = bulletnew(btSoftBodyWorldInfo);
  530. } else {
  531. dynamicsWorld = new (world_mem) btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
  532. }
  533. ghostPairCallback = bulletnew(btGhostPairCallback);
  534. godotFilterCallback = bulletnew(GodotFilterCallback);
  535. gCalculateCombinedRestitutionCallback = &calculateGodotCombinedRestitution;
  536. gCalculateCombinedFrictionCallback = &calculateGodotCombinedFriction;
  537. gContactAddedCallback = &godotContactAddedCallback;
  538. dynamicsWorld->setWorldUserInfo(this);
  539. dynamicsWorld->setInternalTickCallback(onBulletPreTickCallback, this, true);
  540. dynamicsWorld->setInternalTickCallback(onBulletTickCallback, this, false);
  541. dynamicsWorld->getBroadphase()->getOverlappingPairCache()->setInternalGhostPairCallback(ghostPairCallback); // Setup ghost check
  542. dynamicsWorld->getPairCache()->setOverlapFilterCallback(godotFilterCallback);
  543. if (soft_body_world_info) {
  544. soft_body_world_info->m_broadphase = broadphase;
  545. soft_body_world_info->m_dispatcher = dispatcher;
  546. soft_body_world_info->m_sparsesdf.Initialize();
  547. }
  548. update_gravity();
  549. }
  550. void SpaceBullet::destroy_world() {
  551. /// The world elements (like: Collision Objects, Constraints, Shapes) are managed by godot
  552. dynamicsWorld->getBroadphase()->getOverlappingPairCache()->setInternalGhostPairCallback(nullptr);
  553. dynamicsWorld->getPairCache()->setOverlapFilterCallback(nullptr);
  554. bulletdelete(ghostPairCallback);
  555. bulletdelete(godotFilterCallback);
  556. // Deallocate world
  557. dynamicsWorld->~btDiscreteDynamicsWorld();
  558. free(dynamicsWorld);
  559. dynamicsWorld = nullptr;
  560. bulletdelete(solver);
  561. bulletdelete(broadphase);
  562. bulletdelete(dispatcher);
  563. bulletdelete(collisionConfiguration);
  564. bulletdelete(soft_body_world_info);
  565. bulletdelete(gjk_simplex_solver);
  566. bulletdelete(gjk_epa_pen_solver);
  567. }
  568. void SpaceBullet::check_ghost_overlaps() {
  569. // For each area
  570. for (int area_idx = 0; area_idx < areas.size(); area_idx++) {
  571. AreaBullet *area = areas[area_idx];
  572. if (!area->is_monitoring()) {
  573. continue;
  574. }
  575. btGhostObject *bt_ghost = area->get_bt_ghost();
  576. const btTransform &area_transform = area->get_transform__bullet();
  577. const btVector3 &area_scale(area->get_bt_body_scale());
  578. // Mark all current overlapping shapes dirty.
  579. area->mark_all_overlaps_dirty();
  580. // Broadphase
  581. const btAlignedObjectArray<btCollisionObject *> overlapping_pairs = bt_ghost->getOverlappingPairs();
  582. // Narrowphase
  583. for (int pair_idx = 0; pair_idx < overlapping_pairs.size(); pair_idx++) {
  584. btCollisionObject *other_bt_collision_object = overlapping_pairs[pair_idx];
  585. RigidCollisionObjectBullet *other_object = static_cast<RigidCollisionObjectBullet *>(other_bt_collision_object->getUserPointer());
  586. const btTransform &other_transform = other_object->get_transform__bullet();
  587. const btVector3 &other_scale(other_object->get_bt_body_scale());
  588. if (!area->is_updated() && !other_object->is_updated()) {
  589. area->mark_object_overlaps_inside(other_object);
  590. continue;
  591. }
  592. if (other_bt_collision_object->getUserIndex() == CollisionObjectBullet::TYPE_AREA) {
  593. if (!static_cast<AreaBullet *>(other_bt_collision_object->getUserPointer())->is_monitorable()) {
  594. continue;
  595. }
  596. } else if (other_bt_collision_object->getUserIndex() != CollisionObjectBullet::TYPE_RIGID_BODY) {
  597. continue;
  598. }
  599. // For each area shape
  600. for (int our_shape_id = 0; our_shape_id < area->get_shape_count(); our_shape_id++) {
  601. btCollisionShape *area_shape = area->get_bt_shape(our_shape_id);
  602. if (!area_shape->isConvex()) {
  603. continue;
  604. }
  605. btConvexShape *area_convex_shape = static_cast<btConvexShape *>(area_shape);
  606. btTransform area_shape_transform(area->get_bt_shape_transform(our_shape_id));
  607. area_shape_transform.getOrigin() *= area_scale;
  608. btGjkPairDetector::ClosestPointInput gjk_input;
  609. gjk_input.m_transformA = area_transform * area_shape_transform;
  610. // For each other object shape
  611. for (int other_shape_id = 0; other_shape_id < other_object->get_shape_count(); other_shape_id++) {
  612. btCollisionShape *other_shape = other_object->get_bt_shape(other_shape_id);
  613. btTransform other_shape_transform(other_object->get_bt_shape_transform(other_shape_id));
  614. other_shape_transform.getOrigin() *= other_scale;
  615. gjk_input.m_transformB = other_transform * other_shape_transform;
  616. if (other_shape->isConvex()) {
  617. btPointCollector result;
  618. btGjkPairDetector gjk_pair_detector(
  619. area_convex_shape,
  620. static_cast<btConvexShape *>(other_shape),
  621. gjk_simplex_solver,
  622. gjk_epa_pen_solver);
  623. gjk_pair_detector.getClosestPoints(gjk_input, result, 0);
  624. if (result.m_distance <= 0) {
  625. area->set_overlap(other_object, other_shape_id, our_shape_id);
  626. }
  627. } else { // Other shape is not convex.
  628. btCollisionObjectWrapper obA(NULL, area_convex_shape, bt_ghost, gjk_input.m_transformA, -1, our_shape_id);
  629. btCollisionObjectWrapper obB(NULL, other_shape, other_bt_collision_object, gjk_input.m_transformB, -1, other_shape_id);
  630. btCollisionAlgorithm *algorithm = dispatcher->findAlgorithm(&obA, &obB, NULL, BT_CONTACT_POINT_ALGORITHMS);
  631. if (!algorithm) {
  632. continue;
  633. }
  634. GodotDeepPenetrationContactResultCallback contactPointResult(&obA, &obB);
  635. algorithm->processCollision(&obA, &obB, dynamicsWorld->getDispatchInfo(), &contactPointResult);
  636. algorithm->~btCollisionAlgorithm();
  637. dispatcher->freeCollisionAlgorithm(algorithm);
  638. if (contactPointResult.hasHit()) {
  639. area->set_overlap(other_object, our_shape_id, other_shape_id);
  640. }
  641. }
  642. } // End for each other object shape
  643. } // End for each area shape
  644. } // End for each overlapping pair
  645. // All overlapping shapes still marked dirty must have exited.
  646. area->mark_all_dirty_overlaps_as_exit();
  647. } // End for each area
  648. }
  649. void SpaceBullet::check_body_collision() {
  650. #ifdef DEBUG_ENABLED
  651. reset_debug_contact_count();
  652. #endif
  653. const int numManifolds = dynamicsWorld->getDispatcher()->getNumManifolds();
  654. for (int i = 0; i < numManifolds; ++i) {
  655. btPersistentManifold *contactManifold = dynamicsWorld->getDispatcher()->getManifoldByIndexInternal(i);
  656. // I know this static cast is a bit risky. But I'm checking its type just after it.
  657. // This allow me to avoid a lot of other cast and checks
  658. RigidBodyBullet *bodyA = static_cast<RigidBodyBullet *>(contactManifold->getBody0()->getUserPointer());
  659. RigidBodyBullet *bodyB = static_cast<RigidBodyBullet *>(contactManifold->getBody1()->getUserPointer());
  660. if (CollisionObjectBullet::TYPE_RIGID_BODY == bodyA->getType() && CollisionObjectBullet::TYPE_RIGID_BODY == bodyB->getType()) {
  661. if (!bodyA->can_add_collision() && !bodyB->can_add_collision()) {
  662. continue;
  663. }
  664. const int numContacts = contactManifold->getNumContacts();
  665. /// Since I don't need report all contacts for these objects,
  666. /// So report only the first
  667. #define REPORT_ALL_CONTACTS 0
  668. #if REPORT_ALL_CONTACTS
  669. for (int j = 0; j < numContacts; j++) {
  670. btManifoldPoint &pt = contactManifold->getContactPoint(j);
  671. #else
  672. if (numContacts) {
  673. btManifoldPoint &pt = contactManifold->getContactPoint(0);
  674. #endif
  675. if (
  676. pt.getDistance() < 0.0 ||
  677. bodyA->was_colliding(bodyB) ||
  678. bodyB->was_colliding(bodyA)) {
  679. Vector3 collisionWorldPosition;
  680. Vector3 collisionLocalPosition;
  681. Vector3 normalOnB;
  682. float appliedImpulse = pt.m_appliedImpulse;
  683. B_TO_G(pt.m_normalWorldOnB, normalOnB);
  684. // The pt.m_index only contains the shape index when more than one collision shape is used
  685. // and only if the collision shape is not a concave collision shape.
  686. // A value of -1 in pt.m_partId indicates the pt.m_index is a shape index.
  687. int shape_index_a = 0;
  688. if (bodyA->get_shape_count() > 1 && pt.m_partId0 == -1) {
  689. shape_index_a = pt.m_index0;
  690. }
  691. int shape_index_b = 0;
  692. if (bodyB->get_shape_count() > 1 && pt.m_partId1 == -1) {
  693. shape_index_b = pt.m_index1;
  694. }
  695. if (bodyA->can_add_collision()) {
  696. B_TO_G(pt.getPositionWorldOnB(), collisionWorldPosition);
  697. /// pt.m_localPointB Doesn't report the exact point in local space
  698. B_TO_G(pt.getPositionWorldOnB() - contactManifold->getBody1()->getWorldTransform().getOrigin(), collisionLocalPosition);
  699. bodyA->add_collision_object(bodyB, collisionWorldPosition, collisionLocalPosition, normalOnB, appliedImpulse, shape_index_b, shape_index_a);
  700. }
  701. if (bodyB->can_add_collision()) {
  702. B_TO_G(pt.getPositionWorldOnA(), collisionWorldPosition);
  703. /// pt.m_localPointA Doesn't report the exact point in local space
  704. B_TO_G(pt.getPositionWorldOnA() - contactManifold->getBody0()->getWorldTransform().getOrigin(), collisionLocalPosition);
  705. bodyB->add_collision_object(bodyA, collisionWorldPosition, collisionLocalPosition, normalOnB * -1, appliedImpulse * -1, shape_index_a, shape_index_b);
  706. }
  707. #ifdef DEBUG_ENABLED
  708. if (is_debugging_contacts()) {
  709. add_debug_contact(collisionWorldPosition);
  710. }
  711. #endif
  712. }
  713. }
  714. }
  715. }
  716. }
  717. void SpaceBullet::update_gravity() {
  718. btVector3 btGravity;
  719. G_TO_B(gravityDirection * gravityMagnitude, btGravity);
  720. //dynamicsWorld->setGravity(btGravity);
  721. dynamicsWorld->setGravity(btVector3(0, 0, 0));
  722. if (soft_body_world_info) {
  723. soft_body_world_info->m_gravity = btGravity;
  724. }
  725. }
  726. /// IMPORTANT: Please don't turn it ON this is not managed correctly!!
  727. /// I'm leaving this here just for future tests.
  728. /// Debug motion and normal vector drawing
  729. #define debug_test_motion 0
  730. #define RECOVERING_MOVEMENT_SCALE 0.4
  731. #define RECOVERING_MOVEMENT_CYCLES 4
  732. #if debug_test_motion
  733. #include "scene/3d/immediate_geometry.h"
  734. static ImmediateGeometry *motionVec(NULL);
  735. static ImmediateGeometry *normalLine(NULL);
  736. static Ref<Material3D> red_mat;
  737. static Ref<SpatialMaterial> blue_mat;
  738. #endif
  739. 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, const Set<RID> &p_exclude) {
  740. #if debug_test_motion
  741. /// Yes I know this is not good, but I've used it as fast debugging hack.
  742. /// I'm leaving it here just for speedup the other eventual debugs
  743. if (!normalLine) {
  744. motionVec = memnew(ImmediateGeometry);
  745. normalLine = memnew(ImmediateGeometry);
  746. SceneTree::get_singleton()->get_current_scene()->add_child(motionVec);
  747. SceneTree::get_singleton()->get_current_scene()->add_child(normalLine);
  748. motionVec->set_as_toplevel(true);
  749. normalLine->set_as_toplevel(true);
  750. red_mat = Ref<Material3D>(memnew(SpatialMaterial));
  751. red_mat->set_flag(Material3D::FLAG_UNSHADED, true);
  752. red_mat->set_line_width(20.0);
  753. red_mat->set_feature(Material3D::FEATURE_TRANSPARENT, true);
  754. red_mat->set_flag(Material3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  755. red_mat->set_flag(Material3D::FLAG_SRGB_VERTEX_COLOR, true);
  756. red_mat->set_albedo(Color(1, 0, 0, 1));
  757. motionVec->set_material_override(red_mat);
  758. blue_mat = Ref<Material3D>(memnew(SpatialMaterial));
  759. blue_mat->set_flag(Material3D::FLAG_UNSHADED, true);
  760. blue_mat->set_line_width(20.0);
  761. blue_mat->set_feature(Material3D::FEATURE_TRANSPARENT, true);
  762. blue_mat->set_flag(Material3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  763. blue_mat->set_flag(Material3D::FLAG_SRGB_VERTEX_COLOR, true);
  764. blue_mat->set_albedo(Color(0, 0, 1, 1));
  765. normalLine->set_material_override(blue_mat);
  766. }
  767. #endif
  768. btTransform body_transform;
  769. G_TO_B(p_from, body_transform);
  770. UNSCALE_BT_BASIS(body_transform);
  771. if (!p_body->get_kinematic_utilities()) {
  772. p_body->init_kinematic_utilities();
  773. }
  774. btVector3 initial_recover_motion(0, 0, 0);
  775. { /// Phase one - multi shapes depenetration using margin
  776. for (int t(RECOVERING_MOVEMENT_CYCLES); 0 < t; --t) {
  777. if (!recover_from_penetration(p_body, body_transform, RECOVERING_MOVEMENT_SCALE, p_infinite_inertia, initial_recover_motion, nullptr, p_exclude)) {
  778. break;
  779. }
  780. }
  781. // Add recover movement in order to make it safe
  782. body_transform.getOrigin() += initial_recover_motion;
  783. }
  784. btVector3 motion;
  785. G_TO_B(p_motion, motion);
  786. real_t total_length = motion.length();
  787. real_t unsafe_fraction = 1.0;
  788. real_t safe_fraction = 1.0;
  789. {
  790. // Phase two - sweep test, from a secure position without margin
  791. const int shape_count(p_body->get_shape_count());
  792. #if debug_test_motion
  793. Vector3 sup_line;
  794. B_TO_G(body_safe_position.getOrigin(), sup_line);
  795. motionVec->clear();
  796. motionVec->begin(Mesh::PRIMITIVE_LINES, NULL);
  797. motionVec->add_vertex(sup_line);
  798. motionVec->add_vertex(sup_line + p_motion * 10);
  799. motionVec->end();
  800. #endif
  801. for (int shIndex = 0; shIndex < shape_count; ++shIndex) {
  802. if (p_body->is_shape_disabled(shIndex)) {
  803. continue;
  804. }
  805. if (!p_body->get_bt_shape(shIndex)->isConvex()) {
  806. // Skip no convex shape
  807. continue;
  808. }
  809. if (p_exclude_raycast_shapes && p_body->get_bt_shape(shIndex)->getShapeType() == CUSTOM_CONVEX_SHAPE_TYPE) {
  810. // Skip rayshape in order to implement custom separation process
  811. continue;
  812. }
  813. btConvexShape *convex_shape_test(static_cast<btConvexShape *>(p_body->get_bt_shape(shIndex)));
  814. btTransform shape_world_from = body_transform * p_body->get_kinematic_utilities()->shapes[shIndex].transform;
  815. btTransform shape_world_to(shape_world_from);
  816. shape_world_to.getOrigin() += motion;
  817. if ((shape_world_to.getOrigin() - shape_world_from.getOrigin()).fuzzyZero()) {
  818. motion = btVector3(0, 0, 0);
  819. break;
  820. }
  821. GodotKinClosestConvexResultCallback btResult(shape_world_from.getOrigin(), shape_world_to.getOrigin(), p_body, p_infinite_inertia, &p_exclude);
  822. btResult.m_collisionFilterGroup = p_body->get_collision_layer();
  823. btResult.m_collisionFilterMask = p_body->get_collision_mask();
  824. dynamicsWorld->convexSweepTest(convex_shape_test, shape_world_from, shape_world_to, btResult, dynamicsWorld->getDispatchInfo().m_allowedCcdPenetration);
  825. if (btResult.hasHit()) {
  826. if (total_length > CMP_EPSILON) {
  827. real_t hit_fraction = btResult.m_closestHitFraction * motion.length() / total_length;
  828. if (hit_fraction < unsafe_fraction) {
  829. unsafe_fraction = hit_fraction;
  830. real_t margin = p_body->get_kinematic_utilities()->safe_margin;
  831. safe_fraction = MAX(hit_fraction - (1 - ((total_length - margin) / total_length)), 0);
  832. }
  833. }
  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, p_exclude);
  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. r_result->collision_depth = Math::abs(r_recover_result.penetration_distance);
  862. r_result->collision_safe_fraction = safe_fraction;
  863. r_result->collision_unsafe_fraction = unsafe_fraction;
  864. #if debug_test_motion
  865. Vector3 sup_line2;
  866. B_TO_G(motion, sup_line2);
  867. normalLine->clear();
  868. normalLine->begin(Mesh::PRIMITIVE_LINES, NULL);
  869. normalLine->add_vertex(r_result->collision_point);
  870. normalLine->add_vertex(r_result->collision_point + r_result->collision_normal * 10);
  871. normalLine->end();
  872. #endif
  873. } else {
  874. r_result->remainder = Vector3();
  875. }
  876. }
  877. }
  878. return has_penetration;
  879. }
  880. 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) {
  881. btTransform body_transform;
  882. G_TO_B(p_transform, body_transform);
  883. UNSCALE_BT_BASIS(body_transform);
  884. if (!p_body->get_kinematic_utilities()) {
  885. p_body->init_kinematic_utilities();
  886. }
  887. btVector3 recover_motion(0, 0, 0);
  888. int rays_found = 0;
  889. int rays_found_this_round = 0;
  890. for (int t(RECOVERING_MOVEMENT_CYCLES); 0 < t; --t) {
  891. PhysicsServer::SeparationResult *next_results = &r_results[rays_found];
  892. 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);
  893. rays_found += rays_found_this_round;
  894. if (rays_found_this_round == 0) {
  895. body_transform.getOrigin() += recover_motion;
  896. break;
  897. }
  898. }
  899. B_TO_G(recover_motion, r_recover_motion);
  900. return rays_found;
  901. }
  902. struct RecoverPenetrationBroadPhaseCallback : public btBroadphaseAabbCallback {
  903. private:
  904. btDbvtVolume bounds;
  905. const btCollisionObject *self_collision_object;
  906. uint32_t collision_layer;
  907. uint32_t collision_mask;
  908. struct CompoundLeafCallback : btDbvt::ICollide {
  909. private:
  910. RecoverPenetrationBroadPhaseCallback *parent_callback;
  911. btCollisionObject *collision_object;
  912. public:
  913. CompoundLeafCallback(RecoverPenetrationBroadPhaseCallback *p_parent_callback, btCollisionObject *p_collision_object) :
  914. parent_callback(p_parent_callback),
  915. collision_object(p_collision_object) {
  916. }
  917. void Process(const btDbvtNode *leaf) {
  918. BroadphaseResult result;
  919. result.collision_object = collision_object;
  920. result.compound_child_index = leaf->dataAsInt;
  921. parent_callback->results.push_back(result);
  922. }
  923. };
  924. public:
  925. struct BroadphaseResult {
  926. btCollisionObject *collision_object;
  927. int compound_child_index;
  928. };
  929. Vector<BroadphaseResult> results;
  930. public:
  931. 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) :
  932. self_collision_object(p_self_collision_object),
  933. collision_layer(p_collision_layer),
  934. collision_mask(p_collision_mask) {
  935. bounds = btDbvtVolume::FromMM(p_aabb_min, p_aabb_max);
  936. }
  937. virtual ~RecoverPenetrationBroadPhaseCallback() {}
  938. virtual bool process(const btBroadphaseProxy *proxy) {
  939. btCollisionObject *co = static_cast<btCollisionObject *>(proxy->m_clientObject);
  940. if (co->getInternalType() <= btCollisionObject::CO_RIGID_BODY) {
  941. if (self_collision_object != proxy->m_clientObject && GodotFilterCallback::test_collision_filters(collision_layer, collision_mask, proxy->m_collisionFilterGroup, proxy->m_collisionFilterMask)) {
  942. if (co->getCollisionShape()->isCompound()) {
  943. const btCompoundShape *cs = static_cast<btCompoundShape *>(co->getCollisionShape());
  944. if (cs->getNumChildShapes() > 1) {
  945. const btDbvt *tree = cs->getDynamicAabbTree();
  946. ERR_FAIL_COND_V(tree == nullptr, true);
  947. // Transform bounds into compound shape local space
  948. const btTransform other_in_compound_space = co->getWorldTransform().inverse();
  949. const btMatrix3x3 abs_b = other_in_compound_space.getBasis().absolute();
  950. const btVector3 local_center = other_in_compound_space(bounds.Center());
  951. const btVector3 local_extent = bounds.Extents().dot3(abs_b[0], abs_b[1], abs_b[2]);
  952. const btVector3 local_aabb_min = local_center - local_extent;
  953. const btVector3 local_aabb_max = local_center + local_extent;
  954. const btDbvtVolume local_bounds = btDbvtVolume::FromMM(local_aabb_min, local_aabb_max);
  955. // Test collision against compound child shapes using its AABB tree
  956. CompoundLeafCallback compound_leaf_callback(this, co);
  957. tree->collideTV(tree->m_root, local_bounds, compound_leaf_callback);
  958. } else {
  959. // If there's only a single child shape then there's no need to search any more, we know which child overlaps
  960. BroadphaseResult result;
  961. result.collision_object = co;
  962. result.compound_child_index = 0;
  963. results.push_back(result);
  964. }
  965. } else {
  966. BroadphaseResult result;
  967. result.collision_object = co;
  968. result.compound_child_index = -1;
  969. results.push_back(result);
  970. }
  971. return true;
  972. }
  973. }
  974. return false;
  975. }
  976. };
  977. 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, const Set<RID> &p_exclude) {
  978. // Calculate the cumulative AABB of all shapes of the kinematic body
  979. btVector3 aabb_min, aabb_max;
  980. bool shapes_found = false;
  981. for (int kinIndex = p_body->get_kinematic_utilities()->shapes.size() - 1; 0 <= kinIndex; --kinIndex) {
  982. const RigidBodyBullet::KinematicShape &kin_shape(p_body->get_kinematic_utilities()->shapes[kinIndex]);
  983. if (!kin_shape.is_active()) {
  984. continue;
  985. }
  986. if (kin_shape.shape->getShapeType() == CUSTOM_CONVEX_SHAPE_TYPE) {
  987. // Skip rayshape in order to implement custom separation process
  988. continue;
  989. }
  990. btTransform shape_transform = p_body_position * kin_shape.transform;
  991. shape_transform.getOrigin() += r_delta_recover_movement;
  992. btVector3 shape_aabb_min, shape_aabb_max;
  993. kin_shape.shape->getAabb(shape_transform, shape_aabb_min, shape_aabb_max);
  994. if (!shapes_found) {
  995. aabb_min = shape_aabb_min;
  996. aabb_max = shape_aabb_max;
  997. shapes_found = true;
  998. } else {
  999. aabb_min.setX((aabb_min.x() < shape_aabb_min.x()) ? aabb_min.x() : shape_aabb_min.x());
  1000. aabb_min.setY((aabb_min.y() < shape_aabb_min.y()) ? aabb_min.y() : shape_aabb_min.y());
  1001. aabb_min.setZ((aabb_min.z() < shape_aabb_min.z()) ? aabb_min.z() : shape_aabb_min.z());
  1002. aabb_max.setX((aabb_max.x() > shape_aabb_max.x()) ? aabb_max.x() : shape_aabb_max.x());
  1003. aabb_max.setY((aabb_max.y() > shape_aabb_max.y()) ? aabb_max.y() : shape_aabb_max.y());
  1004. aabb_max.setZ((aabb_max.z() > shape_aabb_max.z()) ? aabb_max.z() : shape_aabb_max.z());
  1005. }
  1006. }
  1007. // If there are no shapes then there is no penetration either
  1008. if (!shapes_found) {
  1009. return false;
  1010. }
  1011. // Perform broadphase test
  1012. RecoverPenetrationBroadPhaseCallback recover_broad_result(p_body->get_bt_collision_object(), p_body->get_collision_layer(), p_body->get_collision_mask(), aabb_min, aabb_max);
  1013. dynamicsWorld->getBroadphase()->aabbTest(aabb_min, aabb_max, recover_broad_result);
  1014. bool penetration = false;
  1015. // Perform narrowphase per shape
  1016. for (int kinIndex = p_body->get_kinematic_utilities()->shapes.size() - 1; 0 <= kinIndex; --kinIndex) {
  1017. const RigidBodyBullet::KinematicShape &kin_shape(p_body->get_kinematic_utilities()->shapes[kinIndex]);
  1018. if (!kin_shape.is_active()) {
  1019. continue;
  1020. }
  1021. if (kin_shape.shape->getShapeType() == CUSTOM_CONVEX_SHAPE_TYPE) {
  1022. // Skip rayshape in order to implement custom separation process
  1023. continue;
  1024. }
  1025. if (kin_shape.shape->getShapeType() == EMPTY_SHAPE_PROXYTYPE) {
  1026. continue;
  1027. }
  1028. btTransform shape_transform = p_body_position * kin_shape.transform;
  1029. shape_transform.getOrigin() += r_delta_recover_movement;
  1030. for (int i = recover_broad_result.results.size() - 1; 0 <= i; --i) {
  1031. btCollisionObject *otherObject = recover_broad_result.results[i].collision_object;
  1032. CollisionObjectBullet *gObj = static_cast<CollisionObjectBullet *>(otherObject->getUserPointer());
  1033. if (p_exclude.has(gObj->get_self())) {
  1034. continue;
  1035. }
  1036. if (p_infinite_inertia && !otherObject->isStaticOrKinematicObject()) {
  1037. otherObject->activate(); // Force activation of hitten rigid, soft body
  1038. continue;
  1039. } else if (!p_body->get_bt_collision_object()->checkCollideWith(otherObject) || !otherObject->checkCollideWith(p_body->get_bt_collision_object())) {
  1040. continue;
  1041. }
  1042. if (otherObject->getCollisionShape()->isCompound()) {
  1043. const btCompoundShape *cs = static_cast<const btCompoundShape *>(otherObject->getCollisionShape());
  1044. if (cs->getNumChildShapes() == 0) {
  1045. continue; // No shapes to depenetrate from.
  1046. }
  1047. int shape_idx = recover_broad_result.results[i].compound_child_index;
  1048. ERR_FAIL_COND_V(shape_idx < 0 || shape_idx >= cs->getNumChildShapes(), false);
  1049. if (cs->getChildShape(shape_idx)->isConvex()) {
  1050. 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)) {
  1051. penetration = true;
  1052. }
  1053. } else {
  1054. 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)) {
  1055. penetration = true;
  1056. }
  1057. }
  1058. } else if (otherObject->getCollisionShape()->isConvex()) { /// Execute GJK test against object shape
  1059. 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)) {
  1060. penetration = true;
  1061. }
  1062. } else {
  1063. 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)) {
  1064. penetration = true;
  1065. }
  1066. }
  1067. }
  1068. }
  1069. return penetration;
  1070. }
  1071. 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) {
  1072. // Initialize GJK input
  1073. btGjkPairDetector::ClosestPointInput gjk_input;
  1074. gjk_input.m_transformA = p_transformA;
  1075. // Avoid repeat penetrations
  1076. gjk_input.m_transformA.getOrigin() += r_delta_recover_movement;
  1077. gjk_input.m_transformB = p_transformB;
  1078. // Perform GJK test
  1079. btPointCollector result;
  1080. btGjkPairDetector gjk_pair_detector(p_shapeA, p_shapeB, gjk_simplex_solver, gjk_epa_pen_solver);
  1081. gjk_pair_detector.getClosestPoints(gjk_input, result, nullptr);
  1082. if (0 > result.m_distance) {
  1083. // Has penetration
  1084. r_delta_recover_movement += result.m_normalOnBInWorld * (result.m_distance * -1 * p_recover_movement_scale);
  1085. if (r_recover_result) {
  1086. if (result.m_distance < r_recover_result->penetration_distance) {
  1087. r_recover_result->hasPenetration = true;
  1088. r_recover_result->local_shape_most_recovered = p_shapeId_A;
  1089. r_recover_result->other_collision_object = p_objectB;
  1090. r_recover_result->other_compound_shape_index = p_shapeId_B;
  1091. r_recover_result->penetration_distance = result.m_distance;
  1092. r_recover_result->pointWorld = result.m_pointInWorld;
  1093. r_recover_result->normal = result.m_normalOnBInWorld;
  1094. }
  1095. }
  1096. return true;
  1097. }
  1098. return false;
  1099. }
  1100. 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) {
  1101. /// Contact test
  1102. btTransform tA(p_transformA);
  1103. // Avoid repeat penetrations
  1104. tA.getOrigin() += r_delta_recover_movement;
  1105. btCollisionObjectWrapper obA(nullptr, p_shapeA, p_objectA, tA, -1, p_shapeId_A);
  1106. btCollisionObjectWrapper obB(nullptr, p_shapeB, p_objectB, p_transformB, -1, p_shapeId_B);
  1107. btCollisionAlgorithm *algorithm = dispatcher->findAlgorithm(&obA, &obB, nullptr, BT_CONTACT_POINT_ALGORITHMS);
  1108. if (algorithm) {
  1109. GodotDeepPenetrationContactResultCallback contactPointResult(&obA, &obB);
  1110. //discrete collision detection query
  1111. algorithm->processCollision(&obA, &obB, dynamicsWorld->getDispatchInfo(), &contactPointResult);
  1112. algorithm->~btCollisionAlgorithm();
  1113. dispatcher->freeCollisionAlgorithm(algorithm);
  1114. if (contactPointResult.hasHit()) {
  1115. r_delta_recover_movement += contactPointResult.m_pointNormalWorld * (contactPointResult.m_penetration_distance * -1 * p_recover_movement_scale);
  1116. if (r_recover_result) {
  1117. if (contactPointResult.m_penetration_distance < r_recover_result->penetration_distance) {
  1118. r_recover_result->hasPenetration = true;
  1119. r_recover_result->local_shape_most_recovered = p_shapeId_A;
  1120. r_recover_result->other_collision_object = p_objectB;
  1121. r_recover_result->other_compound_shape_index = p_shapeId_B;
  1122. r_recover_result->penetration_distance = contactPointResult.m_penetration_distance;
  1123. r_recover_result->pointWorld = contactPointResult.m_pointWorld;
  1124. r_recover_result->normal = contactPointResult.m_pointNormalWorld;
  1125. }
  1126. }
  1127. return true;
  1128. }
  1129. }
  1130. return false;
  1131. }
  1132. 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 {
  1133. // optimize results (ignore non-colliding)
  1134. if (p_recover_result.penetration_distance < 0.0) {
  1135. const btRigidBody *btRigid = static_cast<const btRigidBody *>(p_other_object);
  1136. CollisionObjectBullet *collisionObject = static_cast<CollisionObjectBullet *>(p_other_object->getUserPointer());
  1137. r_result->collision_depth = p_recover_result.penetration_distance;
  1138. B_TO_G(p_recover_result.pointWorld, r_result->collision_point);
  1139. B_TO_G(p_recover_result.normal, r_result->collision_normal);
  1140. B_TO_G(btRigid->getVelocityInLocalPoint(p_recover_result.pointWorld - btRigid->getWorldTransform().getOrigin()), r_result->collider_velocity);
  1141. r_result->collision_local_shape = p_shape_id;
  1142. r_result->collider_id = collisionObject->get_instance_id();
  1143. r_result->collider = collisionObject->get_self();
  1144. r_result->collider_shape = p_recover_result.other_compound_shape_index;
  1145. return 1;
  1146. } else {
  1147. return 0;
  1148. }
  1149. }
  1150. 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) {
  1151. // Calculate the cumulative AABB of all shapes of the kinematic body
  1152. btVector3 aabb_min, aabb_max;
  1153. bool shapes_found = false;
  1154. for (int kinIndex = p_body->get_kinematic_utilities()->shapes.size() - 1; 0 <= kinIndex; --kinIndex) {
  1155. const RigidBodyBullet::KinematicShape &kin_shape(p_body->get_kinematic_utilities()->shapes[kinIndex]);
  1156. if (!kin_shape.is_active()) {
  1157. continue;
  1158. }
  1159. if (kin_shape.shape->getShapeType() != CUSTOM_CONVEX_SHAPE_TYPE) {
  1160. continue;
  1161. }
  1162. btTransform shape_transform = p_body_position * kin_shape.transform;
  1163. shape_transform.getOrigin() += r_delta_recover_movement;
  1164. btVector3 shape_aabb_min, shape_aabb_max;
  1165. kin_shape.shape->getAabb(shape_transform, shape_aabb_min, shape_aabb_max);
  1166. if (!shapes_found) {
  1167. aabb_min = shape_aabb_min;
  1168. aabb_max = shape_aabb_max;
  1169. shapes_found = true;
  1170. } else {
  1171. aabb_min.setX((aabb_min.x() < shape_aabb_min.x()) ? aabb_min.x() : shape_aabb_min.x());
  1172. aabb_min.setY((aabb_min.y() < shape_aabb_min.y()) ? aabb_min.y() : shape_aabb_min.y());
  1173. aabb_min.setZ((aabb_min.z() < shape_aabb_min.z()) ? aabb_min.z() : shape_aabb_min.z());
  1174. aabb_max.setX((aabb_max.x() > shape_aabb_max.x()) ? aabb_max.x() : shape_aabb_max.x());
  1175. aabb_max.setY((aabb_max.y() > shape_aabb_max.y()) ? aabb_max.y() : shape_aabb_max.y());
  1176. aabb_max.setZ((aabb_max.z() > shape_aabb_max.z()) ? aabb_max.z() : shape_aabb_max.z());
  1177. }
  1178. }
  1179. // If there are no shapes then there is no penetration either
  1180. if (!shapes_found) {
  1181. return 0;
  1182. }
  1183. // Perform broadphase test
  1184. RecoverPenetrationBroadPhaseCallback recover_broad_result(p_body->get_bt_collision_object(), p_body->get_collision_layer(), p_body->get_collision_mask(), aabb_min, aabb_max);
  1185. dynamicsWorld->getBroadphase()->aabbTest(aabb_min, aabb_max, recover_broad_result);
  1186. int ray_count = 0;
  1187. // Perform narrowphase per shape
  1188. for (int kinIndex = p_body->get_kinematic_utilities()->shapes.size() - 1; 0 <= kinIndex; --kinIndex) {
  1189. if (ray_count >= p_result_max) {
  1190. break;
  1191. }
  1192. const RigidBodyBullet::KinematicShape &kin_shape(p_body->get_kinematic_utilities()->shapes[kinIndex]);
  1193. if (!kin_shape.is_active()) {
  1194. continue;
  1195. }
  1196. if (kin_shape.shape->getShapeType() != CUSTOM_CONVEX_SHAPE_TYPE) {
  1197. continue;
  1198. }
  1199. btTransform shape_transform = p_body_position * kin_shape.transform;
  1200. shape_transform.getOrigin() += r_delta_recover_movement;
  1201. for (int i = recover_broad_result.results.size() - 1; 0 <= i; --i) {
  1202. btCollisionObject *otherObject = recover_broad_result.results[i].collision_object;
  1203. if (p_infinite_inertia && !otherObject->isStaticOrKinematicObject()) {
  1204. otherObject->activate(); // Force activation of hitten rigid, soft body
  1205. continue;
  1206. } else if (!p_body->get_bt_collision_object()->checkCollideWith(otherObject) || !otherObject->checkCollideWith(p_body->get_bt_collision_object())) {
  1207. continue;
  1208. }
  1209. if (otherObject->getCollisionShape()->isCompound()) {
  1210. const btCompoundShape *cs = static_cast<const btCompoundShape *>(otherObject->getCollisionShape());
  1211. int shape_idx = recover_broad_result.results[i].compound_child_index;
  1212. ERR_FAIL_COND_V(shape_idx < 0 || shape_idx >= cs->getNumChildShapes(), false);
  1213. RecoverResult recover_result;
  1214. 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)) {
  1215. ray_count = add_separation_result(&r_results[ray_count], recover_result, kinIndex, otherObject);
  1216. }
  1217. } else {
  1218. RecoverResult recover_result;
  1219. 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)) {
  1220. ray_count = add_separation_result(&r_results[ray_count], recover_result, kinIndex, otherObject);
  1221. }
  1222. }
  1223. }
  1224. }
  1225. return ray_count;
  1226. }