space_bullet.cpp 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163
  1. /*************************************************************************/
  2. /* space_bullet.cpp */
  3. /* Author: AndreaCatania */
  4. /*************************************************************************/
  5. /* This file is part of: */
  6. /* GODOT ENGINE */
  7. /* http://www.godotengine.org */
  8. /*************************************************************************/
  9. /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
  10. /* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */
  11. /* */
  12. /* Permission is hereby granted, free of charge, to any person obtaining */
  13. /* a copy of this software and associated documentation files (the */
  14. /* "Software"), to deal in the Software without restriction, including */
  15. /* without limitation the rights to use, copy, modify, merge, publish, */
  16. /* distribute, sublicense, and/or sell copies of the Software, and to */
  17. /* permit persons to whom the Software is furnished to do so, subject to */
  18. /* the following conditions: */
  19. /* */
  20. /* The above copyright notice and this permission notice shall be */
  21. /* included in all copies or substantial portions of the Software. */
  22. /* */
  23. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  24. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  25. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  26. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  27. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  28. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  29. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  30. /*************************************************************************/
  31. #include "space_bullet.h"
  32. #include "BulletCollision/CollisionDispatch/btCollisionObject.h"
  33. #include "BulletCollision/CollisionDispatch/btGhostObject.h"
  34. #include "BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h"
  35. #include "BulletCollision/NarrowPhaseCollision/btGjkPairDetector.h"
  36. #include "BulletCollision/NarrowPhaseCollision/btPointCollector.h"
  37. #include "BulletSoftBody/btSoftBodyRigidBodyCollisionConfiguration.h"
  38. #include "BulletSoftBody/btSoftRigidDynamicsWorld.h"
  39. #include "btBulletDynamicsCommon.h"
  40. #include "bullet_physics_server.h"
  41. #include "bullet_types_converter.h"
  42. #include "bullet_utilities.h"
  43. #include "constraint_bullet.h"
  44. #include "godot_collision_configuration.h"
  45. #include "godot_collision_dispatcher.h"
  46. #include "rigid_body_bullet.h"
  47. #include "servers/physics_server.h"
  48. #include "soft_body_bullet.h"
  49. #include "ustring.h"
  50. #include <assert.h>
  51. // test only
  52. //#include "scene/3d/immediate_geometry.h"
  53. BulletPhysicsDirectSpaceState::BulletPhysicsDirectSpaceState(SpaceBullet *p_space)
  54. : PhysicsDirectSpaceState(), space(p_space) {}
  55. int BulletPhysicsDirectSpaceState::intersect_point(const Vector3 &p_point, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude, uint32_t p_collision_layer, uint32_t p_object_type_mask) {
  56. if (p_result_max <= 0)
  57. return 0;
  58. btVector3 bt_point;
  59. G_TO_B(p_point, bt_point);
  60. btSphereShape sphere_point(0.f);
  61. btCollisionObject collision_object_point;
  62. collision_object_point.setCollisionShape(&sphere_point);
  63. collision_object_point.setWorldTransform(btTransform(btQuaternion::getIdentity(), bt_point));
  64. // Setup query
  65. GodotAllContactResultCallback btResult(&collision_object_point, r_results, p_result_max, &p_exclude);
  66. btResult.m_collisionFilterGroup = p_collision_layer;
  67. btResult.m_collisionFilterMask = p_object_type_mask;
  68. space->dynamicsWorld->contactTest(&collision_object_point, btResult);
  69. // The results is already populated by GodotAllConvexResultCallback
  70. return btResult.m_count;
  71. }
  72. bool BulletPhysicsDirectSpaceState::intersect_ray(const Vector3 &p_from, const Vector3 &p_to, RayResult &r_result, const Set<RID> &p_exclude, uint32_t p_collision_layer, uint32_t p_object_type_mask, bool p_pick_ray) {
  73. btVector3 btVec_from;
  74. btVector3 btVec_to;
  75. G_TO_B(p_from, btVec_from);
  76. G_TO_B(p_to, btVec_to);
  77. // setup query
  78. GodotClosestRayResultCallback btResult(btVec_from, btVec_to, &p_exclude);
  79. btResult.m_collisionFilterGroup = p_collision_layer;
  80. btResult.m_collisionFilterMask = p_object_type_mask;
  81. btResult.m_pickRay = p_pick_ray;
  82. space->dynamicsWorld->rayTest(btVec_from, btVec_to, btResult);
  83. if (btResult.hasHit()) {
  84. B_TO_G(btResult.m_hitPointWorld, r_result.position);
  85. B_TO_G(btResult.m_hitNormalWorld.normalize(), r_result.normal);
  86. CollisionObjectBullet *gObj = static_cast<CollisionObjectBullet *>(btResult.m_collisionObject->getUserPointer());
  87. if (gObj) {
  88. r_result.shape = 0;
  89. r_result.rid = gObj->get_self();
  90. r_result.collider_id = gObj->get_instance_id();
  91. r_result.collider = 0 == r_result.collider_id ? NULL : ObjectDB::get_instance(r_result.collider_id);
  92. } else {
  93. WARN_PRINTS("The raycast performed has hit a collision object that is not part of Godot scene, please check it.");
  94. }
  95. return true;
  96. } else {
  97. return false;
  98. }
  99. }
  100. int BulletPhysicsDirectSpaceState::intersect_shape(const RID &p_shape, const Transform &p_xform, float p_margin, ShapeResult *p_results, int p_result_max, const Set<RID> &p_exclude, uint32_t p_collision_layer, uint32_t p_object_type_mask) {
  101. if (p_result_max <= 0)
  102. return 0;
  103. ShapeBullet *shape = space->get_physics_server()->get_shape_owner()->get(p_shape);
  104. btConvexShape *btConvex = dynamic_cast<btConvexShape *>(shape->create_bt_shape());
  105. if (!btConvex) {
  106. bulletdelete(btConvex);
  107. ERR_PRINTS("The shape is not a convex shape, then is not supported: shape type: " + itos(shape->get_type()));
  108. return 0;
  109. }
  110. btVector3 scale_with_margin;
  111. G_TO_B(p_xform.basis.get_scale(), scale_with_margin);
  112. btConvex->setLocalScaling(scale_with_margin);
  113. btTransform bt_xform;
  114. G_TO_B(p_xform, bt_xform);
  115. btCollisionObject collision_object;
  116. collision_object.setCollisionShape(btConvex);
  117. collision_object.setWorldTransform(bt_xform);
  118. GodotAllContactResultCallback btQuery(&collision_object, p_results, p_result_max, &p_exclude);
  119. btQuery.m_collisionFilterGroup = p_collision_layer;
  120. btQuery.m_collisionFilterMask = p_object_type_mask;
  121. btQuery.m_closestDistanceThreshold = p_margin;
  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_layer, uint32_t p_object_type_mask, ShapeRestInfo *r_info) {
  127. ShapeBullet *shape = space->get_physics_server()->get_shape_owner()->get(p_shape);
  128. btConvexShape *bt_convex_shape = dynamic_cast<btConvexShape *>(shape->create_bt_shape());
  129. if (!bt_convex_shape) {
  130. bulletdelete(bt_convex_shape);
  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. btVector3 bt_motion;
  135. G_TO_B(p_motion, bt_motion);
  136. btVector3 scale_with_margin;
  137. G_TO_B(p_xform.basis.get_scale() + Vector3(p_margin, p_margin, p_margin), scale_with_margin);
  138. bt_convex_shape->setLocalScaling(scale_with_margin);
  139. btTransform bt_xform_from;
  140. G_TO_B(p_xform, 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);
  144. btResult.m_collisionFilterGroup = p_collision_layer;
  145. btResult.m_collisionFilterMask = p_object_type_mask;
  146. space->dynamicsWorld->convexSweepTest(bt_convex_shape, bt_xform_from, bt_xform_to, btResult);
  147. if (btResult.hasHit()) {
  148. if (btCollisionObject::CO_RIGID_BODY == btResult.m_hitCollisionObject->getInternalType()) {
  149. B_TO_G(static_cast<const btRigidBody *>(btResult.m_hitCollisionObject)->getVelocityInLocalPoint(btResult.m_hitPointWorld), r_info->linear_velocity);
  150. }
  151. CollisionObjectBullet *collision_object = static_cast<CollisionObjectBullet *>(btResult.m_hitCollisionObject->getUserPointer());
  152. p_closest_safe = p_closest_unsafe = btResult.m_closestHitFraction;
  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_shapePart;
  158. }
  159. bulletdelete(bt_convex_shape);
  160. return btResult.hasHit();
  161. }
  162. /// Returns the list of contacts pairs in this order: Local contact, other body contact
  163. 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_layer, uint32_t p_object_type_mask) {
  164. if (p_result_max <= 0)
  165. return 0;
  166. ShapeBullet *shape = space->get_physics_server()->get_shape_owner()->get(p_shape);
  167. btConvexShape *btConvex = dynamic_cast<btConvexShape *>(shape->create_bt_shape());
  168. if (!btConvex) {
  169. bulletdelete(btConvex);
  170. ERR_PRINTS("The shape is not a convex shape, then is not supported: shape type: " + itos(shape->get_type()));
  171. return 0;
  172. }
  173. btVector3 scale_with_margin;
  174. G_TO_B(p_shape_xform.basis.get_scale(), scale_with_margin);
  175. btConvex->setLocalScaling(scale_with_margin);
  176. btTransform bt_xform;
  177. G_TO_B(p_shape_xform, 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 = p_collision_layer;
  183. btQuery.m_collisionFilterMask = p_object_type_mask;
  184. btQuery.m_closestDistanceThreshold = p_margin;
  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_layer, uint32_t p_object_type_mask) {
  191. ShapeBullet *shape = space->get_physics_server()->get_shape_owner()->get(p_shape);
  192. btConvexShape *btConvex = dynamic_cast<btConvexShape *>(shape->create_bt_shape());
  193. if (!btConvex) {
  194. bulletdelete(btConvex);
  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. btVector3 scale_with_margin;
  199. G_TO_B(p_shape_xform.basis.get_scale() + Vector3(p_margin, p_margin, p_margin), scale_with_margin);
  200. btConvex->setLocalScaling(scale_with_margin);
  201. btTransform bt_xform;
  202. G_TO_B(p_shape_xform, bt_xform);
  203. btCollisionObject collision_object;
  204. collision_object.setCollisionShape(btConvex);
  205. collision_object.setWorldTransform(bt_xform);
  206. GodotRestInfoContactResultCallback btQuery(&collision_object, r_info, &p_exclude);
  207. btQuery.m_collisionFilterGroup = p_collision_layer;
  208. btQuery.m_collisionFilterMask = p_object_type_mask;
  209. btQuery.m_closestDistanceThreshold = p_margin;
  210. space->dynamicsWorld->contactTest(&collision_object, btQuery);
  211. bulletdelete(btConvex);
  212. if (btQuery.m_collided) {
  213. if (btCollisionObject::CO_RIGID_BODY == btQuery.m_rest_info_collision_object->getInternalType()) {
  214. B_TO_G(static_cast<const btRigidBody *>(btQuery.m_rest_info_collision_object)->getVelocityInLocalPoint(btQuery.m_rest_info_bt_point), r_info->linear_velocity);
  215. }
  216. B_TO_G(btQuery.m_rest_info_bt_point, r_info->point);
  217. }
  218. return btQuery.m_collided;
  219. }
  220. Vector3 BulletPhysicsDirectSpaceState::get_closest_point_to_object_volume(RID p_object, const Vector3 p_point) const {
  221. RigidCollisionObjectBullet *rigid_object = space->get_physics_server()->get_rigid_collisin_object(p_object);
  222. ERR_FAIL_COND_V(!rigid_object, Vector3());
  223. btVector3 out_closest_point(0, 0, 0);
  224. btScalar out_distance = 1e20;
  225. btVector3 bt_point;
  226. G_TO_B(p_point, bt_point);
  227. btGjkEpaPenetrationDepthSolver gjk_epa_pen_solver;
  228. btVoronoiSimplexSolver gjk_simplex_solver;
  229. gjk_simplex_solver.setEqualVertexThreshold(0.);
  230. btSphereShape point_shape(0.);
  231. btCollisionShape *shape;
  232. btConvexShape *convex_shape;
  233. btTransform child_transform;
  234. btTransform body_transform(rigid_object->get_bt_collision_object()->getWorldTransform());
  235. btGjkPairDetector::ClosestPointInput input;
  236. input.m_transformA.getBasis().setIdentity();
  237. input.m_transformA.setOrigin(bt_point);
  238. bool shapes_found = false;
  239. btCompoundShape *compound = rigid_object->get_compound_shape();
  240. for (int i = compound->getNumChildShapes() - 1; 0 <= i; --i) {
  241. shape = compound->getChildShape(i);
  242. if (shape->isConvex()) {
  243. child_transform = compound->getChildTransform(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, &gjk_simplex_solver, &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(bool p_create_soft_world)
  266. : broadphase(NULL),
  267. dispatcher(NULL),
  268. solver(NULL),
  269. collisionConfiguration(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. create_empty_world(p_create_soft_world);
  278. direct_access = memnew(BulletPhysicsDirectSpaceState(this));
  279. }
  280. SpaceBullet::~SpaceBullet() {
  281. memdelete(direct_access);
  282. destroy_world();
  283. }
  284. void SpaceBullet::flush_queries() {
  285. const btCollisionObjectArray &colObjArray = dynamicsWorld->getCollisionObjectArray();
  286. for (int i = colObjArray.size() - 1; 0 <= i; --i) {
  287. static_cast<CollisionObjectBullet *>(colObjArray[i]->getUserPointer())->dispatch_callbacks();
  288. }
  289. }
  290. void SpaceBullet::step(real_t p_delta_time) {
  291. dynamicsWorld->stepSimulation(p_delta_time, 0, 0);
  292. }
  293. void SpaceBullet::set_param(PhysicsServer::AreaParameter p_param, const Variant &p_value) {
  294. assert(dynamicsWorld);
  295. switch (p_param) {
  296. case PhysicsServer::AREA_PARAM_GRAVITY:
  297. gravityMagnitude = p_value;
  298. update_gravity();
  299. break;
  300. case PhysicsServer::AREA_PARAM_GRAVITY_VECTOR:
  301. gravityDirection = p_value;
  302. update_gravity();
  303. break;
  304. case PhysicsServer::AREA_PARAM_LINEAR_DAMP:
  305. case PhysicsServer::AREA_PARAM_ANGULAR_DAMP:
  306. break; // No damp
  307. case PhysicsServer::AREA_PARAM_PRIORITY:
  308. // Priority is always 0, the lower
  309. break;
  310. case PhysicsServer::AREA_PARAM_GRAVITY_IS_POINT:
  311. case PhysicsServer::AREA_PARAM_GRAVITY_DISTANCE_SCALE:
  312. case PhysicsServer::AREA_PARAM_GRAVITY_POINT_ATTENUATION:
  313. break;
  314. default:
  315. WARN_PRINTS("This set parameter (" + itos(p_param) + ") is ignored, the SpaceBullet doesn't support it.");
  316. break;
  317. }
  318. }
  319. Variant SpaceBullet::get_param(PhysicsServer::AreaParameter p_param) {
  320. switch (p_param) {
  321. case PhysicsServer::AREA_PARAM_GRAVITY:
  322. return gravityMagnitude;
  323. case PhysicsServer::AREA_PARAM_GRAVITY_VECTOR:
  324. return gravityDirection;
  325. case PhysicsServer::AREA_PARAM_LINEAR_DAMP:
  326. case PhysicsServer::AREA_PARAM_ANGULAR_DAMP:
  327. return 0; // No damp
  328. case PhysicsServer::AREA_PARAM_PRIORITY:
  329. return 0; // Priority is always 0, the lower
  330. case PhysicsServer::AREA_PARAM_GRAVITY_IS_POINT:
  331. return false;
  332. case PhysicsServer::AREA_PARAM_GRAVITY_DISTANCE_SCALE:
  333. return 0;
  334. case PhysicsServer::AREA_PARAM_GRAVITY_POINT_ATTENUATION:
  335. return 0;
  336. default:
  337. WARN_PRINTS("This get parameter (" + itos(p_param) + ") is ignored, the SpaceBullet doesn't support it.");
  338. return Variant();
  339. }
  340. }
  341. void SpaceBullet::set_param(PhysicsServer::SpaceParameter p_param, real_t p_value) {
  342. switch (p_param) {
  343. case PhysicsServer::SPACE_PARAM_CONTACT_RECYCLE_RADIUS:
  344. case PhysicsServer::SPACE_PARAM_CONTACT_MAX_SEPARATION:
  345. case PhysicsServer::SPACE_PARAM_BODY_MAX_ALLOWED_PENETRATION:
  346. case PhysicsServer::SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_THRESHOLD:
  347. case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_THRESHOLD:
  348. case PhysicsServer::SPACE_PARAM_BODY_TIME_TO_SLEEP:
  349. case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_DAMP_RATIO:
  350. case PhysicsServer::SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS:
  351. default:
  352. WARN_PRINTS("This set parameter (" + itos(p_param) + ") is ignored, the SpaceBullet doesn't support it.");
  353. break;
  354. }
  355. }
  356. real_t SpaceBullet::get_param(PhysicsServer::SpaceParameter p_param) {
  357. switch (p_param) {
  358. case PhysicsServer::SPACE_PARAM_CONTACT_RECYCLE_RADIUS:
  359. case PhysicsServer::SPACE_PARAM_CONTACT_MAX_SEPARATION:
  360. case PhysicsServer::SPACE_PARAM_BODY_MAX_ALLOWED_PENETRATION:
  361. case PhysicsServer::SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_THRESHOLD:
  362. case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_THRESHOLD:
  363. case PhysicsServer::SPACE_PARAM_BODY_TIME_TO_SLEEP:
  364. case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_DAMP_RATIO:
  365. case PhysicsServer::SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS:
  366. default:
  367. WARN_PRINTS("The SpaceBullet doesn't support this get parameter (" + itos(p_param) + "), 0 is returned.");
  368. return 0.f;
  369. }
  370. }
  371. void SpaceBullet::add_area(AreaBullet *p_area) {
  372. areas.push_back(p_area);
  373. dynamicsWorld->addCollisionObject(p_area->get_bt_ghost(), p_area->get_collision_layer(), p_area->get_collision_mask());
  374. }
  375. void SpaceBullet::remove_area(AreaBullet *p_area) {
  376. areas.erase(p_area);
  377. dynamicsWorld->removeCollisionObject(p_area->get_bt_ghost());
  378. }
  379. void SpaceBullet::reload_collision_filters(AreaBullet *p_area) {
  380. // This is necessary to change collision filter
  381. dynamicsWorld->removeCollisionObject(p_area->get_bt_ghost());
  382. dynamicsWorld->addCollisionObject(p_area->get_bt_ghost(), p_area->get_collision_layer(), p_area->get_collision_mask());
  383. }
  384. void SpaceBullet::add_rigid_body(RigidBodyBullet *p_body) {
  385. if (p_body->is_static()) {
  386. dynamicsWorld->addCollisionObject(p_body->get_bt_rigid_body(), p_body->get_collision_layer(), p_body->get_collision_mask());
  387. } else {
  388. dynamicsWorld->addRigidBody(p_body->get_bt_rigid_body(), p_body->get_collision_layer(), p_body->get_collision_mask());
  389. }
  390. }
  391. void SpaceBullet::remove_rigid_body(RigidBodyBullet *p_body) {
  392. if (p_body->is_static()) {
  393. dynamicsWorld->removeCollisionObject(p_body->get_bt_rigid_body());
  394. } else {
  395. dynamicsWorld->removeRigidBody(p_body->get_bt_rigid_body());
  396. }
  397. }
  398. void SpaceBullet::reload_collision_filters(RigidBodyBullet *p_body) {
  399. // This is necessary to change collision filter
  400. remove_rigid_body(p_body);
  401. add_rigid_body(p_body);
  402. }
  403. void SpaceBullet::add_soft_body(SoftBodyBullet *p_body) {
  404. if (is_using_soft_world()) {
  405. if (p_body->get_bt_soft_body()) {
  406. static_cast<btSoftRigidDynamicsWorld *>(dynamicsWorld)->addSoftBody(p_body->get_bt_soft_body(), p_body->get_collision_layer(), p_body->get_collision_mask());
  407. }
  408. } else {
  409. ERR_PRINT("This soft body can't be added to non soft world");
  410. }
  411. }
  412. void SpaceBullet::remove_soft_body(SoftBodyBullet *p_body) {
  413. if (is_using_soft_world()) {
  414. if (p_body->get_bt_soft_body()) {
  415. static_cast<btSoftRigidDynamicsWorld *>(dynamicsWorld)->removeSoftBody(p_body->get_bt_soft_body());
  416. }
  417. }
  418. }
  419. void SpaceBullet::reload_collision_filters(SoftBodyBullet *p_body) {
  420. // This is necessary to change collision filter
  421. remove_soft_body(p_body);
  422. add_soft_body(p_body);
  423. }
  424. void SpaceBullet::add_constraint(ConstraintBullet *p_constraint, bool disableCollisionsBetweenLinkedBodies) {
  425. p_constraint->set_space(this);
  426. dynamicsWorld->addConstraint(p_constraint->get_bt_constraint(), disableCollisionsBetweenLinkedBodies);
  427. }
  428. void SpaceBullet::remove_constraint(ConstraintBullet *p_constraint) {
  429. dynamicsWorld->removeConstraint(p_constraint->get_bt_constraint());
  430. }
  431. int SpaceBullet::get_num_collision_objects() const {
  432. return dynamicsWorld->getNumCollisionObjects();
  433. }
  434. void SpaceBullet::remove_all_collision_objects() {
  435. for (int i = dynamicsWorld->getNumCollisionObjects() - 1; 0 <= i; --i) {
  436. btCollisionObject *btObj = dynamicsWorld->getCollisionObjectArray()[i];
  437. CollisionObjectBullet *colObj = static_cast<CollisionObjectBullet *>(btObj->getUserPointer());
  438. colObj->set_space(NULL);
  439. }
  440. }
  441. void onBulletPreTickCallback(btDynamicsWorld *p_dynamicsWorld, btScalar timeStep) {
  442. static_cast<SpaceBullet *>(p_dynamicsWorld->getWorldUserInfo())->flush_queries();
  443. }
  444. void onBulletTickCallback(btDynamicsWorld *p_dynamicsWorld, btScalar timeStep) {
  445. // Notify all Collision objects the collision checker is started
  446. const btCollisionObjectArray &colObjArray = p_dynamicsWorld->getCollisionObjectArray();
  447. for (int i = colObjArray.size() - 1; 0 <= i; --i) {
  448. CollisionObjectBullet *colObj = static_cast<CollisionObjectBullet *>(colObjArray[i]->getUserPointer());
  449. assert(NULL != colObj);
  450. colObj->on_collision_checker_start();
  451. }
  452. SpaceBullet *sb = static_cast<SpaceBullet *>(p_dynamicsWorld->getWorldUserInfo());
  453. sb->check_ghost_overlaps();
  454. sb->check_body_collision();
  455. }
  456. BulletPhysicsDirectSpaceState *SpaceBullet::get_direct_state() {
  457. return direct_access;
  458. }
  459. btScalar calculateGodotCombinedRestitution(const btCollisionObject *body0, const btCollisionObject *body1) {
  460. return MAX(body0->getRestitution(), body1->getRestitution());
  461. }
  462. void SpaceBullet::create_empty_world(bool p_create_soft_world) {
  463. assert(NULL == broadphase);
  464. assert(NULL == dispatcher);
  465. assert(NULL == solver);
  466. assert(NULL == collisionConfiguration);
  467. assert(NULL == dynamicsWorld);
  468. assert(NULL == ghostPairCallback);
  469. assert(NULL == godotFilterCallback);
  470. void *world_mem;
  471. if (p_create_soft_world) {
  472. world_mem = malloc(sizeof(btSoftRigidDynamicsWorld));
  473. } else {
  474. world_mem = malloc(sizeof(btDiscreteDynamicsWorld));
  475. }
  476. if (p_create_soft_world) {
  477. collisionConfiguration = bulletnew(btSoftBodyRigidBodyCollisionConfiguration);
  478. } else {
  479. collisionConfiguration = bulletnew(GodotCollisionConfiguration(static_cast<btDiscreteDynamicsWorld *>(world_mem)));
  480. }
  481. dispatcher = bulletnew(GodotCollisionDispatcher(collisionConfiguration));
  482. broadphase = bulletnew(btDbvtBroadphase);
  483. solver = bulletnew(btSequentialImpulseConstraintSolver);
  484. if (p_create_soft_world) {
  485. dynamicsWorld = new (world_mem) btSoftRigidDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
  486. soft_body_world_info = bulletnew(btSoftBodyWorldInfo);
  487. } else {
  488. dynamicsWorld = new (world_mem) btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
  489. }
  490. ghostPairCallback = bulletnew(btGhostPairCallback);
  491. godotFilterCallback = bulletnew(GodotFilterCallback);
  492. gCalculateCombinedRestitutionCallback = &calculateGodotCombinedRestitution;
  493. dynamicsWorld->setWorldUserInfo(this);
  494. dynamicsWorld->setInternalTickCallback(onBulletPreTickCallback, this, true);
  495. dynamicsWorld->setInternalTickCallback(onBulletTickCallback, this, false);
  496. dynamicsWorld->getBroadphase()->getOverlappingPairCache()->setInternalGhostPairCallback(ghostPairCallback); // Setup ghost check
  497. dynamicsWorld->getPairCache()->setOverlapFilterCallback(godotFilterCallback);
  498. if (soft_body_world_info) {
  499. soft_body_world_info->m_broadphase = broadphase;
  500. soft_body_world_info->m_dispatcher = dispatcher;
  501. soft_body_world_info->m_sparsesdf.Initialize();
  502. }
  503. update_gravity();
  504. }
  505. void SpaceBullet::destroy_world() {
  506. assert(NULL != broadphase);
  507. assert(NULL != dispatcher);
  508. assert(NULL != solver);
  509. assert(NULL != collisionConfiguration);
  510. assert(NULL != dynamicsWorld);
  511. assert(NULL != ghostPairCallback);
  512. assert(NULL != godotFilterCallback);
  513. /// The world elements (like: Collision Objects, Constraints, Shapes) are managed by godot
  514. dynamicsWorld->getBroadphase()->getOverlappingPairCache()->setInternalGhostPairCallback(NULL);
  515. dynamicsWorld->getPairCache()->setOverlapFilterCallback(NULL);
  516. bulletdelete(ghostPairCallback);
  517. bulletdelete(godotFilterCallback);
  518. // Deallocate world
  519. dynamicsWorld->~btDiscreteDynamicsWorld();
  520. free(dynamicsWorld);
  521. dynamicsWorld = NULL;
  522. bulletdelete(solver);
  523. bulletdelete(broadphase);
  524. bulletdelete(dispatcher);
  525. bulletdelete(collisionConfiguration);
  526. bulletdelete(soft_body_world_info);
  527. }
  528. void SpaceBullet::check_ghost_overlaps() {
  529. /// Algorith support variables
  530. btGjkEpaPenetrationDepthSolver gjk_epa_pen_solver;
  531. btVoronoiSimplexSolver gjk_simplex_solver;
  532. gjk_simplex_solver.setEqualVertexThreshold(0.f);
  533. btConvexShape *other_body_shape;
  534. btConvexShape *area_shape;
  535. btGjkPairDetector::ClosestPointInput gjk_input;
  536. AreaBullet *area;
  537. RigidCollisionObjectBullet *otherObject;
  538. int x(-1), i(-1), y(-1), z(-1), indexOverlap(-1);
  539. /// For each areas
  540. for (x = areas.size() - 1; 0 <= x; --x) {
  541. area = areas[x];
  542. if (!area->is_monitoring())
  543. continue;
  544. /// 1. Reset all states
  545. for (i = area->overlappingObjects.size() - 1; 0 <= i; --i) {
  546. AreaBullet::OverlappingObjectData &otherObj = area->overlappingObjects[i];
  547. // This check prevent the overwrite of ENTER state
  548. // if this function is called more times before dispatchCallbacks
  549. if (otherObj.state != AreaBullet::OVERLAP_STATE_ENTER) {
  550. otherObj.state = AreaBullet::OVERLAP_STATE_DIRTY;
  551. }
  552. }
  553. /// 2. Check all overlapping objects using GJK
  554. const btAlignedObjectArray<btCollisionObject *> ghostOverlaps = area->get_bt_ghost()->getOverlappingPairs();
  555. // For each overlapping
  556. for (i = ghostOverlaps.size() - 1; 0 <= i; --i) {
  557. if (!(ghostOverlaps[i]->getUserIndex() == CollisionObjectBullet::TYPE_RIGID_BODY || ghostOverlaps[i]->getUserIndex() == CollisionObjectBullet::TYPE_AREA))
  558. continue;
  559. otherObject = static_cast<RigidCollisionObjectBullet *>(ghostOverlaps[i]->getUserPointer());
  560. bool hasOverlap = false;
  561. // For each area shape
  562. for (y = area->get_compound_shape()->getNumChildShapes() - 1; 0 <= y; --y) {
  563. if (!area->get_compound_shape()->getChildShape(y)->isConvex())
  564. continue;
  565. gjk_input.m_transformA = area->get_transform__bullet() * area->get_compound_shape()->getChildTransform(y);
  566. area_shape = static_cast<btConvexShape *>(area->get_compound_shape()->getChildShape(y));
  567. // For each other object shape
  568. for (z = otherObject->get_compound_shape()->getNumChildShapes() - 1; 0 <= z; --z) {
  569. if (!otherObject->get_compound_shape()->getChildShape(z)->isConvex())
  570. continue;
  571. other_body_shape = static_cast<btConvexShape *>(otherObject->get_compound_shape()->getChildShape(z));
  572. gjk_input.m_transformB = otherObject->get_transform__bullet() * otherObject->get_compound_shape()->getChildTransform(z);
  573. btPointCollector result;
  574. btGjkPairDetector gjk_pair_detector(area_shape, other_body_shape, &gjk_simplex_solver, &gjk_epa_pen_solver);
  575. gjk_pair_detector.getClosestPoints(gjk_input, result, 0);
  576. if (0 >= result.m_distance) {
  577. hasOverlap = true;
  578. goto collision_found;
  579. }
  580. } // ~For each other object shape
  581. } // ~For each area shape
  582. collision_found:
  583. if (!hasOverlap)
  584. continue;
  585. indexOverlap = area->find_overlapping_object(otherObject);
  586. if (-1 == indexOverlap) {
  587. // Not found
  588. area->add_overlap(otherObject);
  589. } else {
  590. // Found
  591. area->put_overlap_as_inside(indexOverlap);
  592. }
  593. }
  594. /// 3. Remove not overlapping
  595. for (i = area->overlappingObjects.size() - 1; 0 <= i; --i) {
  596. // If the overlap has DIRTY state it means that it's no more overlapping
  597. if (area->overlappingObjects[i].state == AreaBullet::OVERLAP_STATE_DIRTY) {
  598. area->put_overlap_as_exit(i);
  599. }
  600. }
  601. }
  602. }
  603. void SpaceBullet::check_body_collision() {
  604. #ifdef DEBUG_ENABLED
  605. reset_debug_contact_count();
  606. #endif
  607. const int numManifolds = dynamicsWorld->getDispatcher()->getNumManifolds();
  608. for (int i = 0; i < numManifolds; ++i) {
  609. btPersistentManifold *contactManifold = dynamicsWorld->getDispatcher()->getManifoldByIndexInternal(i);
  610. const btCollisionObject *obA = contactManifold->getBody0();
  611. const btCollisionObject *obB = contactManifold->getBody1();
  612. if (btCollisionObject::CO_RIGID_BODY != obA->getInternalType() || btCollisionObject::CO_RIGID_BODY != obB->getInternalType()) {
  613. // This checks is required to be sure the ghost object is skipped
  614. // The ghost object "getUserPointer" return the BodyBullet owner so this check is required
  615. continue;
  616. }
  617. // Asserts all Godot objects are assigned
  618. assert(NULL != obA->getUserPointer());
  619. assert(NULL != obB->getUserPointer());
  620. // I know this static cast is a bit risky. But I'm checking its type just after it.
  621. // This allow me to avoid a lot of other cast and checks
  622. RigidBodyBullet *bodyA = static_cast<RigidBodyBullet *>(obA->getUserPointer());
  623. RigidBodyBullet *bodyB = static_cast<RigidBodyBullet *>(obB->getUserPointer());
  624. if (CollisionObjectBullet::TYPE_RIGID_BODY == bodyA->getType() && CollisionObjectBullet::TYPE_RIGID_BODY == bodyB->getType()) {
  625. if (!bodyA->can_add_collision() && !bodyB->can_add_collision()) {
  626. continue;
  627. }
  628. const int numContacts = contactManifold->getNumContacts();
  629. #define REPORT_ALL_CONTACTS 0
  630. #if REPORT_ALL_CONTACTS
  631. for (int j = 0; j < numContacts; j++) {
  632. btManifoldPoint &pt = contactManifold->getContactPoint(j);
  633. #else
  634. // Since I don't need report all contacts for these objects, I'll report only the first
  635. if (numContacts) {
  636. btManifoldPoint &pt = contactManifold->getContactPoint(0);
  637. #endif
  638. Vector3 collisionWorldPosition;
  639. Vector3 collisionLocalPosition;
  640. Vector3 normalOnB;
  641. B_TO_G(pt.m_normalWorldOnB, normalOnB);
  642. if (bodyA->can_add_collision()) {
  643. B_TO_G(pt.getPositionWorldOnB(), collisionWorldPosition);
  644. /// pt.m_localPointB Doesn't report the exact point in local space
  645. B_TO_G(pt.getPositionWorldOnB() - obB->getWorldTransform().getOrigin(), collisionLocalPosition);
  646. bodyA->add_collision_object(bodyB, collisionWorldPosition, collisionLocalPosition, normalOnB, pt.m_index1, pt.m_index0);
  647. }
  648. if (bodyB->can_add_collision()) {
  649. B_TO_G(pt.getPositionWorldOnA(), collisionWorldPosition);
  650. /// pt.m_localPointA Doesn't report the exact point in local space
  651. B_TO_G(pt.getPositionWorldOnA() - obA->getWorldTransform().getOrigin(), collisionLocalPosition);
  652. bodyB->add_collision_object(bodyA, collisionWorldPosition, collisionLocalPosition, normalOnB * -1, pt.m_index0, pt.m_index1);
  653. }
  654. #ifdef DEBUG_ENABLED
  655. if (is_debugging_contacts()) {
  656. add_debug_contact(collisionWorldPosition);
  657. }
  658. #endif
  659. }
  660. }
  661. }
  662. }
  663. void SpaceBullet::update_gravity() {
  664. btVector3 btGravity;
  665. G_TO_B(gravityDirection * gravityMagnitude, btGravity);
  666. dynamicsWorld->setGravity(btGravity);
  667. if (soft_body_world_info) {
  668. soft_body_world_info->m_gravity = btGravity;
  669. }
  670. }
  671. /// IMPORTANT: Please don't turn it ON this is not managed correctly!!
  672. /// I'm leaving this here just for future tests.
  673. /// Debug motion and normal vector drawing
  674. #define debug_test_motion 0
  675. #if debug_test_motion
  676. static ImmediateGeometry *motionVec(NULL);
  677. static ImmediateGeometry *normalLine(NULL);
  678. static Ref<SpatialMaterial> red_mat;
  679. static Ref<SpatialMaterial> blue_mat;
  680. #endif
  681. #define IGNORE_AREAS_TRUE true
  682. bool SpaceBullet::test_body_motion(RigidBodyBullet *p_body, const Transform &p_from, const Vector3 &p_motion, real_t p_margin, PhysicsServer::MotionResult *r_result) {
  683. #if debug_test_motion
  684. /// Yes I know this is not good, but I've used it as fast debugging.
  685. /// I'm leaving it here just for speedup the other eventual debugs
  686. if (!normalLine) {
  687. motionVec = memnew(ImmediateGeometry);
  688. normalLine = memnew(ImmediateGeometry);
  689. SceneTree::get_singleton()->get_current_scene()->add_child(motionVec);
  690. SceneTree::get_singleton()->get_current_scene()->add_child(normalLine);
  691. red_mat = Ref<SpatialMaterial>(memnew(SpatialMaterial));
  692. red_mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  693. red_mat->set_line_width(20.0);
  694. red_mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  695. red_mat->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  696. red_mat->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
  697. red_mat->set_albedo(Color(1, 0, 0, 1));
  698. motionVec->set_material_override(red_mat);
  699. blue_mat = Ref<SpatialMaterial>(memnew(SpatialMaterial));
  700. blue_mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  701. blue_mat->set_line_width(20.0);
  702. blue_mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  703. blue_mat->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  704. blue_mat->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
  705. blue_mat->set_albedo(Color(0, 0, 1, 1));
  706. normalLine->set_material_override(blue_mat);
  707. }
  708. #endif
  709. ///// Release all generated manifolds
  710. //{
  711. // if(p_body->get_kinematic_utilities()){
  712. // for(int i= p_body->get_kinematic_utilities()->m_generatedManifold.size()-1; 0<=i; --i){
  713. // dispatcher->releaseManifold( p_body->get_kinematic_utilities()->m_generatedManifold[i] );
  714. // }
  715. // p_body->get_kinematic_utilities()->m_generatedManifold.clear();
  716. // }
  717. //}
  718. btVector3 recover_initial_position;
  719. recover_initial_position.setZero();
  720. /// I'm performing the unstack at the end of movement so I'm sure the player is unstacked even after the movement.
  721. /// I've removed the initial unstack because this is useful just for the first tick since after the first
  722. /// the real unstack is performed at the end of process.
  723. /// However I'm leaving here the old code.
  724. /// Note: It has a bug when two shapes touches something simultaneously the body is moved too much away (I'm not fixing it for the reason written above).
  725. #define INITIAL_UNSTACK 0
  726. #if !INITIAL_UNSTACK
  727. btTransform body_safe_position;
  728. G_TO_B(p_from, body_safe_position);
  729. //btTransform body_unsafe_positino;
  730. //G_TO_B(p_from, body_unsafe_positino);
  731. #else
  732. btTransform body_safe_position;
  733. btTransform body_unsafe_positino;
  734. { /// Phase one - multi shapes depenetration using margin
  735. G_TO_B(p_from, body_safe_position);
  736. G_TO_B(p_from, body_unsafe_positino);
  737. // MAX_PENETRATION_DEPTH Is useful have the ghost a bit penetrated so I can detect the floor easily
  738. recover_from_penetration(p_body, body_safe_position, MAX_PENETRATION_DEPTH, /* p_depenetration_speed */ 1, recover_initial_position);
  739. /// Not required if I put p_depenetration_speed = 1
  740. //for(int t = 0; t<4; ++t){
  741. // if(!recover_from_penetration(p_body, body_safe_position, MAX_PENETRATION_DEPTH, /* p_depenetration_speed */0.2, recover_initial_position)){
  742. // break;
  743. // }
  744. //}
  745. // Add recover position to "From" and "To" transforms
  746. body_safe_position.getOrigin() += recover_initial_position;
  747. }
  748. #endif
  749. int shape_most_recovered(-1);
  750. btVector3 recovered_motion;
  751. G_TO_B(p_motion, recovered_motion);
  752. const int shape_count(p_body->get_shape_count());
  753. { /// phase two - sweep test, from a secure position without margin
  754. #if debug_test_motion
  755. Vector3 sup_line;
  756. B_TO_G(body_safe_position.getOrigin(), sup_line);
  757. motionVec->clear();
  758. motionVec->begin(Mesh::PRIMITIVE_LINES, NULL);
  759. motionVec->add_vertex(sup_line);
  760. motionVec->add_vertex(sup_line + p_motion * 10);
  761. motionVec->end();
  762. #endif
  763. for (int shIndex = 0; shIndex < shape_count; ++shIndex) {
  764. if (p_body->is_shape_disabled(shIndex)) {
  765. continue;
  766. }
  767. btConvexShape *convex_shape_test(dynamic_cast<btConvexShape *>(p_body->get_bt_shape(shIndex)));
  768. if (!convex_shape_test) {
  769. // Skip no convex shape
  770. continue;
  771. }
  772. btTransform shape_xform_from;
  773. G_TO_B(p_body->get_shape_transform(shIndex), shape_xform_from);
  774. //btTransform shape_xform_to(shape_xform_from);
  775. // Add local shape transform
  776. shape_xform_from.getOrigin() += body_safe_position.getOrigin();
  777. shape_xform_from.getBasis() *= body_safe_position.getBasis();
  778. btTransform shape_xform_to(shape_xform_from);
  779. //shape_xform_to.getOrigin() += body_unsafe_positino.getOrigin();
  780. //shape_xform_to.getBasis() *= body_unsafe_positino.getBasis();
  781. shape_xform_to.getOrigin() += recovered_motion;
  782. GodotKinClosestConvexResultCallback btResult(shape_xform_from.getOrigin(), shape_xform_to.getOrigin(), p_body, IGNORE_AREAS_TRUE);
  783. btResult.m_collisionFilterGroup = p_body->get_collision_layer();
  784. btResult.m_collisionFilterMask = p_body->get_collision_mask();
  785. dynamicsWorld->convexSweepTest(convex_shape_test, shape_xform_from, shape_xform_to, btResult);
  786. if (btResult.hasHit()) {
  787. //recovered_motion *= btResult.m_closestHitFraction;
  788. /// Since for each sweep test I fix the motion of new shapes in base the recover result,
  789. /// if another shape will hit something it means that has a deepest recovering respect the previous shape
  790. shape_most_recovered = shIndex;
  791. }
  792. }
  793. }
  794. bool hasHit = false;
  795. { /// Phase three - contact test with margin
  796. btGhostObject *ghost = p_body->get_kinematic_utilities()->m_ghostObject;
  797. GodotRecoverAndClosestContactResultCallback result_callabck;
  798. if (false && 0 <= shape_most_recovered) {
  799. result_callabck.m_self_object = p_body;
  800. result_callabck.m_ignore_areas = IGNORE_AREAS_TRUE;
  801. result_callabck.m_collisionFilterGroup = p_body->get_collision_layer();
  802. result_callabck.m_collisionFilterMask = p_body->get_collision_mask();
  803. const RigidBodyBullet::KinematicShape &kin(p_body->get_kinematic_utilities()->m_shapes[shape_most_recovered]);
  804. ghost->setCollisionShape(kin.shape);
  805. ghost->setWorldTransform(body_safe_position);
  806. ghost->getWorldTransform().getOrigin() += recovered_motion;
  807. ghost->getWorldTransform().getOrigin() += kin.transform.getOrigin();
  808. ghost->getWorldTransform().getBasis() *= kin.transform.getBasis();
  809. dynamicsWorld->contactTest(ghost, result_callabck);
  810. recovered_motion += result_callabck.m_recover_penetration; // Required to avoid all kind of penetration
  811. } else {
  812. // The sweep result does not return a penetrated shape, so I've to check all shapes
  813. // Then return the most penetrated shape
  814. GodotRecoverAndClosestContactResultCallback iter_result_callabck(p_body, IGNORE_AREAS_TRUE);
  815. iter_result_callabck.m_collisionFilterGroup = p_body->get_collision_layer();
  816. iter_result_callabck.m_collisionFilterMask = p_body->get_collision_mask();
  817. btScalar max_penetration(99999999999);
  818. for (int i = 0; i < shape_count; ++i) {
  819. const RigidBodyBullet::KinematicShape &kin(p_body->get_kinematic_utilities()->m_shapes[i]);
  820. if (!kin.is_active()) {
  821. continue;
  822. }
  823. // reset callback each function
  824. iter_result_callabck.reset();
  825. ghost->setCollisionShape(kin.shape);
  826. ghost->setWorldTransform(body_safe_position);
  827. ghost->getWorldTransform().getOrigin() += recovered_motion;
  828. ghost->getWorldTransform().getOrigin() += kin.transform.getOrigin();
  829. ghost->getWorldTransform().getBasis() *= kin.transform.getBasis();
  830. dynamicsWorld->contactTest(ghost, iter_result_callabck);
  831. if (iter_result_callabck.hasHit()) {
  832. if (max_penetration > iter_result_callabck.m_penetration_distance) {
  833. max_penetration = iter_result_callabck.m_penetration_distance;
  834. shape_most_recovered = i;
  835. // This is more penetrated
  836. result_callabck.m_pointCollisionObject = iter_result_callabck.m_pointCollisionObject;
  837. result_callabck.m_pointNormalWorld = iter_result_callabck.m_pointNormalWorld;
  838. result_callabck.m_pointWorld = iter_result_callabck.m_pointWorld;
  839. result_callabck.m_penetration_distance = iter_result_callabck.m_penetration_distance;
  840. result_callabck.m_other_compound_shape_index = iter_result_callabck.m_other_compound_shape_index;
  841. recovered_motion += iter_result_callabck.m_recover_penetration; // Required to avoid all kind of penetration
  842. }
  843. }
  844. }
  845. }
  846. hasHit = result_callabck.hasHit();
  847. if (r_result) {
  848. B_TO_G(recovered_motion + recover_initial_position, r_result->motion);
  849. if (hasHit) {
  850. if (btCollisionObject::CO_RIGID_BODY != result_callabck.m_pointCollisionObject->getInternalType()) {
  851. ERR_PRINT("The collision is not against a rigid body. Please check what's going on.");
  852. goto EndExecution;
  853. }
  854. const btRigidBody *btRigid = static_cast<const btRigidBody *>(result_callabck.m_pointCollisionObject);
  855. CollisionObjectBullet *collisionObject = static_cast<CollisionObjectBullet *>(btRigid->getUserPointer());
  856. r_result->remainder = p_motion - r_result->motion; // is the remaining movements
  857. B_TO_G(result_callabck.m_pointWorld, r_result->collision_point);
  858. B_TO_G(result_callabck.m_pointNormalWorld, r_result->collision_normal);
  859. B_TO_G(btRigid->getVelocityInLocalPoint(result_callabck.m_pointWorld - btRigid->getWorldTransform().getOrigin()), r_result->collider_velocity); // It calculates velocity at point and assign it using special function Bullet_to_Godot
  860. r_result->collider = collisionObject->get_self();
  861. r_result->collider_id = collisionObject->get_instance_id();
  862. r_result->collider_shape = result_callabck.m_other_compound_shape_index;
  863. r_result->collision_local_shape = shape_most_recovered;
  864. //{ /// Add manifold point to manage collisions
  865. // btPersistentManifold* manifold = dynamicsWorld->getDispatcher()->getNewManifold(p_body->getBtBody(), btRigid);
  866. // btManifoldPoint manifoldPoint(result_callabck.m_pointWorld, result_callabck.m_pointWorld, result_callabck.m_pointNormalWorld, result_callabck.m_penetration_distance);
  867. // manifoldPoint.m_index0 = r_result->collision_local_shape;
  868. // manifoldPoint.m_index1 = r_result->collider_shape;
  869. // manifold->addManifoldPoint(manifoldPoint);
  870. // p_body->get_kinematic_utilities()->m_generatedManifold.push_back(manifold);
  871. //}
  872. #if debug_test_motion
  873. Vector3 sup_line2;
  874. B_TO_G(recovered_motion, sup_line2);
  875. //Vector3 sup_pos;
  876. //B_TO_G( pt.getPositionWorldOnB(), sup_pos);
  877. normalLine->clear();
  878. normalLine->begin(Mesh::PRIMITIVE_LINES, NULL);
  879. normalLine->add_vertex(r_result->collision_point);
  880. normalLine->add_vertex(r_result->collision_point + r_result->collision_normal * 10);
  881. normalLine->end();
  882. #endif
  883. } else {
  884. r_result->remainder = Vector3();
  885. }
  886. }
  887. }
  888. EndExecution:
  889. p_body->get_kinematic_utilities()->resetDefShape();
  890. return hasHit;
  891. }
  892. /// Note: It has a bug when two shapes touches something simultaneously the body is moved too much away
  893. /// (I'm not fixing it because I don't use it).
  894. bool SpaceBullet::recover_from_penetration(RigidBodyBullet *p_body, const btTransform &p_from, btScalar p_maxPenetrationDepth, btScalar p_depenetration_speed, btVector3 &out_recover_position) {
  895. bool penetration = false;
  896. btPairCachingGhostObject *ghost = p_body->get_kinematic_utilities()->m_ghostObject;
  897. for (int kinIndex = p_body->get_kinematic_utilities()->m_shapes.size() - 1; 0 <= kinIndex; --kinIndex) {
  898. const RigidBodyBullet::KinematicShape &kin_shape(p_body->get_kinematic_utilities()->m_shapes[kinIndex]);
  899. if (!kin_shape.is_active()) {
  900. continue;
  901. }
  902. btConvexShape *convexShape = kin_shape.shape;
  903. btTransform shape_xform(kin_shape.transform);
  904. // from local to world
  905. shape_xform.getOrigin() += p_from.getOrigin();
  906. shape_xform.getBasis() *= p_from.getBasis();
  907. // Apply last recovery to avoid doubling the recovering
  908. shape_xform.getOrigin() += out_recover_position;
  909. ghost->setCollisionShape(convexShape);
  910. ghost->setWorldTransform(shape_xform);
  911. btVector3 minAabb, maxAabb;
  912. convexShape->getAabb(shape_xform, minAabb, maxAabb);
  913. dynamicsWorld->getBroadphase()->setAabb(ghost->getBroadphaseHandle(),
  914. minAabb,
  915. maxAabb,
  916. dynamicsWorld->getDispatcher());
  917. dynamicsWorld->getDispatcher()->dispatchAllCollisionPairs(ghost->getOverlappingPairCache(), dynamicsWorld->getDispatchInfo(), dynamicsWorld->getDispatcher());
  918. for (int i = 0; i < ghost->getOverlappingPairCache()->getNumOverlappingPairs(); ++i) {
  919. p_body->get_kinematic_utilities()->m_manifoldArray.resize(0);
  920. btBroadphasePair *collisionPair = &ghost->getOverlappingPairCache()->getOverlappingPairArray()[i];
  921. btCollisionObject *obj0 = static_cast<btCollisionObject *>(collisionPair->m_pProxy0->m_clientObject);
  922. btCollisionObject *obj1 = static_cast<btCollisionObject *>(collisionPair->m_pProxy1->m_clientObject);
  923. if ((obj0 && !obj0->hasContactResponse()) || (obj1 && !obj1->hasContactResponse()))
  924. continue;
  925. // This is not required since the dispatched does all the job
  926. //if (!needsCollision(obj0, obj1))
  927. // continue;
  928. if (collisionPair->m_algorithm)
  929. collisionPair->m_algorithm->getAllContactManifolds(p_body->get_kinematic_utilities()->m_manifoldArray);
  930. for (int j = 0; j < p_body->get_kinematic_utilities()->m_manifoldArray.size(); ++j) {
  931. btPersistentManifold *manifold = p_body->get_kinematic_utilities()->m_manifoldArray[j];
  932. btScalar directionSign = manifold->getBody0() == ghost ? btScalar(-1.0) : btScalar(1.0);
  933. for (int p = 0; p < manifold->getNumContacts(); ++p) {
  934. const btManifoldPoint &pt = manifold->getContactPoint(p);
  935. btScalar dist = pt.getDistance();
  936. if (dist < -p_maxPenetrationDepth) {
  937. penetration = true;
  938. out_recover_position += pt.m_normalWorldOnB * directionSign * (dist + p_maxPenetrationDepth) * p_depenetration_speed;
  939. //print_line("penetrate distance: " + rtos(dist));
  940. }
  941. //else {
  942. // print_line("touching distance: " + rtos(dist));
  943. //}
  944. }
  945. }
  946. }
  947. }
  948. p_body->get_kinematic_utilities()->resetDefShape();
  949. return penetration;
  950. }