space_bullet.cpp 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159
  1. /*************************************************************************/
  2. /* space_bullet.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2018 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 "godot_collision_configuration.h"
  36. #include "godot_collision_dispatcher.h"
  37. #include "rigid_body_bullet.h"
  38. #include "servers/physics_server.h"
  39. #include "soft_body_bullet.h"
  40. #include "ustring.h"
  41. #include <BulletCollision/CollisionDispatch/btCollisionObject.h>
  42. #include <BulletCollision/CollisionDispatch/btGhostObject.h>
  43. #include <BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h>
  44. #include <BulletCollision/NarrowPhaseCollision/btGjkPairDetector.h>
  45. #include <BulletCollision/NarrowPhaseCollision/btPointCollector.h>
  46. #include <BulletSoftBody/btSoftBodyRigidBodyCollisionConfiguration.h>
  47. #include <BulletSoftBody/btSoftRigidDynamicsWorld.h>
  48. #include <btBulletDynamicsCommon.h>
  49. #include <assert.h>
  50. /**
  51. @author AndreaCatania
  52. */
  53. BulletPhysicsDirectSpaceState::BulletPhysicsDirectSpaceState(SpaceBullet *p_space) :
  54. PhysicsDirectSpaceState(),
  55. space(p_space) {}
  56. 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) {
  57. if (p_result_max <= 0)
  58. return 0;
  59. btVector3 bt_point;
  60. G_TO_B(p_point, bt_point);
  61. btSphereShape sphere_point(0.f);
  62. btCollisionObject collision_object_point;
  63. collision_object_point.setCollisionShape(&sphere_point);
  64. collision_object_point.setWorldTransform(btTransform(btQuaternion::getIdentity(), bt_point));
  65. // Setup query
  66. GodotAllContactResultCallback btResult(&collision_object_point, r_results, p_result_max, &p_exclude);
  67. btResult.m_collisionFilterGroup = 0;
  68. btResult.m_collisionFilterMask = p_collision_mask;
  69. space->dynamicsWorld->contactTest(&collision_object_point, btResult);
  70. // The results is already populated by GodotAllConvexResultCallback
  71. return btResult.m_count;
  72. }
  73. 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_pick_ray) {
  74. btVector3 btVec_from;
  75. btVector3 btVec_to;
  76. G_TO_B(p_from, btVec_from);
  77. G_TO_B(p_to, btVec_to);
  78. // setup query
  79. GodotClosestRayResultCallback btResult(btVec_from, btVec_to, &p_exclude);
  80. btResult.m_collisionFilterGroup = 0;
  81. btResult.m_collisionFilterMask = p_collision_mask;
  82. btResult.m_pickRay = p_pick_ray;
  83. space->dynamicsWorld->rayTest(btVec_from, btVec_to, btResult);
  84. if (btResult.hasHit()) {
  85. B_TO_G(btResult.m_hitPointWorld, r_result.position);
  86. B_TO_G(btResult.m_hitNormalWorld.normalize(), r_result.normal);
  87. CollisionObjectBullet *gObj = static_cast<CollisionObjectBullet *>(btResult.m_collisionObject->getUserPointer());
  88. if (gObj) {
  89. r_result.shape = btResult.m_shapeId;
  90. r_result.rid = gObj->get_self();
  91. r_result.collider_id = gObj->get_instance_id();
  92. r_result.collider = 0 == r_result.collider_id ? NULL : ObjectDB::get_instance(r_result.collider_id);
  93. } else {
  94. WARN_PRINTS("The raycast performed has hit a collision object that is not part of Godot scene, please check it.");
  95. }
  96. return true;
  97. } else {
  98. return false;
  99. }
  100. }
  101. 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) {
  102. if (p_result_max <= 0)
  103. return 0;
  104. ShapeBullet *shape = space->get_physics_server()->get_shape_owner()->get(p_shape);
  105. btCollisionShape *btShape = shape->create_bt_shape(p_xform.basis.get_scale(), p_margin);
  106. if (!btShape->isConvex()) {
  107. bulletdelete(btShape);
  108. ERR_PRINTS("The shape is not a convex shape, then is not supported: shape type: " + itos(shape->get_type()));
  109. return 0;
  110. }
  111. btConvexShape *btConvex = static_cast<btConvexShape *>(btShape);
  112. btTransform bt_xform;
  113. G_TO_B(p_xform, bt_xform);
  114. UNSCALE_BT_BASIS(bt_xform);
  115. btCollisionObject collision_object;
  116. collision_object.setCollisionShape(btConvex);
  117. collision_object.setWorldTransform(bt_xform);
  118. GodotAllContactResultCallback btQuery(&collision_object, r_results, p_result_max, &p_exclude);
  119. btQuery.m_collisionFilterGroup = 0;
  120. btQuery.m_collisionFilterMask = p_collision_mask;
  121. btQuery.m_closestDistanceThreshold = 0;
  122. space->dynamicsWorld->contactTest(&collision_object, btQuery);
  123. bulletdelete(btConvex);
  124. return btQuery.m_count;
  125. }
  126. bool BulletPhysicsDirectSpaceState::cast_motion(const RID &p_shape, const Transform &p_xform, const Vector3 &p_motion, float p_margin, float &p_closest_safe, float &p_closest_unsafe, const Set<RID> &p_exclude, uint32_t p_collision_mask, ShapeRestInfo *r_info) {
  127. ShapeBullet *shape = space->get_physics_server()->get_shape_owner()->get(p_shape);
  128. btCollisionShape *btShape = shape->create_bt_shape(p_xform.basis.get_scale(), p_margin);
  129. if (!btShape->isConvex()) {
  130. bulletdelete(btShape);
  131. ERR_PRINTS("The shape is not a convex shape, then is not supported: shape type: " + itos(shape->get_type()));
  132. return 0;
  133. }
  134. btConvexShape *bt_convex_shape = static_cast<btConvexShape *>(btShape);
  135. btVector3 bt_motion;
  136. G_TO_B(p_motion, bt_motion);
  137. btTransform bt_xform_from;
  138. G_TO_B(p_xform, bt_xform_from);
  139. UNSCALE_BT_BASIS(bt_xform_from);
  140. btTransform bt_xform_to(bt_xform_from);
  141. bt_xform_to.getOrigin() += bt_motion;
  142. GodotClosestConvexResultCallback btResult(bt_xform_from.getOrigin(), bt_xform_to.getOrigin(), &p_exclude);
  143. btResult.m_collisionFilterGroup = 0;
  144. btResult.m_collisionFilterMask = p_collision_mask;
  145. space->dynamicsWorld->convexSweepTest(bt_convex_shape, bt_xform_from, bt_xform_to, btResult, 0.002);
  146. if (btResult.hasHit()) {
  147. p_closest_safe = p_closest_unsafe = btResult.m_closestHitFraction;
  148. if (r_info) {
  149. if (btCollisionObject::CO_RIGID_BODY == btResult.m_hitCollisionObject->getInternalType()) {
  150. B_TO_G(static_cast<const btRigidBody *>(btResult.m_hitCollisionObject)->getVelocityInLocalPoint(btResult.m_hitPointWorld), r_info->linear_velocity);
  151. }
  152. CollisionObjectBullet *collision_object = static_cast<CollisionObjectBullet *>(btResult.m_hitCollisionObject->getUserPointer());
  153. B_TO_G(btResult.m_hitPointWorld, r_info->point);
  154. B_TO_G(btResult.m_hitNormalWorld, r_info->normal);
  155. r_info->rid = collision_object->get_self();
  156. r_info->collider_id = collision_object->get_instance_id();
  157. r_info->shape = btResult.m_shapeId;
  158. }
  159. }
  160. bulletdelete(bt_convex_shape);
  161. return btResult.hasHit();
  162. }
  163. /// Returns the list of contacts pairs in this order: Local contact, other body contact
  164. 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) {
  165. if (p_result_max <= 0)
  166. return 0;
  167. ShapeBullet *shape = space->get_physics_server()->get_shape_owner()->get(p_shape);
  168. btCollisionShape *btShape = shape->create_bt_shape(p_shape_xform.basis.get_scale(), p_margin);
  169. if (!btShape->isConvex()) {
  170. bulletdelete(btShape);
  171. ERR_PRINTS("The shape is not a convex shape, then is not supported: shape type: " + itos(shape->get_type()));
  172. return 0;
  173. }
  174. btConvexShape *btConvex = static_cast<btConvexShape *>(btShape);
  175. btTransform bt_xform;
  176. G_TO_B(p_shape_xform, bt_xform);
  177. UNSCALE_BT_BASIS(bt_xform);
  178. btCollisionObject collision_object;
  179. collision_object.setCollisionShape(btConvex);
  180. collision_object.setWorldTransform(bt_xform);
  181. GodotContactPairContactResultCallback btQuery(&collision_object, r_results, p_result_max, &p_exclude);
  182. btQuery.m_collisionFilterGroup = 0;
  183. btQuery.m_collisionFilterMask = p_collision_mask;
  184. btQuery.m_closestDistanceThreshold = 0;
  185. space->dynamicsWorld->contactTest(&collision_object, btQuery);
  186. r_result_count = btQuery.m_count;
  187. bulletdelete(btConvex);
  188. return btQuery.m_count;
  189. }
  190. 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) {
  191. ShapeBullet *shape = space->get_physics_server()->get_shape_owner()->get(p_shape);
  192. btCollisionShape *btShape = shape->create_bt_shape(p_shape_xform.basis.get_scale(), p_margin);
  193. if (!btShape->isConvex()) {
  194. bulletdelete(btShape);
  195. ERR_PRINTS("The shape is not a convex shape, then is not supported: shape type: " + itos(shape->get_type()));
  196. return 0;
  197. }
  198. btConvexShape *btConvex = static_cast<btConvexShape *>(btShape);
  199. btTransform bt_xform;
  200. G_TO_B(p_shape_xform, bt_xform);
  201. UNSCALE_BT_BASIS(bt_xform);
  202. btCollisionObject collision_object;
  203. collision_object.setCollisionShape(btConvex);
  204. collision_object.setWorldTransform(bt_xform);
  205. GodotRestInfoContactResultCallback btQuery(&collision_object, r_info, &p_exclude);
  206. btQuery.m_collisionFilterGroup = 0;
  207. btQuery.m_collisionFilterMask = p_collision_mask;
  208. btQuery.m_closestDistanceThreshold = 0;
  209. space->dynamicsWorld->contactTest(&collision_object, btQuery);
  210. bulletdelete(btConvex);
  211. if (btQuery.m_collided) {
  212. if (btCollisionObject::CO_RIGID_BODY == btQuery.m_rest_info_collision_object->getInternalType()) {
  213. B_TO_G(static_cast<const btRigidBody *>(btQuery.m_rest_info_collision_object)->getVelocityInLocalPoint(btQuery.m_rest_info_bt_point), r_info->linear_velocity);
  214. }
  215. B_TO_G(btQuery.m_rest_info_bt_point, r_info->point);
  216. }
  217. return btQuery.m_collided;
  218. }
  219. Vector3 BulletPhysicsDirectSpaceState::get_closest_point_to_object_volume(RID p_object, const Vector3 p_point) const {
  220. RigidCollisionObjectBullet *rigid_object = space->get_physics_server()->get_rigid_collisin_object(p_object);
  221. ERR_FAIL_COND_V(!rigid_object, Vector3());
  222. btVector3 out_closest_point(0, 0, 0);
  223. btScalar out_distance = 1e20;
  224. btVector3 bt_point;
  225. G_TO_B(p_point, bt_point);
  226. btSphereShape point_shape(0.);
  227. btCollisionShape *shape;
  228. btConvexShape *convex_shape;
  229. btTransform child_transform;
  230. btTransform body_transform(rigid_object->get_bt_collision_object()->getWorldTransform());
  231. btGjkPairDetector::ClosestPointInput input;
  232. input.m_transformA.getBasis().setIdentity();
  233. input.m_transformA.setOrigin(bt_point);
  234. bool shapes_found = false;
  235. btCompoundShape *compound = rigid_object->get_compound_shape();
  236. for (int i = compound->getNumChildShapes() - 1; 0 <= i; --i) {
  237. shape = compound->getChildShape(i);
  238. if (shape->isConvex()) {
  239. child_transform = compound->getChildTransform(i);
  240. convex_shape = static_cast<btConvexShape *>(shape);
  241. input.m_transformB = body_transform * child_transform;
  242. btPointCollector result;
  243. btGjkPairDetector gjk_pair_detector(&point_shape, convex_shape, space->gjk_simplex_solver, space->gjk_epa_pen_solver);
  244. gjk_pair_detector.getClosestPoints(input, result, 0);
  245. if (out_distance > result.m_distance) {
  246. out_distance = result.m_distance;
  247. out_closest_point = result.m_pointInWorld;
  248. }
  249. }
  250. shapes_found = true;
  251. }
  252. if (shapes_found) {
  253. Vector3 out;
  254. B_TO_G(out_closest_point, out);
  255. return out;
  256. } else {
  257. // no shapes found, use distance to origin.
  258. return rigid_object->get_transform().get_origin();
  259. }
  260. }
  261. SpaceBullet::SpaceBullet(bool p_create_soft_world) :
  262. broadphase(NULL),
  263. dispatcher(NULL),
  264. solver(NULL),
  265. collisionConfiguration(NULL),
  266. dynamicsWorld(NULL),
  267. soft_body_world_info(NULL),
  268. ghostPairCallback(NULL),
  269. godotFilterCallback(NULL),
  270. gravityDirection(0, -1, 0),
  271. gravityMagnitude(10),
  272. contactDebugCount(0) {
  273. create_empty_world(p_create_soft_world);
  274. direct_access = memnew(BulletPhysicsDirectSpaceState(this));
  275. }
  276. SpaceBullet::~SpaceBullet() {
  277. memdelete(direct_access);
  278. destroy_world();
  279. }
  280. void SpaceBullet::flush_queries() {
  281. const btCollisionObjectArray &colObjArray = dynamicsWorld->getCollisionObjectArray();
  282. for (int i = colObjArray.size() - 1; 0 <= i; --i) {
  283. static_cast<CollisionObjectBullet *>(colObjArray[i]->getUserPointer())->dispatch_callbacks();
  284. }
  285. }
  286. void SpaceBullet::step(real_t p_delta_time) {
  287. dynamicsWorld->stepSimulation(p_delta_time, 0, 0);
  288. }
  289. void SpaceBullet::set_param(PhysicsServer::AreaParameter p_param, const Variant &p_value) {
  290. assert(dynamicsWorld);
  291. switch (p_param) {
  292. case PhysicsServer::AREA_PARAM_GRAVITY:
  293. gravityMagnitude = p_value;
  294. update_gravity();
  295. break;
  296. case PhysicsServer::AREA_PARAM_GRAVITY_VECTOR:
  297. gravityDirection = p_value;
  298. update_gravity();
  299. break;
  300. case PhysicsServer::AREA_PARAM_LINEAR_DAMP:
  301. case PhysicsServer::AREA_PARAM_ANGULAR_DAMP:
  302. break; // No damp
  303. case PhysicsServer::AREA_PARAM_PRIORITY:
  304. // Priority is always 0, the lower
  305. break;
  306. case PhysicsServer::AREA_PARAM_GRAVITY_IS_POINT:
  307. case PhysicsServer::AREA_PARAM_GRAVITY_DISTANCE_SCALE:
  308. case PhysicsServer::AREA_PARAM_GRAVITY_POINT_ATTENUATION:
  309. break;
  310. default:
  311. WARN_PRINTS("This set parameter (" + itos(p_param) + ") is ignored, the SpaceBullet doesn't support it.");
  312. break;
  313. }
  314. }
  315. Variant SpaceBullet::get_param(PhysicsServer::AreaParameter p_param) {
  316. switch (p_param) {
  317. case PhysicsServer::AREA_PARAM_GRAVITY:
  318. return gravityMagnitude;
  319. case PhysicsServer::AREA_PARAM_GRAVITY_VECTOR:
  320. return gravityDirection;
  321. case PhysicsServer::AREA_PARAM_LINEAR_DAMP:
  322. case PhysicsServer::AREA_PARAM_ANGULAR_DAMP:
  323. return 0; // No damp
  324. case PhysicsServer::AREA_PARAM_PRIORITY:
  325. return 0; // Priority is always 0, the lower
  326. case PhysicsServer::AREA_PARAM_GRAVITY_IS_POINT:
  327. return false;
  328. case PhysicsServer::AREA_PARAM_GRAVITY_DISTANCE_SCALE:
  329. return 0;
  330. case PhysicsServer::AREA_PARAM_GRAVITY_POINT_ATTENUATION:
  331. return 0;
  332. default:
  333. WARN_PRINTS("This get parameter (" + itos(p_param) + ") is ignored, the SpaceBullet doesn't support it.");
  334. return Variant();
  335. }
  336. }
  337. void SpaceBullet::set_param(PhysicsServer::SpaceParameter p_param, real_t p_value) {
  338. switch (p_param) {
  339. case PhysicsServer::SPACE_PARAM_CONTACT_RECYCLE_RADIUS:
  340. case PhysicsServer::SPACE_PARAM_CONTACT_MAX_SEPARATION:
  341. case PhysicsServer::SPACE_PARAM_BODY_MAX_ALLOWED_PENETRATION:
  342. case PhysicsServer::SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_THRESHOLD:
  343. case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_THRESHOLD:
  344. case PhysicsServer::SPACE_PARAM_BODY_TIME_TO_SLEEP:
  345. case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_DAMP_RATIO:
  346. case PhysicsServer::SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS:
  347. default:
  348. WARN_PRINTS("This set parameter (" + itos(p_param) + ") is ignored, the SpaceBullet doesn't support it.");
  349. break;
  350. }
  351. }
  352. real_t SpaceBullet::get_param(PhysicsServer::SpaceParameter p_param) {
  353. switch (p_param) {
  354. case PhysicsServer::SPACE_PARAM_CONTACT_RECYCLE_RADIUS:
  355. case PhysicsServer::SPACE_PARAM_CONTACT_MAX_SEPARATION:
  356. case PhysicsServer::SPACE_PARAM_BODY_MAX_ALLOWED_PENETRATION:
  357. case PhysicsServer::SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_THRESHOLD:
  358. case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_THRESHOLD:
  359. case PhysicsServer::SPACE_PARAM_BODY_TIME_TO_SLEEP:
  360. case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_DAMP_RATIO:
  361. case PhysicsServer::SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS:
  362. default:
  363. WARN_PRINTS("The SpaceBullet doesn't support this get parameter (" + itos(p_param) + "), 0 is returned.");
  364. return 0.f;
  365. }
  366. }
  367. void SpaceBullet::add_area(AreaBullet *p_area) {
  368. areas.push_back(p_area);
  369. dynamicsWorld->addCollisionObject(p_area->get_bt_ghost(), p_area->get_collision_layer(), p_area->get_collision_mask());
  370. }
  371. void SpaceBullet::remove_area(AreaBullet *p_area) {
  372. areas.erase(p_area);
  373. dynamicsWorld->removeCollisionObject(p_area->get_bt_ghost());
  374. }
  375. void SpaceBullet::reload_collision_filters(AreaBullet *p_area) {
  376. // This is necessary to change collision filter
  377. dynamicsWorld->removeCollisionObject(p_area->get_bt_ghost());
  378. dynamicsWorld->addCollisionObject(p_area->get_bt_ghost(), p_area->get_collision_layer(), p_area->get_collision_mask());
  379. }
  380. void SpaceBullet::add_rigid_body(RigidBodyBullet *p_body) {
  381. if (p_body->is_static()) {
  382. dynamicsWorld->addCollisionObject(p_body->get_bt_rigid_body(), p_body->get_collision_layer(), p_body->get_collision_mask());
  383. } else {
  384. dynamicsWorld->addRigidBody(p_body->get_bt_rigid_body(), p_body->get_collision_layer(), p_body->get_collision_mask());
  385. p_body->scratch_space_override_modificator();
  386. }
  387. }
  388. void SpaceBullet::remove_rigid_body(RigidBodyBullet *p_body) {
  389. if (p_body->is_static()) {
  390. dynamicsWorld->removeCollisionObject(p_body->get_bt_rigid_body());
  391. } else {
  392. dynamicsWorld->removeRigidBody(p_body->get_bt_rigid_body());
  393. }
  394. }
  395. void SpaceBullet::reload_collision_filters(RigidBodyBullet *p_body) {
  396. // This is necessary to change collision filter
  397. remove_rigid_body(p_body);
  398. add_rigid_body(p_body);
  399. }
  400. void SpaceBullet::add_soft_body(SoftBodyBullet *p_body) {
  401. if (is_using_soft_world()) {
  402. if (p_body->get_bt_soft_body()) {
  403. static_cast<btSoftRigidDynamicsWorld *>(dynamicsWorld)->addSoftBody(p_body->get_bt_soft_body(), p_body->get_collision_layer(), p_body->get_collision_mask());
  404. }
  405. } else {
  406. ERR_PRINT("This soft body can't be added to non soft world");
  407. }
  408. }
  409. void SpaceBullet::remove_soft_body(SoftBodyBullet *p_body) {
  410. if (is_using_soft_world()) {
  411. if (p_body->get_bt_soft_body()) {
  412. static_cast<btSoftRigidDynamicsWorld *>(dynamicsWorld)->removeSoftBody(p_body->get_bt_soft_body());
  413. }
  414. }
  415. }
  416. void SpaceBullet::reload_collision_filters(SoftBodyBullet *p_body) {
  417. // This is necessary to change collision filter
  418. remove_soft_body(p_body);
  419. add_soft_body(p_body);
  420. }
  421. void SpaceBullet::add_constraint(ConstraintBullet *p_constraint, bool disableCollisionsBetweenLinkedBodies) {
  422. p_constraint->set_space(this);
  423. dynamicsWorld->addConstraint(p_constraint->get_bt_constraint(), disableCollisionsBetweenLinkedBodies);
  424. }
  425. void SpaceBullet::remove_constraint(ConstraintBullet *p_constraint) {
  426. dynamicsWorld->removeConstraint(p_constraint->get_bt_constraint());
  427. }
  428. int SpaceBullet::get_num_collision_objects() const {
  429. return dynamicsWorld->getNumCollisionObjects();
  430. }
  431. void SpaceBullet::remove_all_collision_objects() {
  432. for (int i = dynamicsWorld->getNumCollisionObjects() - 1; 0 <= i; --i) {
  433. btCollisionObject *btObj = dynamicsWorld->getCollisionObjectArray()[i];
  434. CollisionObjectBullet *colObj = static_cast<CollisionObjectBullet *>(btObj->getUserPointer());
  435. colObj->set_space(NULL);
  436. }
  437. }
  438. void onBulletPreTickCallback(btDynamicsWorld *p_dynamicsWorld, btScalar timeStep) {
  439. static_cast<SpaceBullet *>(p_dynamicsWorld->getWorldUserInfo())->flush_queries();
  440. }
  441. void onBulletTickCallback(btDynamicsWorld *p_dynamicsWorld, btScalar timeStep) {
  442. // Notify all Collision objects the collision checker is started
  443. const btCollisionObjectArray &colObjArray = p_dynamicsWorld->getCollisionObjectArray();
  444. for (int i = colObjArray.size() - 1; 0 <= i; --i) {
  445. CollisionObjectBullet *colObj = static_cast<CollisionObjectBullet *>(colObjArray[i]->getUserPointer());
  446. assert(NULL != colObj);
  447. colObj->on_collision_checker_start();
  448. }
  449. SpaceBullet *sb = static_cast<SpaceBullet *>(p_dynamicsWorld->getWorldUserInfo());
  450. sb->check_ghost_overlaps();
  451. sb->check_body_collision();
  452. }
  453. BulletPhysicsDirectSpaceState *SpaceBullet::get_direct_state() {
  454. return direct_access;
  455. }
  456. btScalar calculateGodotCombinedRestitution(const btCollisionObject *body0, const btCollisionObject *body1) {
  457. return MAX(body0->getRestitution(), body1->getRestitution());
  458. }
  459. void SpaceBullet::create_empty_world(bool p_create_soft_world) {
  460. gjk_epa_pen_solver = bulletnew(btGjkEpaPenetrationDepthSolver);
  461. gjk_simplex_solver = bulletnew(btVoronoiSimplexSolver);
  462. gjk_simplex_solver->setEqualVertexThreshold(0.f);
  463. void *world_mem;
  464. if (p_create_soft_world) {
  465. world_mem = malloc(sizeof(btSoftRigidDynamicsWorld));
  466. } else {
  467. world_mem = malloc(sizeof(btDiscreteDynamicsWorld));
  468. }
  469. if (p_create_soft_world) {
  470. collisionConfiguration = bulletnew(btSoftBodyRigidBodyCollisionConfiguration);
  471. } else {
  472. collisionConfiguration = bulletnew(GodotCollisionConfiguration(static_cast<btDiscreteDynamicsWorld *>(world_mem)));
  473. }
  474. dispatcher = bulletnew(GodotCollisionDispatcher(collisionConfiguration));
  475. broadphase = bulletnew(btDbvtBroadphase);
  476. solver = bulletnew(btSequentialImpulseConstraintSolver);
  477. if (p_create_soft_world) {
  478. dynamicsWorld = new (world_mem) btSoftRigidDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
  479. soft_body_world_info = bulletnew(btSoftBodyWorldInfo);
  480. } else {
  481. dynamicsWorld = new (world_mem) btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
  482. }
  483. ghostPairCallback = bulletnew(btGhostPairCallback);
  484. godotFilterCallback = bulletnew(GodotFilterCallback);
  485. gCalculateCombinedRestitutionCallback = &calculateGodotCombinedRestitution;
  486. dynamicsWorld->setWorldUserInfo(this);
  487. dynamicsWorld->setInternalTickCallback(onBulletPreTickCallback, this, true);
  488. dynamicsWorld->setInternalTickCallback(onBulletTickCallback, this, false);
  489. dynamicsWorld->getBroadphase()->getOverlappingPairCache()->setInternalGhostPairCallback(ghostPairCallback); // Setup ghost check
  490. dynamicsWorld->getPairCache()->setOverlapFilterCallback(godotFilterCallback);
  491. if (soft_body_world_info) {
  492. soft_body_world_info->m_broadphase = broadphase;
  493. soft_body_world_info->m_dispatcher = dispatcher;
  494. soft_body_world_info->m_sparsesdf.Initialize();
  495. }
  496. update_gravity();
  497. }
  498. void SpaceBullet::destroy_world() {
  499. /// The world elements (like: Collision Objects, Constraints, Shapes) are managed by godot
  500. dynamicsWorld->getBroadphase()->getOverlappingPairCache()->setInternalGhostPairCallback(NULL);
  501. dynamicsWorld->getPairCache()->setOverlapFilterCallback(NULL);
  502. bulletdelete(ghostPairCallback);
  503. bulletdelete(godotFilterCallback);
  504. // Deallocate world
  505. dynamicsWorld->~btDiscreteDynamicsWorld();
  506. free(dynamicsWorld);
  507. dynamicsWorld = NULL;
  508. bulletdelete(solver);
  509. bulletdelete(broadphase);
  510. bulletdelete(dispatcher);
  511. bulletdelete(collisionConfiguration);
  512. bulletdelete(soft_body_world_info);
  513. bulletdelete(gjk_simplex_solver);
  514. bulletdelete(gjk_epa_pen_solver);
  515. }
  516. void SpaceBullet::check_ghost_overlaps() {
  517. /// Algorith support variables
  518. btConvexShape *other_body_shape;
  519. btConvexShape *area_shape;
  520. btGjkPairDetector::ClosestPointInput gjk_input;
  521. AreaBullet *area;
  522. RigidCollisionObjectBullet *otherObject;
  523. int x(-1), i(-1), y(-1), z(-1), indexOverlap(-1);
  524. /// For each areas
  525. for (x = areas.size() - 1; 0 <= x; --x) {
  526. area = areas[x];
  527. if (!area->is_monitoring())
  528. continue;
  529. /// 1. Reset all states
  530. for (i = area->overlappingObjects.size() - 1; 0 <= i; --i) {
  531. AreaBullet::OverlappingObjectData &otherObj = area->overlappingObjects[i];
  532. // This check prevent the overwrite of ENTER state
  533. // if this function is called more times before dispatchCallbacks
  534. if (otherObj.state != AreaBullet::OVERLAP_STATE_ENTER) {
  535. otherObj.state = AreaBullet::OVERLAP_STATE_DIRTY;
  536. }
  537. }
  538. /// 2. Check all overlapping objects using GJK
  539. const btAlignedObjectArray<btCollisionObject *> ghostOverlaps = area->get_bt_ghost()->getOverlappingPairs();
  540. // For each overlapping
  541. for (i = ghostOverlaps.size() - 1; 0 <= i; --i) {
  542. if (!(ghostOverlaps[i]->getUserIndex() == CollisionObjectBullet::TYPE_RIGID_BODY || ghostOverlaps[i]->getUserIndex() == CollisionObjectBullet::TYPE_AREA))
  543. continue;
  544. otherObject = static_cast<RigidCollisionObjectBullet *>(ghostOverlaps[i]->getUserPointer());
  545. bool hasOverlap = false;
  546. // For each area shape
  547. for (y = area->get_compound_shape()->getNumChildShapes() - 1; 0 <= y; --y) {
  548. if (!area->get_compound_shape()->getChildShape(y)->isConvex())
  549. continue;
  550. gjk_input.m_transformA = area->get_transform__bullet() * area->get_compound_shape()->getChildTransform(y);
  551. area_shape = static_cast<btConvexShape *>(area->get_compound_shape()->getChildShape(y));
  552. // For each other object shape
  553. for (z = otherObject->get_compound_shape()->getNumChildShapes() - 1; 0 <= z; --z) {
  554. if (!otherObject->get_compound_shape()->getChildShape(z)->isConvex())
  555. continue;
  556. other_body_shape = static_cast<btConvexShape *>(otherObject->get_compound_shape()->getChildShape(z));
  557. gjk_input.m_transformB = otherObject->get_transform__bullet() * otherObject->get_compound_shape()->getChildTransform(z);
  558. btPointCollector result;
  559. btGjkPairDetector gjk_pair_detector(area_shape, other_body_shape, gjk_simplex_solver, gjk_epa_pen_solver);
  560. gjk_pair_detector.getClosestPoints(gjk_input, result, 0);
  561. if (0 >= result.m_distance) {
  562. hasOverlap = true;
  563. goto collision_found;
  564. }
  565. } // ~For each other object shape
  566. } // ~For each area shape
  567. collision_found:
  568. if (!hasOverlap)
  569. continue;
  570. indexOverlap = area->find_overlapping_object(otherObject);
  571. if (-1 == indexOverlap) {
  572. // Not found
  573. area->add_overlap(otherObject);
  574. } else {
  575. // Found
  576. area->put_overlap_as_inside(indexOverlap);
  577. }
  578. }
  579. /// 3. Remove not overlapping
  580. for (i = area->overlappingObjects.size() - 1; 0 <= i; --i) {
  581. // If the overlap has DIRTY state it means that it's no more overlapping
  582. if (area->overlappingObjects[i].state == AreaBullet::OVERLAP_STATE_DIRTY) {
  583. area->put_overlap_as_exit(i);
  584. }
  585. }
  586. }
  587. }
  588. void SpaceBullet::check_body_collision() {
  589. #ifdef DEBUG_ENABLED
  590. reset_debug_contact_count();
  591. #endif
  592. const int numManifolds = dynamicsWorld->getDispatcher()->getNumManifolds();
  593. for (int i = 0; i < numManifolds; ++i) {
  594. btPersistentManifold *contactManifold = dynamicsWorld->getDispatcher()->getManifoldByIndexInternal(i);
  595. // I know this static cast is a bit risky. But I'm checking its type just after it.
  596. // This allow me to avoid a lot of other cast and checks
  597. RigidBodyBullet *bodyA = static_cast<RigidBodyBullet *>(contactManifold->getBody0()->getUserPointer());
  598. RigidBodyBullet *bodyB = static_cast<RigidBodyBullet *>(contactManifold->getBody1()->getUserPointer());
  599. if (CollisionObjectBullet::TYPE_RIGID_BODY == bodyA->getType() && CollisionObjectBullet::TYPE_RIGID_BODY == bodyB->getType()) {
  600. if (!bodyA->can_add_collision() && !bodyB->can_add_collision()) {
  601. continue;
  602. }
  603. const int numContacts = contactManifold->getNumContacts();
  604. #define REPORT_ALL_CONTACTS 0
  605. #if REPORT_ALL_CONTACTS
  606. for (int j = 0; j < numContacts; j++) {
  607. btManifoldPoint &pt = contactManifold->getContactPoint(j);
  608. #else
  609. // Since I don't need report all contacts for these objects, I'll report only the first
  610. if (numContacts) {
  611. btManifoldPoint &pt = contactManifold->getContactPoint(0);
  612. #endif
  613. Vector3 collisionWorldPosition;
  614. Vector3 collisionLocalPosition;
  615. Vector3 normalOnB;
  616. B_TO_G(pt.m_normalWorldOnB, normalOnB);
  617. if (bodyA->can_add_collision()) {
  618. B_TO_G(pt.getPositionWorldOnB(), collisionWorldPosition);
  619. /// pt.m_localPointB Doesn't report the exact point in local space
  620. B_TO_G(pt.getPositionWorldOnB() - contactManifold->getBody1()->getWorldTransform().getOrigin(), collisionLocalPosition);
  621. bodyA->add_collision_object(bodyB, collisionWorldPosition, collisionLocalPosition, normalOnB, pt.m_index1, pt.m_index0);
  622. }
  623. if (bodyB->can_add_collision()) {
  624. B_TO_G(pt.getPositionWorldOnA(), collisionWorldPosition);
  625. /// pt.m_localPointA Doesn't report the exact point in local space
  626. B_TO_G(pt.getPositionWorldOnA() - contactManifold->getBody0()->getWorldTransform().getOrigin(), collisionLocalPosition);
  627. bodyB->add_collision_object(bodyA, collisionWorldPosition, collisionLocalPosition, normalOnB * -1, pt.m_index0, pt.m_index1);
  628. }
  629. #ifdef DEBUG_ENABLED
  630. if (is_debugging_contacts()) {
  631. add_debug_contact(collisionWorldPosition);
  632. }
  633. #endif
  634. }
  635. }
  636. }
  637. }
  638. void SpaceBullet::update_gravity() {
  639. btVector3 btGravity;
  640. G_TO_B(gravityDirection * gravityMagnitude, btGravity);
  641. //dynamicsWorld->setGravity(btGravity);
  642. dynamicsWorld->setGravity(btVector3(0, 0, 0));
  643. if (soft_body_world_info) {
  644. soft_body_world_info->m_gravity = btGravity;
  645. }
  646. }
  647. /// IMPORTANT: Please don't turn it ON this is not managed correctly!!
  648. /// I'm leaving this here just for future tests.
  649. /// Debug motion and normal vector drawing
  650. #define debug_test_motion 0
  651. #define PERFORM_INITIAL_UNSTACK 0
  652. #define RECOVERING_MOVEMENT_SCALE 0.4
  653. #define RECOVERING_MOVEMENT_CYCLES 4
  654. #if debug_test_motion
  655. #include "scene/3d/immediate_geometry.h"
  656. static ImmediateGeometry *motionVec(NULL);
  657. static ImmediateGeometry *normalLine(NULL);
  658. static Ref<SpatialMaterial> red_mat;
  659. static Ref<SpatialMaterial> blue_mat;
  660. #endif
  661. #define IGNORE_AREAS_TRUE true
  662. bool SpaceBullet::test_body_motion(RigidBodyBullet *p_body, const Transform &p_from, const Vector3 &p_motion, PhysicsServer::MotionResult *r_result) {
  663. #if debug_test_motion
  664. /// Yes I know this is not good, but I've used it as fast debugging hack.
  665. /// I'm leaving it here just for speedup the other eventual debugs
  666. if (!normalLine) {
  667. motionVec = memnew(ImmediateGeometry);
  668. normalLine = memnew(ImmediateGeometry);
  669. SceneTree::get_singleton()->get_current_scene()->add_child(motionVec);
  670. SceneTree::get_singleton()->get_current_scene()->add_child(normalLine);
  671. motionVec->set_as_toplevel(true);
  672. normalLine->set_as_toplevel(true);
  673. red_mat = Ref<SpatialMaterial>(memnew(SpatialMaterial));
  674. red_mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  675. red_mat->set_line_width(20.0);
  676. red_mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  677. red_mat->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  678. red_mat->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
  679. red_mat->set_albedo(Color(1, 0, 0, 1));
  680. motionVec->set_material_override(red_mat);
  681. blue_mat = Ref<SpatialMaterial>(memnew(SpatialMaterial));
  682. blue_mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  683. blue_mat->set_line_width(20.0);
  684. blue_mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  685. blue_mat->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  686. blue_mat->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
  687. blue_mat->set_albedo(Color(0, 0, 1, 1));
  688. normalLine->set_material_override(blue_mat);
  689. }
  690. #endif
  691. ///// Release all generated manifolds
  692. //{
  693. // if(p_body->get_kinematic_utilities()){
  694. // for(int i= p_body->get_kinematic_utilities()->m_generatedManifold.size()-1; 0<=i; --i){
  695. // dispatcher->releaseManifold( p_body->get_kinematic_utilities()->m_generatedManifold[i] );
  696. // }
  697. // p_body->get_kinematic_utilities()->m_generatedManifold.clear();
  698. // }
  699. //}
  700. btTransform body_safe_position;
  701. G_TO_B(p_from, body_safe_position);
  702. UNSCALE_BT_BASIS(body_safe_position);
  703. #if PERFORM_INITIAL_UNSTACK
  704. btVector3 recover_initial_position(0, 0, 0);
  705. { /// Phase one - multi shapes depenetration using margin
  706. for (int t(RECOVERING_MOVEMENT_CYCLES); 0 < t; --t) {
  707. if (!recover_from_penetration(p_body, body_safe_position, RECOVERING_MOVEMENT_SCALE, recover_initial_position)) {
  708. break;
  709. }
  710. }
  711. // Add recover movement in order to make it safe
  712. body_safe_position.getOrigin() += recover_initial_position;
  713. }
  714. #endif
  715. btVector3 motion;
  716. G_TO_B(p_motion, motion);
  717. { /// phase two - sweep test, from a secure position without margin
  718. const int shape_count(p_body->get_shape_count());
  719. #if debug_test_motion
  720. Vector3 sup_line;
  721. B_TO_G(body_safe_position.getOrigin(), sup_line);
  722. motionVec->clear();
  723. motionVec->begin(Mesh::PRIMITIVE_LINES, NULL);
  724. motionVec->add_vertex(sup_line);
  725. motionVec->add_vertex(sup_line + p_motion * 10);
  726. motionVec->end();
  727. #endif
  728. for (int shIndex = 0; shIndex < shape_count; ++shIndex) {
  729. if (p_body->is_shape_disabled(shIndex)) {
  730. continue;
  731. }
  732. if (!p_body->get_bt_shape(shIndex)->isConvex()) {
  733. // Skip no convex shape
  734. continue;
  735. }
  736. btConvexShape *convex_shape_test(static_cast<btConvexShape *>(p_body->get_bt_shape(shIndex)));
  737. btTransform shape_world_from = body_safe_position * p_body->get_kinematic_utilities()->shapes[shIndex].transform;
  738. btTransform shape_world_to(shape_world_from);
  739. shape_world_to.getOrigin() += motion;
  740. GodotKinClosestConvexResultCallback btResult(shape_world_from.getOrigin(), shape_world_to.getOrigin(), p_body, IGNORE_AREAS_TRUE);
  741. btResult.m_collisionFilterGroup = p_body->get_collision_layer();
  742. btResult.m_collisionFilterMask = p_body->get_collision_mask();
  743. dynamicsWorld->convexSweepTest(convex_shape_test, shape_world_from, shape_world_to, btResult, 0.002);
  744. if (btResult.hasHit()) {
  745. /// Since for each sweep test I fix the motion of new shapes in base the recover result,
  746. /// if another shape will hit something it means that has a deepest penetration respect the previous shape
  747. motion *= btResult.m_closestHitFraction;
  748. }
  749. }
  750. body_safe_position.getOrigin() += motion;
  751. }
  752. bool has_penetration = false;
  753. { /// Phase three - Recover + contact test with margin
  754. btVector3 delta_recover_movement(0, 0, 0);
  755. RecoverResult r_recover_result;
  756. bool l_has_penetration;
  757. real_t l_penetration_distance = 1e20;
  758. for (int t(RECOVERING_MOVEMENT_CYCLES); 0 < t; --t) {
  759. l_has_penetration = recover_from_penetration(p_body, body_safe_position, RECOVERING_MOVEMENT_SCALE, delta_recover_movement, &r_recover_result);
  760. if (r_result) {
  761. #if PERFORM_INITIAL_UNSTACK
  762. B_TO_G(motion + delta_recover_movement + recover_initial_position, r_result->motion);
  763. #else
  764. B_TO_G(motion + delta_recover_movement, r_result->motion);
  765. #endif
  766. if (l_has_penetration) {
  767. has_penetration = true;
  768. if (l_penetration_distance <= r_recover_result.penetration_distance) {
  769. continue;
  770. }
  771. l_penetration_distance = r_recover_result.penetration_distance;
  772. const btRigidBody *btRigid = static_cast<const btRigidBody *>(r_recover_result.other_collision_object);
  773. CollisionObjectBullet *collisionObject = static_cast<CollisionObjectBullet *>(btRigid->getUserPointer());
  774. B_TO_G(motion, r_result->remainder); // is the remaining movements
  775. r_result->remainder = p_motion - r_result->remainder;
  776. B_TO_G(r_recover_result.pointWorld, r_result->collision_point);
  777. B_TO_G(r_recover_result.normal, r_result->collision_normal);
  778. 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
  779. r_result->collider = collisionObject->get_self();
  780. r_result->collider_id = collisionObject->get_instance_id();
  781. r_result->collider_shape = r_recover_result.other_compound_shape_index;
  782. r_result->collision_local_shape = r_recover_result.local_shape_most_recovered;
  783. //{ /// Add manifold point to manage collisions
  784. // btPersistentManifold* manifold = dynamicsWorld->getDispatcher()->getNewManifold(p_body->getBtBody(), btRigid);
  785. // btManifoldPoint manifoldPoint(result_callabck.m_pointWorld, result_callabck.m_pointWorld, result_callabck.m_pointNormalWorld, result_callabck.m_penetration_distance);
  786. // manifoldPoint.m_index0 = r_result->collision_local_shape;
  787. // manifoldPoint.m_index1 = r_result->collider_shape;
  788. // manifold->addManifoldPoint(manifoldPoint);
  789. // p_body->get_kinematic_utilities()->m_generatedManifold.push_back(manifold);
  790. //}
  791. #if debug_test_motion
  792. Vector3 sup_line2;
  793. B_TO_G(motion, sup_line2);
  794. normalLine->clear();
  795. normalLine->begin(Mesh::PRIMITIVE_LINES, NULL);
  796. normalLine->add_vertex(r_result->collision_point);
  797. normalLine->add_vertex(r_result->collision_point + r_result->collision_normal * 10);
  798. normalLine->end();
  799. #endif
  800. } else {
  801. r_result->remainder = Vector3();
  802. }
  803. } else {
  804. if (!l_has_penetration)
  805. break;
  806. }
  807. }
  808. }
  809. return has_penetration;
  810. }
  811. struct RecoverPenetrationBroadPhaseCallback : public btBroadphaseAabbCallback {
  812. private:
  813. const btCollisionObject *self_collision_object;
  814. uint32_t collision_layer;
  815. uint32_t collision_mask;
  816. public:
  817. Vector<btCollisionObject *> result_collision_objects;
  818. public:
  819. RecoverPenetrationBroadPhaseCallback(const btCollisionObject *p_self_collision_object, uint32_t p_collision_layer, uint32_t p_collision_mask) :
  820. self_collision_object(p_self_collision_object),
  821. collision_layer(p_collision_layer),
  822. collision_mask(p_collision_mask) {}
  823. virtual ~RecoverPenetrationBroadPhaseCallback() {}
  824. virtual bool process(const btBroadphaseProxy *proxy) {
  825. btCollisionObject *co = static_cast<btCollisionObject *>(proxy->m_clientObject);
  826. if (co->getInternalType() <= btCollisionObject::CO_RIGID_BODY) {
  827. if (self_collision_object != proxy->m_clientObject && GodotFilterCallback::test_collision_filters(collision_layer, collision_mask, proxy->m_collisionFilterGroup, proxy->m_collisionFilterMask)) {
  828. result_collision_objects.push_back(co);
  829. return true;
  830. }
  831. }
  832. return false;
  833. }
  834. void reset() {
  835. result_collision_objects.empty();
  836. }
  837. };
  838. bool SpaceBullet::recover_from_penetration(RigidBodyBullet *p_body, const btTransform &p_body_position, btScalar p_recover_movement_scale, btVector3 &r_delta_recover_movement, RecoverResult *r_recover_result) {
  839. RecoverPenetrationBroadPhaseCallback recover_broad_result(p_body->get_bt_collision_object(), p_body->get_collision_layer(), p_body->get_collision_mask());
  840. btTransform body_shape_position;
  841. btTransform body_shape_position_recovered;
  842. // Broad phase support
  843. btVector3 minAabb, maxAabb;
  844. bool penetration = false;
  845. // For each shape
  846. for (int kinIndex = p_body->get_kinematic_utilities()->shapes.size() - 1; 0 <= kinIndex; --kinIndex) {
  847. recover_broad_result.reset();
  848. const RigidBodyBullet::KinematicShape &kin_shape(p_body->get_kinematic_utilities()->shapes[kinIndex]);
  849. if (!kin_shape.is_active()) {
  850. continue;
  851. }
  852. body_shape_position = p_body_position * kin_shape.transform;
  853. body_shape_position_recovered = body_shape_position;
  854. body_shape_position_recovered.getOrigin() += r_delta_recover_movement;
  855. kin_shape.shape->getAabb(body_shape_position_recovered, minAabb, maxAabb);
  856. dynamicsWorld->getBroadphase()->aabbTest(minAabb, maxAabb, recover_broad_result);
  857. for (int i = recover_broad_result.result_collision_objects.size() - 1; 0 <= i; --i) {
  858. btCollisionObject *otherObject = recover_broad_result.result_collision_objects[i];
  859. if (!p_body->get_bt_collision_object()->checkCollideWith(otherObject) || !otherObject->checkCollideWith(p_body->get_bt_collision_object()))
  860. continue;
  861. if (otherObject->getCollisionShape()->isCompound()) {
  862. // Each convex shape
  863. btCompoundShape *cs = static_cast<btCompoundShape *>(otherObject->getCollisionShape());
  864. for (int x = cs->getNumChildShapes() - 1; 0 <= x; --x) {
  865. if (cs->getChildShape(x)->isConvex()) {
  866. if (RFP_convex_convex_test(kin_shape.shape, static_cast<const btConvexShape *>(cs->getChildShape(x)), otherObject, x, body_shape_position, otherObject->getWorldTransform() * cs->getChildTransform(x), p_recover_movement_scale, r_delta_recover_movement, r_recover_result)) {
  867. penetration = true;
  868. }
  869. } else {
  870. if (RFP_convex_world_test(kin_shape.shape, cs->getChildShape(x), p_body->get_bt_collision_object(), otherObject, kinIndex, x, body_shape_position, otherObject->getWorldTransform() * cs->getChildTransform(x), p_recover_movement_scale, r_delta_recover_movement, r_recover_result)) {
  871. penetration = true;
  872. }
  873. }
  874. }
  875. } else if (otherObject->getCollisionShape()->isConvex()) { /// Execute GJK test against object shape
  876. if (RFP_convex_convex_test(kin_shape.shape, static_cast<const btConvexShape *>(otherObject->getCollisionShape()), otherObject, 0, body_shape_position, otherObject->getWorldTransform(), p_recover_movement_scale, r_delta_recover_movement, r_recover_result)) {
  877. penetration = true;
  878. }
  879. } else {
  880. if (RFP_convex_world_test(kin_shape.shape, otherObject->getCollisionShape(), p_body->get_bt_collision_object(), otherObject, kinIndex, 0, body_shape_position, otherObject->getWorldTransform(), p_recover_movement_scale, r_delta_recover_movement, r_recover_result)) {
  881. penetration = true;
  882. }
  883. }
  884. }
  885. }
  886. return penetration;
  887. }
  888. bool SpaceBullet::RFP_convex_convex_test(const btConvexShape *p_shapeA, const btConvexShape *p_shapeB, btCollisionObject *p_objectB, 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) {
  889. // Initialize GJK input
  890. btGjkPairDetector::ClosestPointInput gjk_input;
  891. gjk_input.m_transformA = p_transformA;
  892. gjk_input.m_transformA.getOrigin() += r_delta_recover_movement;
  893. gjk_input.m_transformB = p_transformB;
  894. // Perform GJK test
  895. btPointCollector result;
  896. btGjkPairDetector gjk_pair_detector(p_shapeA, p_shapeB, gjk_simplex_solver, gjk_epa_pen_solver);
  897. gjk_pair_detector.getClosestPoints(gjk_input, result, 0);
  898. if (0 > result.m_distance) {
  899. // Has penetration
  900. r_delta_recover_movement += result.m_normalOnBInWorld * (result.m_distance * -1 * p_recover_movement_scale);
  901. if (r_recover_result) {
  902. if (result.m_distance < r_recover_result->penetration_distance) {
  903. r_recover_result->hasPenetration = true;
  904. r_recover_result->other_collision_object = p_objectB;
  905. r_recover_result->other_compound_shape_index = p_shapeId_B;
  906. r_recover_result->penetration_distance = result.m_distance;
  907. r_recover_result->pointWorld = result.m_pointInWorld;
  908. r_recover_result->normal = result.m_normalOnBInWorld;
  909. }
  910. }
  911. return true;
  912. }
  913. return false;
  914. }
  915. 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) {
  916. /// Contact test
  917. btTransform tA(p_transformA);
  918. tA.getOrigin() += r_delta_recover_movement;
  919. btCollisionObjectWrapper obA(NULL, p_shapeA, p_objectA, tA, -1, p_shapeId_A);
  920. btCollisionObjectWrapper obB(NULL, p_shapeB, p_objectB, p_transformB, -1, p_shapeId_B);
  921. btCollisionAlgorithm *algorithm = dispatcher->findAlgorithm(&obA, &obB, NULL, BT_CLOSEST_POINT_ALGORITHMS);
  922. if (algorithm) {
  923. GodotDeepPenetrationContactResultCallback contactPointResult(&obA, &obB);
  924. //discrete collision detection query
  925. algorithm->processCollision(&obA, &obB, dynamicsWorld->getDispatchInfo(), &contactPointResult);
  926. algorithm->~btCollisionAlgorithm();
  927. dispatcher->freeCollisionAlgorithm(algorithm);
  928. if (contactPointResult.hasHit()) {
  929. r_delta_recover_movement += contactPointResult.m_pointNormalWorld * (contactPointResult.m_penetration_distance * -1 * p_recover_movement_scale);
  930. if (r_recover_result) {
  931. if (contactPointResult.m_penetration_distance < r_recover_result->penetration_distance) {
  932. r_recover_result->hasPenetration = true;
  933. r_recover_result->other_collision_object = p_objectB;
  934. r_recover_result->other_compound_shape_index = p_shapeId_B;
  935. r_recover_result->penetration_distance = contactPointResult.m_penetration_distance;
  936. r_recover_result->pointWorld = contactPointResult.m_pointWorld;
  937. r_recover_result->normal = contactPointResult.m_pointNormalWorld;
  938. }
  939. }
  940. return true;
  941. }
  942. }
  943. return false;
  944. }