space_bullet.cpp 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301
  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. if (!area->is_monitoring())
  540. continue;
  541. /// 1. Reset all states
  542. for (i = area->overlappingObjects.size() - 1; 0 <= i; --i) {
  543. AreaBullet::OverlappingObjectData &otherObj = area->overlappingObjects.write[i];
  544. // This check prevent the overwrite of ENTER state
  545. // if this function is called more times before dispatchCallbacks
  546. if (otherObj.state != AreaBullet::OVERLAP_STATE_ENTER) {
  547. otherObj.state = AreaBullet::OVERLAP_STATE_DIRTY;
  548. }
  549. }
  550. /// 2. Check all overlapping objects using GJK
  551. const btAlignedObjectArray<btCollisionObject *> ghostOverlaps = area->get_bt_ghost()->getOverlappingPairs();
  552. // For each overlapping
  553. for (i = ghostOverlaps.size() - 1; 0 <= i; --i) {
  554. btCollisionObject *overlapped_bt_co = ghostOverlaps[i];
  555. RigidCollisionObjectBullet *otherObject = static_cast<RigidCollisionObjectBullet *>(overlapped_bt_co->getUserPointer());
  556. if (!area->is_transform_changed() && !otherObject->is_transform_changed())
  557. continue;
  558. if (overlapped_bt_co->getUserIndex() == CollisionObjectBullet::TYPE_AREA) {
  559. if (!static_cast<AreaBullet *>(overlapped_bt_co->getUserPointer())->is_monitorable())
  560. continue;
  561. } else if (overlapped_bt_co->getUserIndex() != CollisionObjectBullet::TYPE_RIGID_BODY)
  562. continue;
  563. bool hasOverlap = false;
  564. // For each area shape
  565. for (y = area->get_shape_count() - 1; 0 <= y; --y) {
  566. if (!area->get_bt_shape(y)->isConvex())
  567. continue;
  568. gjk_input.m_transformA = area->get_transform__bullet() * area->get_bt_shape_transform(y);
  569. area_shape = static_cast<btConvexShape *>(area->get_bt_shape(y));
  570. // For each other object shape
  571. for (z = otherObject->get_shape_count() - 1; 0 <= z; --z) {
  572. other_body_shape = static_cast<btCollisionShape *>(otherObject->get_bt_shape(z));
  573. gjk_input.m_transformB = otherObject->get_transform__bullet() * otherObject->get_bt_shape_transform(z);
  574. if (other_body_shape->isConvex()) {
  575. btPointCollector result;
  576. btGjkPairDetector gjk_pair_detector(area_shape, static_cast<btConvexShape *>(other_body_shape), gjk_simplex_solver, gjk_epa_pen_solver);
  577. gjk_pair_detector.getClosestPoints(gjk_input, result, 0);
  578. if (0 >= result.m_distance) {
  579. hasOverlap = true;
  580. goto collision_found;
  581. }
  582. } else {
  583. btCollisionObjectWrapper obA(NULL, area_shape, area->get_bt_ghost(), gjk_input.m_transformA, -1, y);
  584. btCollisionObjectWrapper obB(NULL, other_body_shape, otherObject->get_bt_collision_object(), gjk_input.m_transformB, -1, z);
  585. btCollisionAlgorithm *algorithm = dispatcher->findAlgorithm(&obA, &obB, NULL, BT_CONTACT_POINT_ALGORITHMS);
  586. if (!algorithm)
  587. continue;
  588. GodotDeepPenetrationContactResultCallback contactPointResult(&obA, &obB);
  589. algorithm->processCollision(&obA, &obB, dynamicsWorld->getDispatchInfo(), &contactPointResult);
  590. algorithm->~btCollisionAlgorithm();
  591. dispatcher->freeCollisionAlgorithm(algorithm);
  592. if (contactPointResult.hasHit()) {
  593. hasOverlap = true;
  594. goto collision_found;
  595. }
  596. }
  597. } // ~For each other object shape
  598. } // ~For each area shape
  599. collision_found:
  600. if (!hasOverlap)
  601. continue;
  602. indexOverlap = area->find_overlapping_object(otherObject);
  603. if (-1 == indexOverlap) {
  604. // Not found
  605. area->add_overlap(otherObject);
  606. } else {
  607. // Found
  608. area->put_overlap_as_inside(indexOverlap);
  609. }
  610. }
  611. /// 3. Remove not overlapping
  612. for (i = area->overlappingObjects.size() - 1; 0 <= i; --i) {
  613. // If the overlap has DIRTY state it means that it's no more overlapping
  614. if (area->overlappingObjects[i].state == AreaBullet::OVERLAP_STATE_DIRTY) {
  615. area->put_overlap_as_exit(i);
  616. }
  617. }
  618. }
  619. }
  620. void SpaceBullet::check_body_collision() {
  621. #ifdef DEBUG_ENABLED
  622. reset_debug_contact_count();
  623. #endif
  624. const int numManifolds = dynamicsWorld->getDispatcher()->getNumManifolds();
  625. for (int i = 0; i < numManifolds; ++i) {
  626. btPersistentManifold *contactManifold = dynamicsWorld->getDispatcher()->getManifoldByIndexInternal(i);
  627. // I know this static cast is a bit risky. But I'm checking its type just after it.
  628. // This allow me to avoid a lot of other cast and checks
  629. RigidBodyBullet *bodyA = static_cast<RigidBodyBullet *>(contactManifold->getBody0()->getUserPointer());
  630. RigidBodyBullet *bodyB = static_cast<RigidBodyBullet *>(contactManifold->getBody1()->getUserPointer());
  631. if (CollisionObjectBullet::TYPE_RIGID_BODY == bodyA->getType() && CollisionObjectBullet::TYPE_RIGID_BODY == bodyB->getType()) {
  632. if (!bodyA->can_add_collision() && !bodyB->can_add_collision()) {
  633. continue;
  634. }
  635. const int numContacts = contactManifold->getNumContacts();
  636. /// Since I don't need report all contacts for these objects,
  637. /// So report only the first
  638. #define REPORT_ALL_CONTACTS 0
  639. #if REPORT_ALL_CONTACTS
  640. for (int j = 0; j < numContacts; j++) {
  641. btManifoldPoint &pt = contactManifold->getContactPoint(j);
  642. #else
  643. if (numContacts) {
  644. btManifoldPoint &pt = contactManifold->getContactPoint(0);
  645. #endif
  646. if (
  647. pt.getDistance() <= 0.0 ||
  648. bodyA->was_colliding(bodyB) ||
  649. bodyB->was_colliding(bodyA)) {
  650. Vector3 collisionWorldPosition;
  651. Vector3 collisionLocalPosition;
  652. Vector3 normalOnB;
  653. float appliedImpulse = pt.m_appliedImpulse;
  654. B_TO_G(pt.m_normalWorldOnB, normalOnB);
  655. if (bodyA->can_add_collision()) {
  656. B_TO_G(pt.getPositionWorldOnB(), collisionWorldPosition);
  657. /// pt.m_localPointB Doesn't report the exact point in local space
  658. B_TO_G(pt.getPositionWorldOnB() - contactManifold->getBody1()->getWorldTransform().getOrigin(), collisionLocalPosition);
  659. bodyA->add_collision_object(bodyB, collisionWorldPosition, collisionLocalPosition, normalOnB, appliedImpulse, pt.m_index1, pt.m_index0);
  660. }
  661. if (bodyB->can_add_collision()) {
  662. B_TO_G(pt.getPositionWorldOnA(), collisionWorldPosition);
  663. /// pt.m_localPointA Doesn't report the exact point in local space
  664. B_TO_G(pt.getPositionWorldOnA() - contactManifold->getBody0()->getWorldTransform().getOrigin(), collisionLocalPosition);
  665. bodyB->add_collision_object(bodyA, collisionWorldPosition, collisionLocalPosition, normalOnB * -1, appliedImpulse * -1, pt.m_index0, pt.m_index1);
  666. }
  667. #ifdef DEBUG_ENABLED
  668. if (is_debugging_contacts()) {
  669. add_debug_contact(collisionWorldPosition);
  670. }
  671. #endif
  672. }
  673. }
  674. }
  675. }
  676. }
  677. void SpaceBullet::update_gravity() {
  678. btVector3 btGravity;
  679. G_TO_B(gravityDirection * gravityMagnitude, btGravity);
  680. //dynamicsWorld->setGravity(btGravity);
  681. dynamicsWorld->setGravity(btVector3(0, 0, 0));
  682. if (soft_body_world_info) {
  683. soft_body_world_info->m_gravity = btGravity;
  684. }
  685. }
  686. /// IMPORTANT: Please don't turn it ON this is not managed correctly!!
  687. /// I'm leaving this here just for future tests.
  688. /// Debug motion and normal vector drawing
  689. #define debug_test_motion 0
  690. #define RECOVERING_MOVEMENT_SCALE 0.4
  691. #define RECOVERING_MOVEMENT_CYCLES 4
  692. #if debug_test_motion
  693. #include "scene/3d/immediate_geometry.h"
  694. static ImmediateGeometry *motionVec(NULL);
  695. static ImmediateGeometry *normalLine(NULL);
  696. static Ref<SpatialMaterial> red_mat;
  697. static Ref<SpatialMaterial> blue_mat;
  698. #endif
  699. 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) {
  700. #if debug_test_motion
  701. /// Yes I know this is not good, but I've used it as fast debugging hack.
  702. /// I'm leaving it here just for speedup the other eventual debugs
  703. if (!normalLine) {
  704. motionVec = memnew(ImmediateGeometry);
  705. normalLine = memnew(ImmediateGeometry);
  706. SceneTree::get_singleton()->get_current_scene()->add_child(motionVec);
  707. SceneTree::get_singleton()->get_current_scene()->add_child(normalLine);
  708. motionVec->set_as_toplevel(true);
  709. normalLine->set_as_toplevel(true);
  710. red_mat = Ref<SpatialMaterial>(memnew(SpatialMaterial));
  711. red_mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  712. red_mat->set_line_width(20.0);
  713. red_mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  714. red_mat->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  715. red_mat->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
  716. red_mat->set_albedo(Color(1, 0, 0, 1));
  717. motionVec->set_material_override(red_mat);
  718. blue_mat = Ref<SpatialMaterial>(memnew(SpatialMaterial));
  719. blue_mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  720. blue_mat->set_line_width(20.0);
  721. blue_mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  722. blue_mat->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  723. blue_mat->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
  724. blue_mat->set_albedo(Color(0, 0, 1, 1));
  725. normalLine->set_material_override(blue_mat);
  726. }
  727. #endif
  728. btTransform body_transform;
  729. G_TO_B(p_from, body_transform);
  730. UNSCALE_BT_BASIS(body_transform);
  731. btVector3 initial_recover_motion(0, 0, 0);
  732. { /// Phase one - multi shapes depenetration using margin
  733. for (int t(RECOVERING_MOVEMENT_CYCLES); 0 < t; --t) {
  734. if (!recover_from_penetration(p_body, body_transform, RECOVERING_MOVEMENT_SCALE, p_infinite_inertia, initial_recover_motion)) {
  735. break;
  736. }
  737. }
  738. // Add recover movement in order to make it safe
  739. body_transform.getOrigin() += initial_recover_motion;
  740. }
  741. btVector3 motion;
  742. G_TO_B(p_motion, motion);
  743. { /// phase two - sweep test, from a secure position without margin
  744. const int shape_count(p_body->get_shape_count());
  745. #if debug_test_motion
  746. Vector3 sup_line;
  747. B_TO_G(body_safe_position.getOrigin(), sup_line);
  748. motionVec->clear();
  749. motionVec->begin(Mesh::PRIMITIVE_LINES, NULL);
  750. motionVec->add_vertex(sup_line);
  751. motionVec->add_vertex(sup_line + p_motion * 10);
  752. motionVec->end();
  753. #endif
  754. for (int shIndex = 0; shIndex < shape_count; ++shIndex) {
  755. if (p_body->is_shape_disabled(shIndex)) {
  756. continue;
  757. }
  758. if (!p_body->get_bt_shape(shIndex)->isConvex()) {
  759. // Skip no convex shape
  760. continue;
  761. }
  762. if (p_exclude_raycast_shapes && p_body->get_bt_shape(shIndex)->getShapeType() == CUSTOM_CONVEX_SHAPE_TYPE) {
  763. // Skip rayshape in order to implement custom separation process
  764. continue;
  765. }
  766. btConvexShape *convex_shape_test(static_cast<btConvexShape *>(p_body->get_bt_shape(shIndex)));
  767. btTransform shape_world_from = body_transform * p_body->get_kinematic_utilities()->shapes[shIndex].transform;
  768. btTransform shape_world_to(shape_world_from);
  769. shape_world_to.getOrigin() += motion;
  770. GodotKinClosestConvexResultCallback btResult(shape_world_from.getOrigin(), shape_world_to.getOrigin(), p_body, p_infinite_inertia);
  771. btResult.m_collisionFilterGroup = p_body->get_collision_layer();
  772. btResult.m_collisionFilterMask = p_body->get_collision_mask();
  773. dynamicsWorld->convexSweepTest(convex_shape_test, shape_world_from, shape_world_to, btResult, dynamicsWorld->getDispatchInfo().m_allowedCcdPenetration);
  774. if (btResult.hasHit()) {
  775. /// Since for each sweep test I fix the motion of new shapes in base the recover result,
  776. /// if another shape will hit something it means that has a deepest penetration respect the previous shape
  777. motion *= btResult.m_closestHitFraction;
  778. }
  779. }
  780. body_transform.getOrigin() += motion;
  781. }
  782. bool has_penetration = false;
  783. { /// Phase three - contact test with margin
  784. btVector3 __rec(0, 0, 0);
  785. RecoverResult r_recover_result;
  786. has_penetration = recover_from_penetration(p_body, body_transform, 1, p_infinite_inertia, __rec, &r_recover_result);
  787. // Parse results
  788. if (r_result) {
  789. B_TO_G(motion + initial_recover_motion + __rec, r_result->motion);
  790. if (has_penetration) {
  791. const btRigidBody *btRigid = static_cast<const btRigidBody *>(r_recover_result.other_collision_object);
  792. CollisionObjectBullet *collisionObject = static_cast<CollisionObjectBullet *>(btRigid->getUserPointer());
  793. B_TO_G(motion, r_result->remainder); // is the remaining movements
  794. r_result->remainder = p_motion - r_result->remainder;
  795. B_TO_G(r_recover_result.pointWorld, r_result->collision_point);
  796. B_TO_G(r_recover_result.normal, r_result->collision_normal);
  797. 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
  798. r_result->collider = collisionObject->get_self();
  799. r_result->collider_id = collisionObject->get_instance_id();
  800. r_result->collider_shape = r_recover_result.other_compound_shape_index;
  801. r_result->collision_local_shape = r_recover_result.local_shape_most_recovered;
  802. #if debug_test_motion
  803. Vector3 sup_line2;
  804. B_TO_G(motion, sup_line2);
  805. normalLine->clear();
  806. normalLine->begin(Mesh::PRIMITIVE_LINES, NULL);
  807. normalLine->add_vertex(r_result->collision_point);
  808. normalLine->add_vertex(r_result->collision_point + r_result->collision_normal * 10);
  809. normalLine->end();
  810. #endif
  811. } else {
  812. r_result->remainder = Vector3();
  813. }
  814. }
  815. }
  816. return has_penetration;
  817. }
  818. 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) {
  819. btTransform body_transform;
  820. G_TO_B(p_transform, body_transform);
  821. UNSCALE_BT_BASIS(body_transform);
  822. btVector3 recover_motion(0, 0, 0);
  823. int rays_found = 0;
  824. for (int t(RECOVERING_MOVEMENT_CYCLES); 0 < t; --t) {
  825. 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);
  826. rays_found = MAX(last_ray_index, rays_found);
  827. if (!rays_found) {
  828. break;
  829. } else {
  830. body_transform.getOrigin() += recover_motion;
  831. }
  832. }
  833. //optimize results (remove non colliding)
  834. for (int i = 0; i < rays_found; i++) {
  835. if (r_results[i].collision_depth >= 0) {
  836. rays_found--;
  837. SWAP(r_results[i], r_results[rays_found]);
  838. }
  839. }
  840. B_TO_G(recover_motion, r_recover_motion);
  841. return rays_found;
  842. }
  843. struct RecoverPenetrationBroadPhaseCallback : public btBroadphaseAabbCallback {
  844. private:
  845. const btCollisionObject *self_collision_object;
  846. uint32_t collision_layer;
  847. uint32_t collision_mask;
  848. public:
  849. Vector<btCollisionObject *> result_collision_objects;
  850. public:
  851. RecoverPenetrationBroadPhaseCallback(const btCollisionObject *p_self_collision_object, uint32_t p_collision_layer, uint32_t p_collision_mask) :
  852. self_collision_object(p_self_collision_object),
  853. collision_layer(p_collision_layer),
  854. collision_mask(p_collision_mask) {}
  855. virtual ~RecoverPenetrationBroadPhaseCallback() {}
  856. virtual bool process(const btBroadphaseProxy *proxy) {
  857. btCollisionObject *co = static_cast<btCollisionObject *>(proxy->m_clientObject);
  858. if (co->getInternalType() <= btCollisionObject::CO_RIGID_BODY) {
  859. if (self_collision_object != proxy->m_clientObject && GodotFilterCallback::test_collision_filters(collision_layer, collision_mask, proxy->m_collisionFilterGroup, proxy->m_collisionFilterMask)) {
  860. result_collision_objects.push_back(co);
  861. return true;
  862. }
  863. }
  864. return false;
  865. }
  866. void reset() {
  867. result_collision_objects.clear();
  868. }
  869. };
  870. 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) {
  871. RecoverPenetrationBroadPhaseCallback recover_broad_result(p_body->get_bt_collision_object(), p_body->get_collision_layer(), p_body->get_collision_mask());
  872. btTransform body_shape_position;
  873. btTransform body_shape_position_recovered;
  874. // Broad phase support
  875. btVector3 minAabb, maxAabb;
  876. bool penetration = false;
  877. // For each shape
  878. for (int kinIndex = p_body->get_kinematic_utilities()->shapes.size() - 1; 0 <= kinIndex; --kinIndex) {
  879. recover_broad_result.reset();
  880. const RigidBodyBullet::KinematicShape &kin_shape(p_body->get_kinematic_utilities()->shapes[kinIndex]);
  881. if (!kin_shape.is_active()) {
  882. continue;
  883. }
  884. if (kin_shape.shape->getShapeType() == CUSTOM_CONVEX_SHAPE_TYPE) {
  885. // Skip rayshape in order to implement custom separation process
  886. continue;
  887. }
  888. body_shape_position = p_body_position * kin_shape.transform;
  889. body_shape_position_recovered = body_shape_position;
  890. body_shape_position_recovered.getOrigin() += r_delta_recover_movement;
  891. kin_shape.shape->getAabb(body_shape_position_recovered, minAabb, maxAabb);
  892. dynamicsWorld->getBroadphase()->aabbTest(minAabb, maxAabb, recover_broad_result);
  893. for (int i = recover_broad_result.result_collision_objects.size() - 1; 0 <= i; --i) {
  894. btCollisionObject *otherObject = recover_broad_result.result_collision_objects[i];
  895. if (p_infinite_inertia && !otherObject->isStaticOrKinematicObject()) {
  896. otherObject->activate(); // Force activation of hitten rigid, soft body
  897. continue;
  898. } else if (!p_body->get_bt_collision_object()->checkCollideWith(otherObject) || !otherObject->checkCollideWith(p_body->get_bt_collision_object()))
  899. continue;
  900. if (otherObject->getCollisionShape()->isCompound()) {
  901. // Each convex shape
  902. btCompoundShape *cs = static_cast<btCompoundShape *>(otherObject->getCollisionShape());
  903. for (int x = cs->getNumChildShapes() - 1; 0 <= x; --x) {
  904. if (cs->getChildShape(x)->isConvex()) {
  905. 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)) {
  906. penetration = true;
  907. }
  908. } else {
  909. 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)) {
  910. penetration = true;
  911. }
  912. }
  913. }
  914. } else if (otherObject->getCollisionShape()->isConvex()) { /// Execute GJK test against object shape
  915. 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)) {
  916. penetration = true;
  917. }
  918. } else {
  919. 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)) {
  920. penetration = true;
  921. }
  922. }
  923. }
  924. }
  925. return penetration;
  926. }
  927. 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) {
  928. // Initialize GJK input
  929. btGjkPairDetector::ClosestPointInput gjk_input;
  930. gjk_input.m_transformA = p_transformA;
  931. gjk_input.m_transformA.getOrigin() += r_delta_recover_movement;
  932. gjk_input.m_transformB = p_transformB;
  933. // Perform GJK test
  934. btPointCollector result;
  935. btGjkPairDetector gjk_pair_detector(p_shapeA, p_shapeB, gjk_simplex_solver, gjk_epa_pen_solver);
  936. gjk_pair_detector.getClosestPoints(gjk_input, result, 0);
  937. if (0 > result.m_distance) {
  938. // Has penetration
  939. r_delta_recover_movement += result.m_normalOnBInWorld * (result.m_distance * -1 * p_recover_movement_scale);
  940. if (r_recover_result) {
  941. if (result.m_distance < r_recover_result->penetration_distance) {
  942. r_recover_result->hasPenetration = true;
  943. r_recover_result->other_collision_object = p_objectB;
  944. r_recover_result->other_compound_shape_index = p_shapeId_B;
  945. r_recover_result->penetration_distance = result.m_distance;
  946. r_recover_result->pointWorld = result.m_pointInWorld;
  947. r_recover_result->normal = result.m_normalOnBInWorld;
  948. }
  949. }
  950. return true;
  951. }
  952. return false;
  953. }
  954. 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) {
  955. /// Contact test
  956. btTransform tA(p_transformA);
  957. tA.getOrigin() += r_delta_recover_movement;
  958. btCollisionObjectWrapper obA(NULL, p_shapeA, p_objectA, tA, -1, p_shapeId_A);
  959. btCollisionObjectWrapper obB(NULL, p_shapeB, p_objectB, p_transformB, -1, p_shapeId_B);
  960. btCollisionAlgorithm *algorithm = dispatcher->findAlgorithm(&obA, &obB, NULL, BT_CONTACT_POINT_ALGORITHMS);
  961. if (algorithm) {
  962. GodotDeepPenetrationContactResultCallback contactPointResult(&obA, &obB);
  963. //discrete collision detection query
  964. algorithm->processCollision(&obA, &obB, dynamicsWorld->getDispatchInfo(), &contactPointResult);
  965. algorithm->~btCollisionAlgorithm();
  966. dispatcher->freeCollisionAlgorithm(algorithm);
  967. if (contactPointResult.hasHit()) {
  968. r_delta_recover_movement += contactPointResult.m_pointNormalWorld * (contactPointResult.m_penetration_distance * -1 * p_recover_movement_scale);
  969. if (r_recover_result) {
  970. if (contactPointResult.m_penetration_distance < r_recover_result->penetration_distance) {
  971. r_recover_result->hasPenetration = true;
  972. r_recover_result->other_collision_object = p_objectB;
  973. r_recover_result->other_compound_shape_index = p_shapeId_B;
  974. r_recover_result->penetration_distance = contactPointResult.m_penetration_distance;
  975. r_recover_result->pointWorld = contactPointResult.m_pointWorld;
  976. r_recover_result->normal = contactPointResult.m_pointNormalWorld;
  977. }
  978. }
  979. return true;
  980. }
  981. }
  982. return false;
  983. }
  984. 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) {
  985. RecoverPenetrationBroadPhaseCallback recover_broad_result(p_body->get_bt_collision_object(), p_body->get_collision_layer(), p_body->get_collision_mask());
  986. btTransform body_shape_position;
  987. btTransform body_shape_position_recovered;
  988. // Broad phase support
  989. btVector3 minAabb, maxAabb;
  990. int ray_index = 0;
  991. // For each shape
  992. for (int kinIndex = p_body->get_kinematic_utilities()->shapes.size() - 1; 0 <= kinIndex; --kinIndex) {
  993. recover_broad_result.reset();
  994. if (ray_index >= p_result_max) {
  995. break;
  996. }
  997. const RigidBodyBullet::KinematicShape &kin_shape(p_body->get_kinematic_utilities()->shapes[kinIndex]);
  998. if (!kin_shape.is_active()) {
  999. continue;
  1000. }
  1001. if (kin_shape.shape->getShapeType() != CUSTOM_CONVEX_SHAPE_TYPE) {
  1002. continue;
  1003. }
  1004. body_shape_position = p_body_position * kin_shape.transform;
  1005. body_shape_position_recovered = body_shape_position;
  1006. body_shape_position_recovered.getOrigin() += r_delta_recover_movement;
  1007. kin_shape.shape->getAabb(body_shape_position_recovered, minAabb, maxAabb);
  1008. dynamicsWorld->getBroadphase()->aabbTest(minAabb, maxAabb, recover_broad_result);
  1009. for (int i = recover_broad_result.result_collision_objects.size() - 1; 0 <= i; --i) {
  1010. btCollisionObject *otherObject = recover_broad_result.result_collision_objects[i];
  1011. if (p_infinite_inertia && !otherObject->isStaticOrKinematicObject()) {
  1012. otherObject->activate(); // Force activation of hitten rigid, soft body
  1013. continue;
  1014. } else if (!p_body->get_bt_collision_object()->checkCollideWith(otherObject) || !otherObject->checkCollideWith(p_body->get_bt_collision_object()))
  1015. continue;
  1016. if (otherObject->getCollisionShape()->isCompound()) {
  1017. // Each convex shape
  1018. btCompoundShape *cs = static_cast<btCompoundShape *>(otherObject->getCollisionShape());
  1019. for (int x = cs->getNumChildShapes() - 1; 0 <= x; --x) {
  1020. RecoverResult r_recover_result;
  1021. 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)) {
  1022. const btRigidBody *btRigid = static_cast<const btRigidBody *>(otherObject);
  1023. CollisionObjectBullet *collisionObject = static_cast<CollisionObjectBullet *>(otherObject->getUserPointer());
  1024. r_results[ray_index].collision_depth = r_recover_result.penetration_distance;
  1025. B_TO_G(r_recover_result.pointWorld, r_results[ray_index].collision_point);
  1026. B_TO_G(r_recover_result.normal, r_results[ray_index].collision_normal);
  1027. B_TO_G(btRigid->getVelocityInLocalPoint(r_recover_result.pointWorld - btRigid->getWorldTransform().getOrigin()), r_results[ray_index].collider_velocity);
  1028. r_results[ray_index].collision_local_shape = kinIndex;
  1029. r_results[ray_index].collider_id = collisionObject->get_instance_id();
  1030. r_results[ray_index].collider = collisionObject->get_self();
  1031. r_results[ray_index].collider_shape = r_recover_result.other_compound_shape_index;
  1032. }
  1033. }
  1034. }
  1035. }
  1036. ++ray_index;
  1037. }
  1038. return ray_index;
  1039. }