space_bullet.cpp 51 KB

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